Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_NET_H
7#define BITCOIN_NET_H
8
9#include <bip324.h>
10#include <chainparams.h>
11#include <common/bloom.h>
12#include <compat/compat.h>
13#include <consensus/amount.h>
14#include <crypto/siphash.h>
15#include <hash.h>
16#include <i2p.h>
18#include <net_permissions.h>
19#include <netaddress.h>
20#include <netbase.h>
21#include <netgroup.h>
24#include <policy/feerate.h>
25#include <protocol.h>
26#include <random.h>
27#include <semaphore_grant.h>
28#include <span.h>
29#include <streams.h>
30#include <sync.h>
31#include <uint256.h>
32#include <util/check.h>
33#include <util/not_null.h>
34#include <util/sock.h>
35#include <util/threadinterrupt.h>
36
37#include <atomic>
38#include <condition_variable>
39#include <cstdint>
40#include <deque>
41#include <functional>
42#include <list>
43#include <map>
44#include <memory>
45#include <optional>
46#include <queue>
47#include <string_view>
48#include <thread>
49#include <unordered_set>
50#include <vector>
51
52class AddrMan;
53class BanMan;
54class CChainParams;
55class CNode;
56class CScheduler;
57struct bilingual_str;
58
60inline constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
62inline constexpr auto FEELER_INTERVAL = 2min;
64inline constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
66inline constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
68inline constexpr unsigned int MAX_SUBVERSION_LENGTH = 256;
70inline constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
72inline constexpr int MAX_ADDNODE_CONNECTIONS = 8;
74inline constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
76inline constexpr int MAX_FEELER_CONNECTIONS = 1;
78inline constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};
80inline constexpr bool DEFAULT_LISTEN = true;
82inline constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS{200};
84inline constexpr int MAX_PEER_CONNECTIONS{2'000};
86inline constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT{50};
88inline const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
90inline constexpr bool DEFAULT_BLOCKSONLY = false;
94inline constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
96inline constexpr int NUM_FDS_MESSAGE_CAPTURE = 1;
98inline constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
99
100inline constexpr bool DEFAULT_FORCEDNSSEED{false};
101inline constexpr bool DEFAULT_DNSSEED{true};
102inline constexpr bool DEFAULT_FIXEDSEEDS{true};
103inline constexpr size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
104inline constexpr size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
105
106inline constexpr bool DEFAULT_V2_TRANSPORT{true};
107
109
114
121
122class CNodeStats;
124
126 CSerializedNetMsg() = default;
129 // No implicit copying, only moves.
132
134 {
136 copy.data = data;
137 copy.m_type = m_type;
138 return copy;
139 }
140
141 std::vector<unsigned char> data;
142 std::string m_type;
143
145 size_t GetMemoryUsage() const noexcept;
146};
147
153void Discover();
154
156
157enum
158{
159 LOCAL_NONE, // unknown
160 LOCAL_IF, // address a local interface listens on
161 LOCAL_BIND, // address explicit bound to
162 LOCAL_MAPPED, // address reported by PCP
163 LOCAL_MANUAL, // address explicitly specified (-externalip=)
164
167
169std::optional<CService> GetLocalAddrForPeer(CNode& node);
170
171void ClearLocal();
172bool AddLocal(const CService& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
173bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
174void RemoveLocal(const CService& addr);
175bool SeenLocal(const CService& addr);
176bool IsLocal(const CService& addr);
177CService GetLocalAddress(const CNode& peer);
178
179extern bool fDiscover;
180extern bool fListen;
181
183extern std::string strSubVersion;
184
189
191extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
192
193extern const std::string NET_MESSAGE_TYPE_OTHER;
194using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
195
197{
198public:
202 std::chrono::seconds m_last_tx_time;
203 std::chrono::seconds m_last_block_time;
205 std::string m_addr_name;
207 std::string cleanSubVer;
209 // We requested high bandwidth connection to peer
211 // Peer requested high bandwidth connection
218 NodeClock::duration m_last_ping_time;
219 NodeClock::duration m_min_ping_time;
220 // Our address, as reported by the peer
221 std::string addrLocal;
222 // Address of this peer
224 // Bind address of our side of the connection
226 // Network the peer connected through
233 std::string m_session_id;
234};
235
236
242{
243public:
247 uint32_t m_message_size{0};
248 uint32_t m_raw_message_size{0};
249 std::string m_type;
250
251 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
252 // Only one CNetMessage object will exist for the same message on either
253 // the receive or processing queue. For performance reasons we therefore
254 // delete the copy constructor and assignment operator to avoid the
255 // possibility of copying CNetMessage objects.
257 CNetMessage(const CNetMessage&) = delete;
260
262 size_t GetMemoryUsage() const noexcept;
263};
264
267public:
268 virtual ~Transport() = default;
269
270 struct Info
271 {
273 std::optional<uint256> session_id;
274 };
275
277 virtual Info GetInfo() const noexcept = 0;
278
279 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
280 // agnostic CNetMessage (message type & payload) objects.
281
283 virtual bool ReceivedMessageComplete() const = 0;
284
291 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
292
300 virtual CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) = 0;
301
302 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
303
310 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
311
320 std::span<const uint8_t> /*to_send*/,
321 bool /*more*/,
322 const std::string& /*m_type*/
323 >;
324
360 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
361
368 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
369
371 virtual size_t GetSendMemoryUsage() const noexcept = 0;
372
373 // 3. Miscellaneous functions.
374
376 virtual bool ShouldReconnectV1() const noexcept = 0;
377};
378
380{
381private:
383 const NodeId m_node_id; // Only for logging
385 mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
386 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
387 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
388 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
389 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
390 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
391 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
392 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
393
394 const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
395 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
396 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
397
398 void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
399 AssertLockHeld(m_recv_mutex);
400 vRecv.clear();
401 hdrbuf.clear();
402 hdrbuf.resize(24);
403 in_data = false;
404 nHdrPos = 0;
405 nDataPos = 0;
406 data_hash.SetNull();
407 hasher.Reset();
408 }
409
410 bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
411 {
412 AssertLockHeld(m_recv_mutex);
413 if (!in_data) return false;
414 return hdr.nMessageSize == nDataPos;
415 }
416
420 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
424 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
426 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
427
428public:
429 explicit V1Transport(NodeId node_id) noexcept;
430
432 {
433 AssertLockNotHeld(m_recv_mutex);
434 return WITH_LOCK(m_recv_mutex, return CompleteInternal());
435 }
436
437 Info GetInfo() const noexcept override;
438
439 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
440 {
441 AssertLockNotHeld(m_recv_mutex);
442 LOCK(m_recv_mutex);
443 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
444 if (ret < 0) {
445 Reset();
446 } else {
447 msg_bytes = msg_bytes.subspan(ret);
448 }
449 return ret >= 0;
450 }
451
452 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
453
454 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
455 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
456 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
457 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
458 bool ShouldReconnectV1() const noexcept override { return false; }
459};
460
461class V2Transport final : public Transport
462{
463private:
467 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
468
471 static constexpr size_t V1_PREFIX_LEN = 16;
472
473 // The sender side and receiver side of V2Transport are state machines that are transitioned
474 // through, based on what has been received. The receive state corresponds to the contents of,
475 // and bytes received to, the receive buffer. The send state controls what can be appended to
476 // the send buffer and what can be sent from it.
477
492 enum class RecvState : uint8_t {
498 KEY_MAYBE_V1,
499
505 KEY,
506
513 GARB_GARBTERM,
514
523 VERSION,
524
530 APP,
531
536 APP_READY,
537
541 V1,
542 };
543
557 enum class SendState : uint8_t {
564 MAYBE_V1,
565
571 AWAITING_KEY,
572
579 READY,
580
584 V1,
585 };
586
590 const bool m_initiating;
595
597 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
600 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
602 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
604 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
606 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
609
612 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
614 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
616 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
618 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
620 std::string m_send_type GUARDED_BY(m_send_mutex);
624 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
625
627 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
629 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
631 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
633 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
635 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
637 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
639 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
641 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
643 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
644
645public:
646 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
647
653 V2Transport(NodeId nodeid, bool initiating) noexcept;
654
656 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
657
658 // Receive side functions.
659 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
660 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
661 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
662
663 // Send side functions.
664 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
665 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
666 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
667 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
668
669 // Miscellaneous functions.
670 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
671 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
672};
673
675{
677 std::optional<Proxy> proxy_override = {};
678 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
679 bool prefer_evict = false;
680 size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
681 bool use_v2transport = false;
682};
683
685class CNode
686{
687public:
691
693
702 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
703
705 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
707 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
709 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
713
714 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
715
716 std::atomic<NodeClock::time_point> m_last_send{NodeClock::epoch};
717 std::atomic<NodeClock::time_point> m_last_recv{NodeClock::epoch};
720
722 const std::optional<Proxy> m_proxy_override;
723
724 // Address of this peer
726 // Bind address of our side of the connection
728 const std::string m_addr_name;
730 const std::string m_dest;
732 const bool m_inbound_onion;
733 std::atomic<int> nVersion{0};
739 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
740 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
742 return NetPermissions::HasFlag(m_permission_flags, permission);
743 }
745 std::atomic_bool fSuccessfullyConnected{false};
746 // Setting fDisconnect to true will cause the node to be disconnected the
747 // next time DisconnectNodes() runs
748 std::atomic_bool fDisconnect{false};
750 std::atomic<int> nRefCount{0};
751
753 std::atomic_bool fPauseRecv{false};
754 std::atomic_bool fPauseSend{false};
756 std::atomic<NodeClock::time_point> m_pause_send_since{NodeClock::epoch};
757
761
763
765 void MarkReceivedMsgsForProcessing()
766 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
767
773 std::optional<std::pair<CNetMessage, bool>> PollMessage()
774 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
775
777 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
779 {
780 mapSendBytesPerMsgType[msg_type] += sent_bytes;
781 }
782
784 switch (m_conn_type) {
787 return true;
793 return false;
794 } // no default case, so the compiler can warn about missing cases
795
796 assert(false);
797 }
798
799 bool IsFullOutboundConn() const {
800 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
801 }
802
803 bool IsManualConn() const {
804 return m_conn_type == ConnectionType::MANUAL;
805 }
806
808 {
809 switch (m_conn_type) {
815 return false;
818 return true;
819 } // no default case, so the compiler can warn about missing cases
820
821 assert(false);
822 }
823
824 bool IsBlockOnlyConn() const {
825 return m_conn_type == ConnectionType::BLOCK_RELAY;
826 }
827
828 bool IsFeelerConn() const {
829 return m_conn_type == ConnectionType::FEELER;
830 }
831
832 bool IsAddrFetchConn() const {
833 return m_conn_type == ConnectionType::ADDR_FETCH;
834 }
835
837 {
838 return m_conn_type == ConnectionType::PRIVATE_BROADCAST;
839 }
840
844 {
845 return IsPrivateBroadcastConn() ? WTXID_RELAY_VERSION : PROTOCOL_VERSION;
846 }
847
848 bool IsInboundConn() const {
849 return m_conn_type == ConnectionType::INBOUND;
850 }
851
853 switch (m_conn_type) {
857 return false;
862 return true;
863 } // no default case, so the compiler can warn about missing cases
864
865 assert(false);
866 }
867
878 Network ConnectedThroughNetwork() const;
879
881 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
882
883 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
884 std::atomic<bool> m_bip152_highbandwidth_to{false};
885 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
886 std::atomic<bool> m_bip152_highbandwidth_from{false};
887
889 std::atomic_bool m_has_all_wanted_services{false};
890
893 std::atomic_bool m_relays_txs{false};
894
897 std::atomic_bool m_bloom_filter_loaded{false};
898
904 std::atomic<std::chrono::seconds> m_last_block_time{0s};
905
910 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
911
913 std::atomic<NodeClock::duration> m_last_ping_time{0us};
914
917 std::atomic<NodeClock::duration> m_min_ping_time{NodeClock::duration::max()};
918
919 CNode(NodeId id,
920 std::shared_ptr<Sock> sock,
921 const CAddress& addrIn,
924 const CService& addrBindIn,
925 const std::string& addrNameIn,
927 bool inbound_onion,
929 CNodeOptions&& node_opts = {});
930 CNode(const CNode&) = delete;
931 CNode& operator=(const CNode&) = delete;
932
933 NodeId GetId() const {
934 return id;
935 }
936
938 return nLocalHostNonce;
939 }
940
941 int GetRefCount() const
942 {
943 assert(nRefCount >= 0);
944 return nRefCount;
945 }
946
956 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
957
959 {
960 Assume(m_greatest_common_version == INIT_PROTO_VERSION);
961 m_greatest_common_version = greatest_common_version;
962 }
964 {
965 return m_greatest_common_version;
966 }
967
968 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
970 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
971
972 CNode* AddRef()
973 {
974 nRefCount++;
975 return this;
976 }
977
978 void Release()
979 {
980 nRefCount--;
981 }
982
983 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
984
985 void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
986
987 std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
988
994 std::string LogPeer() const;
995
1001 std::string DisconnectMsg() const;
1002
1004 void PongReceived(NodeClock::duration ping_time)
1005 {
1006 m_last_ping_time = ping_time;
1007 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
1008 }
1009
1010private:
1011 const NodeId id;
1013 std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1014
1015 const size_t m_recv_flood_size;
1016 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1017
1019 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1020 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1021
1022 // Our address, as reported by the peer
1023 CService m_addr_local GUARDED_BY(m_addr_local_mutex);
1025
1026 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1027 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1028
1039 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1040};
1041
1046{
1047public:
1050
1053
1055 virtual void FinalizeNode(const CNode& node) = 0;
1056
1061 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1062
1070 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1071
1078 virtual bool SendMessages(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1079
1080
1081protected:
1087};
1088
1090{
1091public:
1092
1093 struct Options
1094 {
1095 ServiceFlags m_local_services = NODE_NONE;
1096 int m_max_automatic_connections = DEFAULT_MAX_PEER_CONNECTIONS;
1097 int m_full_relay_inbound_percent = DEFAULT_FULL_RELAY_INBOUND_PCT;
1099 NetEventsInterface* m_msgproc = nullptr;
1100 BanMan* m_banman = nullptr;
1101 unsigned int nSendBufferMaxSize = 0;
1102 unsigned int nReceiveFloodSize = 0;
1103 uint64_t nMaxOutboundLimit = 0;
1104 int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1105 std::vector<std::string> vSeedNodes;
1106 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1107 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1108 std::vector<NetWhitebindPermissions> vWhiteBinds;
1109 std::vector<CService> vBinds;
1110 std::vector<CService> onion_binds;
1114 bool m_use_addrman_outgoing = true;
1115 std::vector<std::string> m_specified_outgoing;
1116 std::vector<std::string> m_added_nodes;
1118 bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1119 bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1120 bool m_capture_messages = false;
1121 };
1122
1123 void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1124 {
1125 AssertLockNotHeld(m_total_bytes_sent_mutex);
1126
1127 m_local_services = connOptions.m_local_services;
1128 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1129 m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1130 m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1131 m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1132 m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1133 m_max_inbound_full_relay = std::max(0, static_cast<int>(connOptions.m_full_relay_inbound_percent / 100.0 * m_max_inbound));
1134 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1135 m_client_interface = connOptions.uiInterface;
1136 m_banman = connOptions.m_banman;
1137 m_msgproc = connOptions.m_msgproc;
1138 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1139 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1140 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1141 {
1142 LOCK(m_total_bytes_sent_mutex);
1143 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1144 }
1145 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1146 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1147 {
1148 LOCK(m_added_nodes_mutex);
1149 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1150 // peer doesn't support it or immediately disconnects us for another reason.
1151 const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1152 for (const std::string& added_node : connOptions.m_added_nodes) {
1153 m_added_node_params.push_back({added_node, use_v2transport});
1154 }
1155 }
1156 m_onion_binds = connOptions.onion_binds;
1157 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1158 whitelist_relay = connOptions.whitelist_relay;
1159 m_capture_messages = connOptions.m_capture_messages;
1160 }
1161
1162 // test only
1163 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1164
1167 AddrMan& addrman,
1168 const NetGroupManager& netgroupman,
1169 const CChainParams& params,
1170 bool network_active = true,
1171 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1172
1173 ~CConnman();
1174
1175 bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc, !m_anchors_mutex);
1176
1177 void StopThreads();
1178 void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_anchors_mutex);
1179 void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_anchors_mutex)
1180 {
1181 AssertLockNotHeld(m_nodes_mutex);
1182 AssertLockNotHeld(m_reconnections_mutex);
1185 };
1186
1187 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1188 bool GetNetworkActive() const { return fNetworkActive; };
1189 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1190 void SetNetworkActive(bool active) EXCLUSIVE_LOCKS_REQUIRED(!m_anchors_mutex, !m_nodes_mutex);
1191
1204 bool OpenNetworkConnection(const CAddress& addrConnect,
1205 bool fCountFailure,
1207 const char* pszDest,
1208 ConnectionType conn_type,
1209 bool use_v2transport,
1210 const std::optional<Proxy>& proxy_override)
1211 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1212
1215 {
1216 public:
1225 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1226
1231 std::counting_semaphore<> m_sem_conn_max{MAX_PRIVATE_BROADCAST_CONNECTIONS};
1232
1242 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1243
1245 size_t NumToOpen() const;
1246
1252 void NumToOpenAdd(size_t n);
1253
1260 size_t NumToOpenSub(size_t n);
1261
1263 void NumToOpenWait() const;
1264
1265 protected:
1271 std::optional<Proxy> ProxyForIPv4or6() const;
1272
1274 std::atomic_size_t m_num_to_open{0};
1275
1276 friend struct ConnmanTestMsg;
1277 } m_private_broadcast;
1278
1279 bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1280 void ASMapHealthCheck();
1281
1282 // alias for thread safety annotations only, not defined
1283 Mutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);
1284
1285 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1286
1287 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1288
1289 using NodeFn = std::function<void(CNode*)>;
1290 void ForEachNode(const NodeFn& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1291 {
1292 LOCK(m_nodes_mutex);
1293 for (auto&& node : m_nodes) {
1294 if (NodeFullyConnected(node))
1295 func(node);
1296 }
1297 };
1298
1299 void ForEachNode(const NodeFn& func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
1300 {
1301 LOCK(m_nodes_mutex);
1302 for (auto&& node : m_nodes) {
1303 if (NodeFullyConnected(node))
1304 func(node);
1305 }
1306 };
1307
1308 // Addrman functions
1320 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1335 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1336
1337 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1338 // a peer that is better than all our current peers.
1339 void SetTryNewOutboundPeer(bool flag);
1340 bool GetTryNewOutboundPeer() const;
1341
1342 void StartExtraBlockRelayPeers();
1343
1344 // Count the number of full-relay peer we have.
1345 int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1346 // Return the number of outbound peers we have in excess of our target (eg,
1347 // if we previously called SetTryNewOutboundPeer(true), and have since set
1348 // to false, we may have extra peers that we wish to disconnect). This may
1349 // return a value less than (num_outbound_connections - num_outbound_slots)
1350 // in cases where some outbound connections are not yet fully connected, or
1351 // not yet fully disconnected.
1352 int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1353 // Count the number of block-relay-only peers we have over our limit.
1354 int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1364 bool EvictTxPeerIfFull(std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1365
1366 bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1367 bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1368 bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1369 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const
1370 EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_nodes_mutex);
1371
1385 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)
1386 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1387
1388 size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1389 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1390 uint32_t GetMappedAS(const CNetAddr& addr) const;
1391 void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1392 bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1393 bool DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast = true) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1394 bool DisconnectNode(const CNetAddr& addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1395 bool DisconnectNode(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1396
1403 ServiceFlags GetLocalServices() const;
1404
1407 void AddLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services | services); };
1408 void RemoveLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services & ~services); }
1409
1410 uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1411 std::chrono::seconds GetMaxOutboundTimeframe() const;
1412
1416 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1417
1420 uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1421
1422 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1423
1424 uint64_t GetTotalBytesRecv() const;
1425 uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1426
1428 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1429
1430 void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1431
1433 bool ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const;
1434
1435 bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1436
1437private:
1439 public:
1440 std::shared_ptr<Sock> sock;
1443 : sock{sock_}, m_permissions{permissions_}
1444 {
1445 }
1446
1447 private:
1449 };
1450
1453 std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
1454
1456 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1457 bool InitBinds(const Options& options);
1458
1460 void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex,
1461 !m_nodes_mutex,
1462 !m_reconnections_mutex,
1463 !m_unused_i2p_sessions_mutex);
1464
1465 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1466
1467 void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex,
1468 !m_nodes_mutex,
1469 !m_unused_i2p_sessions_mutex);
1470
1472 void ThreadOpenConnections(std::vector<std::string> connect, std::span<const std::string> seed_nodes)
1473 EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex,
1474 !m_addr_fetches_mutex,
1475 !m_nodes_mutex,
1476 !m_reconnections_mutex,
1477 !m_unused_i2p_sessions_mutex,
1478 !m_anchors_mutex);
1479
1481 void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc);
1483 void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1484 void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1485 void AcceptConnection(const ListenSocket& hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1486
1495 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1496 NetPermissionFlags permission_flags,
1497 const CService& addr_bind,
1498 const CService& addr)
1499 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1500
1501 void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);
1502 void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1504 bool InactivityCheck(const CNode& node, NodeClock::time_point now) const;
1505
1511 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1512
1516 void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_total_bytes_sent_mutex, !mutexMsgProc);
1517
1523 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1524 const Sock::EventsPerSock& events_per_sock)
1525 EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1526
1531 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
1532 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1533
1535 void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex);
1537 void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
1538
1539 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1540
1548 bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1549
1557 bool AlreadyConnectedToAddressPort(const CService& addr_port) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1558
1562 bool AlreadyConnectedToAddress(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1563
1570 bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1571
1582 CNode* ConnectNode(CAddress addrConnect,
1583 const char* pszDest,
1584 bool fCountFailure,
1585 ConnectionType conn_type,
1586 bool use_v2transport,
1587 const std::optional<Proxy>& proxy_override)
1588 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1589
1590 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1591
1592 void DeleteNode(CNode* pnode);
1593
1594 NodeId GetNewNodeId();
1595
1597 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1598
1599 void DumpAddresses();
1600
1601 // Network stats
1602 void RecordBytesRecv(uint64_t bytes);
1603 void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1604
1609 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1610
1614 std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1615
1626 bool MaybePickPreferredNetwork(std::optional<Network>& network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1627
1628 // Whether the node should be passed out in ForEach* callbacks
1629 static bool NodeFullyConnected(const CNode* pnode);
1630
1631 uint16_t GetDefaultPort(Network net) const;
1632 uint16_t GetDefaultPort(const std::string& addr) const;
1633
1634 // Network usage totals
1635 mutable Mutex m_total_bytes_sent_mutex;
1636 std::atomic<uint64_t> nTotalBytesRecv{0};
1637 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1638
1639 // outbound limit & stats
1641 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1642 uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
1643
1644 // P2P timeout in seconds
1645 std::chrono::seconds m_peer_connect_timeout;
1646
1647 // Whitelisted ranges. Any node connecting from these is automatically
1648 // whitelisted (as well as those connecting to whitelisted binds).
1649 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1650 // Whitelisted ranges for outgoing connections.
1651 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1652
1653 unsigned int nSendBufferMaxSize{0};
1654 unsigned int nReceiveFloodSize{0};
1655
1656 std::vector<ListenSocket> vhListenSocket;
1657 std::atomic<bool> fNetworkActive{true};
1658 bool fAddressesInitialized{false};
1659 std::reference_wrapper<AddrMan> addrman;
1661 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1663
1664 // connection string and whether to use v2 p2p
1665 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1666
1668 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1669 std::list<CNode*> m_nodes_disconnected;
1671 std::atomic<NodeId> nLastNodeId{0};
1672 unsigned int nPrevNodeCount{0};
1673
1674 // Stores number of full-tx connections (outbound and manual) per network
1675 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1676
1684 std::vector<CAddress> m_addrs_response_cache;
1685 std::chrono::microseconds m_cache_entry_expiration{0};
1686 };
1687
1702 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1703
1715 std::atomic<ServiceFlags> m_local_services;
1716
1717 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1718 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1719
1726
1727 /*
1728 * Maximum number of peers by connection type. Might vary from defaults
1729 * based on -maxconnections init value.
1730 */
1731
1732 // How many full-relay (tx, block, addr) outbound peers we want
1734
1735 // How many block-relay only outbound peers we want
1736 // We do not relay tx or addr messages with these peers
1738
1739 int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1740 int m_max_feeler{MAX_FEELER_CONNECTIONS};
1744
1750
1757 std::vector<CAddress> m_anchors GUARDED_BY(m_anchors_mutex);
1758
1760 const uint64_t nSeed0, nSeed1;
1761
1763 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1764
1765 std::condition_variable condMsgProc;
1767 std::atomic<bool> flagInterruptMsgProc{false};
1768
1773 const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1774
1780 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1781
1789
1794
1799 std::atomic_bool m_start_extra_block_relay_peers{false};
1800
1805 std::vector<CService> m_onion_binds;
1806
1812
1818
1822 bool m_capture_messages{false};
1823
1828
1836 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1837
1842
1853
1857 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1858
1860 void PerformReconnections()
1861 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1862
1867 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1868
1874 {
1875 public:
1876 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1877 EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
1878 {
1879 {
1880 LOCK(connman.m_nodes_mutex);
1881 m_nodes_copy = connman.m_nodes;
1882 for (auto& node : m_nodes_copy) {
1883 node->AddRef();
1884 }
1885 }
1886 if (shuffle) {
1887 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1888 }
1889 }
1890
1892 {
1893 for (auto& node : m_nodes_copy) {
1894 node->Release();
1895 }
1896 }
1897
1898 const std::vector<CNode*>& Nodes() const
1899 {
1900 return m_nodes_copy;
1901 }
1902
1903 private:
1904 std::vector<CNode*> m_nodes_copy;
1905 };
1906
1908
1909 friend struct ConnmanTestMsg;
1910};
1911
1913extern std::function<void(const CAddress& addr,
1914 const std::string& msg_type,
1915 std::span<const unsigned char> data,
1916 bool is_incoming)>
1918
1919#endif // BITCOIN_NET_H
int ret
int flags
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition check.h:131
Stochastic address manager.
Definition addrman.h:110
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition bip324.h:22
A CService with information about it as peer.
Definition protocol.h:387
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:77
Signals for UI communication.
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition net.h:1874
const std::vector< CNode * > & Nodes() const
Definition net.h:1898
NodesSnapshot(const CConnman &connman, bool shuffle) EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
Definition net.h:1876
std::vector< CNode * > m_nodes_copy
Definition net.h:1904
Group of private broadcast related members.
Definition net.h:1215
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition net.h:1817
std::condition_variable condMsgProc
Definition net.h:1765
std::thread threadMessageHandler
Definition net.h:1786
void RemoveLocalServices(ServiceFlags services)
Definition net.h:1408
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1649
CClientUIInterface * m_client_interface
Definition net.h:1746
std::reference_wrapper< AddrMan > addrman
Definition net.h:1659
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
int m_max_inbound
Definition net.h:1742
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
int m_max_outbound_block_relay
Definition net.h:1737
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
void SetCaptureMessages(bool cap)
Definition net.h:1163
std::thread threadI2PAcceptIncoming
Definition net.h:1787
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
int m_max_automatic_outbound
Definition net.h:1741
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int m_max_automatic_connections
Maximum number of automatic connections permitted, excluding manual connections but including inbound...
Definition net.h:1725
BanMan * m_banman
Pointer to this node's banman.
Definition net.h:1749
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1640
std::thread threadDNSAddressSeed
Definition net.h:1782
void ForEachNode(const NodeFn &func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.h:1299
const NetGroupManager & m_netgroupman
Definition net.h:1660
std::vector< CAddress > m_anchors GUARDED_BY(m_anchors_mutex)
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition net.h:1811
std::chrono::seconds m_peer_connect_timeout
Definition net.h:1645
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay This t...
Definition net.h:1793
std::vector< ListenSocket > vhListenSocket
Definition net.h:1656
std::thread threadOpenConnections
Definition net.h:1785
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition net.h:1715
Mutex m_addr_fetches_mutex
Definition net.h:1662
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition net.h:1841
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1760
std::queue< std::unique_ptr< i2p::sam::Session > > m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex)
A pool of created I2P SAM transient sessions that should be used instead of creating new ones in orde...
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition net.h:1717
const CChainParams & m_params
Definition net.h:1907
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition net.h:1773
std::thread threadPrivateBroadcast
Definition net.h:1788
Mutex mutexMsgProc
Definition net.h:1766
std::thread threadOpenAddedConnections
Definition net.h:1784
Mutex m_added_nodes_mutex
Definition net.h:1667
Mutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
int m_max_outbound_full_relay
Definition net.h:1733
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition net.h:1827
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int m_max_inbound_full_relay
Definition net.h:1743
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition net.h:1718
Mutex m_anchors_mutex
Addresses that were saved during the previous clean shutdown or when the network was deactivated.
Definition net.h:1756
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1641
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1637
bool GetUseAddrmanOutgoing() const
Definition net.h:1189
std::list< CNode * > m_nodes_disconnected
Definition net.h:1669
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1780
bool m_use_addrman_outgoing
Definition net.h:1745
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1651
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition net.h:1702
std::function< void(CNode *)> NodeFn
Definition net.h:1289
NetEventsInterface * m_msgproc
Definition net.h:1747
AssertLockNotHeld(m_reconnections_mutex)
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition net.h:1805
Mutex m_nodes_mutex
Definition net.h:1670
std::thread threadSocketHandler
Definition net.h:1783
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:32
An encapsulated private key.
Definition key.h:46
Message header.
Definition protocol.h:29
Network address.
Definition netaddress.h:113
Transport protocol agnostic message container.
Definition net.h:242
CNetMessage(CNetMessage &&)=default
CNetMessage(DataStream &&recv_in)
Definition net.h:251
std::string m_type
Definition net.h:249
DataStream m_recv
received message data time of message receipt
Definition net.h:244
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition net.h:686
bool IsFeelerConn() const
Definition net.h:828
bool ExpectServicesFromConn() const
Definition net.h:852
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition net.h:730
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition net.h:714
bool IsInboundConn() const
Definition net.h:848
bool HasPermission(NetPermissionFlags permission) const
Definition net.h:741
CountingSemaphoreGrant grantOutbound
Definition net.h:749
bool IsOutboundOrBlockRelayConn() const
Definition net.h:783
NodeId GetId() const
Definition net.h:933
bool IsManualConn() const
Definition net.h:803
const std::string m_addr_name
Definition net.h:728
CNode & operator=(const CNode &)=delete
const CService addrBind
Definition net.h:727
void SetCommonVersion(int greatest_common_version)
Definition net.h:958
std::list< CNetMessage > vRecvMsg
Definition net.h:1016
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition net.h:1020
bool IsAddrFetchConn() const
Definition net.h:832
uint64_t GetLocalNonce() const
Definition net.h:937
const CAddress addr
Definition net.h:725
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
Definition net.h:719
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition net.h:752
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
bool IsBlockOnlyConn() const
Definition net.h:824
int GetCommonVersion() const
Definition net.h:963
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition net.h:799
Mutex m_subver_mutex
Definition net.h:734
Mutex cs_vSend
Definition net.h:710
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition net.h:760
int GetRefCount() const
Definition net.h:941
const util::NotNullUniquePtr< Transport > m_transport
Transport serializer/deserializer.
Definition net.h:690
void PongReceived(NodeClock::duration ping_time)
A ping-pong round trip has completed successfully. Update latest and minimum ping durations.
Definition net.h:1004
Mutex m_msg_process_queue_mutex
Definition net.h:1018
const ConnectionType m_conn_type
Definition net.h:762
const size_t m_recv_flood_size
Definition net.h:1015
const uint64_t nLocalHostNonce
Definition net.h:1012
bool IsManualOrFullOutboundConn() const
Definition net.h:807
bool IsPrivateBroadcastConn() const
Definition net.h:836
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
const NetPermissionFlags m_permission_flags
Definition net.h:692
Mutex m_addr_local_mutex
Definition net.h:1024
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition net.h:705
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition net.h:732
const NodeId id
Definition net.h:1011
Mutex cs_vRecv
Definition net.h:712
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition net.h:707
int AdvertisedVersion() const
Protocol version advertised in our VERSION message.
Definition net.h:843
Mutex m_sock_mutex
Definition net.h:711
const std::optional< Proxy > m_proxy_override
Proxy to use regardless of global proxy settings if reconnecting to this node.
Definition net.h:722
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
std::deque< CSerializedNetMsg > vSendMsg GUARDED_BY(cs_vSend)
Messages still to be fed to m_transport->SetMessageToSend.
void Release()
Definition net.h:978
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition net.h:739
std::string m_session_id
BIP324 session id string in hex, if any.
Definition net.h:233
std::string addrLocal
Definition net.h:221
NodeClock::duration m_min_ping_time
Definition net.h:219
uint64_t nRecvBytes
Definition net.h:215
uint32_t m_mapped_as
Definition net.h:228
mapMsgTypeSize mapRecvBytesPerMsgType
Definition net.h:216
bool fInbound
Definition net.h:208
uint64_t nSendBytes
Definition net.h:213
ConnectionType m_conn_type
Definition net.h:229
std::chrono::seconds m_last_tx_time
Definition net.h:202
CAddress addr
Definition net.h:223
mapMsgTypeSize mapSendBytesPerMsgType
Definition net.h:214
CService addrBind
Definition net.h:225
NodeClock::time_point m_last_recv
Definition net.h:201
NodeClock::time_point m_last_send
Definition net.h:200
NodeClock::duration m_last_ping_time
Definition net.h:218
TransportProtocolType m_transport_type
Transport protocol type.
Definition net.h:231
bool m_bip152_highbandwidth_from
Definition net.h:212
bool m_bip152_highbandwidth_to
Definition net.h:210
std::string m_addr_name
Definition net.h:205
NodeClock::time_point m_connected
Definition net.h:204
int nVersion
Definition net.h:206
std::chrono::seconds m_last_block_time
Definition net.h:203
Network m_network
Definition net.h:227
NodeId nodeid
Definition net.h:199
std::string cleanSubVer
Definition net.h:207
NetPermissionFlags m_permission_flags
Definition net.h:217
Simple class for background tasks that should be run periodically or once "after a while".
Definition scheduler.h:39
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:531
General SipHash-2-4 implementation.
Definition siphash.h:99
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
Fast randomness source.
Definition random.h:386
Different type to mark Mutex at global scope.
Definition sync.h:142
Definition init.h:13
Interface for message handling.
Definition net.h:1046
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:1049
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual bool ProcessMessages(CNode &node, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const =0
Callback to determine whether the given set of service flags are sufficient for a peer to be "relevan...
virtual bool SendMessages(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state)
Netgroup manager.
Definition netgroup.h:17
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition sock.h:35
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition net.h:266
virtual ~Transport()=default
virtual Info GetInfo() const noexcept=0
Retrieve information about this transport.
std::tuple< std::span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
Definition net.h:323
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition net.h:388
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition net.h:424
const NodeId m_node_id
Definition net.h:383
Mutex m_send_mutex
Lock for sending state.
Definition net.h:418
CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex)
The data of the message currently being sent.
size_t m_bytes_sent GUARDED_BY(m_send_mutex)
How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send....
Definition net.h:426
unsigned int nDataPos GUARDED_BY(m_recv_mutex)
bool in_data GUARDED_BY(m_recv_mutex)
uint256 data_hash GUARDED_BY(m_recv_mutex)
std::vector< uint8_t > m_header_to_send GUARDED_BY(m_send_mutex)
The header of the message currently being sent.
const MessageStartChars m_magic_bytes
Definition net.h:382
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition net.h:390
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:410
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
Definition net.h:384
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition net.h:431
std::vector< uint8_t > m_send_buffer GUARDED_BY(m_send_mutex)
The send buffer; meaning is determined by m_send_state.
bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex)
Whether we've sent at least 24 bytes (which would trigger disconnect for V1 peers).
Definition net.h:624
const NodeId m_nodeid
NodeId (for debug logging).
Definition net.h:592
BIP324Cipher m_cipher
Cipher state.
Definition net.h:588
SendState
State type that controls the sender side.
Definition net.h:557
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition net.h:594
Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex)
Lock for sending-side fields.
SendState m_send_state GUARDED_BY(m_send_mutex)
Current sender state.
std::string m_send_type GUARDED_BY(m_send_mutex)
Type of the message being sent.
const bool m_initiating
Whether we are the initiator side.
Definition net.h:590
std::vector< uint8_t > m_recv_buffer GUARDED_BY(m_recv_mutex)
Receive buffer; meaning is determined by m_recv_state.
std::vector< uint8_t > m_send_garbage GUARDED_BY(m_send_mutex)
The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only).
uint32_t m_recv_len GUARDED_BY(m_recv_mutex)
In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >= BIP324Cipher::LENGTH_LEN.
Definition net.h:600
uint32_t m_send_pos GUARDED_BY(m_send_mutex)
How many bytes from the send buffer have been sent so far.
Definition net.h:616
RecvState m_recv_state GUARDED_BY(m_recv_mutex)
Current receiver state.
Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex)
Lock for receiver-side fields.
std::vector< uint8_t > m_recv_aad GUARDED_BY(m_recv_mutex)
AAD expected in next received packet (currently used only for garbage).
std::vector< uint8_t > m_recv_decode_buffer GUARDED_BY(m_recv_mutex)
Buffer to put decrypted contents in, for converting to CNetMessage.
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition net.h:492
256-bit opaque blob.
Definition uint256.h:196
NotNull is intended to be used to denote that a smart pointer type can not hold a nullptr value.
Definition not_null.h:45
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
TransportProtocolType
Transport layer version.
@ V1
Unencrypted, plaintext protocol.
CClientUIInterface uiInterface
std::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:4391
constexpr bool DEFAULT_LISTEN
-listen default
Definition net.h:80
uint16_t GetListenPort()
Definition net.cpp:139
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition net.h:94
constexpr unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:68
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:335
constexpr int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition net.h:76
constexpr bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:90
constexpr int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:72
void RemoveLocal(const CService &addr)
Definition net.cpp:313
constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition net.h:60
constexpr size_t DEFAULT_MAXSENDBUFFER
Definition net.h:104
bool fDiscover
Definition net.cpp:117
constexpr bool DEFAULT_FIXEDSEEDS
Definition net.h:102
constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:82
constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition net.h:92
void ClearLocal()
Definition net.cpp:271
bool fListen
Definition net.cpp:118
constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition net.h:66
constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:64
constexpr size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:103
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition net.cpp:121
const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition net.h:88
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:241
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:109
std::map< std::string, uint64_t > mapMsgTypeSize
Definition net.h:194
constexpr bool DEFAULT_FORCEDNSSEED
Definition net.h:100
constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition net.h:78
constexpr bool DEFAULT_DNSSEED
Definition net.h:101
int64_t NodeId
Definition net.h:108
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:74
CService GetLocalAddress(const CNode &peer)
Definition net.cpp:221
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:119
constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition net.h:98
constexpr int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:96
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE, bool add_even_if_unreachable=false)
Definition net.cpp:278
constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition net.h:62
constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT
Default percentage of inbound connection slots that tx-relaying peers can use.
Definition net.h:86
@ LOCAL_NONE
Definition net.h:159
@ LOCAL_MAPPED
Definition net.h:162
@ LOCAL_MANUAL
Definition net.h:163
@ LOCAL_MAX
Definition net.h:165
@ LOCAL_BIND
Definition net.h:161
@ LOCAL_IF
Definition net.h:160
constexpr bool DEFAULT_V2_TRANSPORT
Definition net.h:106
constexpr int MAX_PEER_CONNECTIONS
Maximum value of -maxconnections.
Definition net.h:84
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:70
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition net.cpp:3470
bool SeenLocal(const CService &addr)
vote for a local address
Definition net.cpp:324
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition netaddress.h:33
ConnectionDirection
Definition netbase.h:35
ServiceFlags
nServices flags
Definition protocol.h:321
@ NODE_NONE
Definition protocol.h:324
@ NODE_P2P_V2
Definition protocol.h:342
constexpr int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
constexpr int PROTOCOL_VERSION
network protocol versioning
constexpr int WTXID_RELAY_VERSION
"wtxidrelay" message type for wtxid-based relay starts with this version
bool fInbound
Definition net.h:119
CService resolvedAddress
Definition net.h:117
AddedNodeParams m_params
Definition net.h:116
bool fConnected
Definition net.h:118
std::string m_added_node
Definition net.h:111
bool m_use_v2transport
Definition net.h:112
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1683
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1684
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition net.h:1441
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition net.h:1442
NetPermissionFlags m_permissions
Definition net.h:1448
std::shared_ptr< Sock > sock
Definition net.h:1440
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:1108
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1106
std::vector< CService > onion_binds
Definition net.h:1110
std::vector< std::string > m_specified_outgoing
Definition net.h:1115
std::vector< std::string > m_added_nodes
Definition net.h:1116
std::vector< CService > vBinds
Definition net.h:1109
bool m_i2p_accept_incoming
Definition net.h:1117
std::vector< std::string > vSeedNodes
Definition net.h:1105
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:1113
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1107
Struct for entries in m_reconnections.
Definition net.h:1845
std::optional< Proxy > proxy_override
Definition net.h:1846
ConnectionType conn_type
Definition net.h:1850
std::string destination
Definition net.h:1849
CountingSemaphoreGrant grant
Definition net.h:1848
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition net.h:133
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition net.h:142
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition net.h:141
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:123
uint16_t nPort
Definition net.h:187
Version of the system clock that is mockable in the context of tests (via FakeNodeClock or SetMockTim...
Definition time.h:27
std::chrono::time_point< NodeClock > time_point
Definition time.h:28
static constexpr time_point epoch
Definition time.h:33
std::optional< uint256 > session_id
Definition net.h:273
TransportProtocolType transport_type
Definition net.h:272
Bilingual messages:
Definition translation.h:24
#define AssertLockNotHeld(cs)
Definition sync.h:149
#define LOCK(cs)
Definition sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:299
#define AssertLockHeld(cs)
Definition sync.h:144
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define LOCK_RETURNED(x)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())