Bitcoin ABC 0.33.6
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Copyright (c) 2017-2019 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#ifndef BITCOIN_NET_H
8#define BITCOIN_NET_H
9
10#include <avalanche/proofid.h>
12#include <chainparams.h>
13#include <common/bloom.h>
14#include <compat/compat.h>
15#include <consensus/amount.h>
16#include <crypto/siphash.h>
17#include <hash.h>
18#include <i2p.h>
19#include <kernel/cs_main.h>
20#include <logging.h>
21#include <net_permissions.h>
22#include <netaddress.h>
23#include <netbase.h>
25#include <node/eviction.h>
27#include <nodeid.h>
28#include <protocol.h>
29#include <pubkey.h>
30#include <radix.h>
31#include <random.h>
32#include <span.h>
33#include <streams.h>
34#include <sync.h>
35#include <uint256.h>
36#include <util/check.h>
37#include <util/sock.h>
38#include <util/time.h>
39
40#include <atomic>
41#include <condition_variable>
42#include <cstdint>
43#include <deque>
44#include <functional>
45#include <list>
46#include <map>
47#include <memory>
48#include <optional>
49#include <queue>
50#include <thread>
51#include <vector>
52
53class AddrMan;
54class BanMan;
55class Config;
56class CNode;
57class CScheduler;
59struct bilingual_str;
60
65static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
67static constexpr auto FEELER_INTERVAL = 2min;
69static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
71static const unsigned int MAX_SUBVERSION_LENGTH = 256;
78static const int MAX_ADDNODE_CONNECTIONS = 8;
87static const int MAX_FEELER_CONNECTIONS = 1;
89static const bool DEFAULT_LISTEN = true;
95static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 1024;
97static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
99static const bool DEFAULT_BLOCKSONLY = false;
101static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
103static const int NUM_FDS_MESSAGE_CAPTURE = 1;
104
105static const bool DEFAULT_FORCEDNSSEED = false;
106static const bool DEFAULT_DNSSEED = true;
107static const bool DEFAULT_FIXEDSEEDS = true;
108static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
109static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
110static const size_t DEFAULT_MAXINFLIGHTBUFFER = 1 * 1000 * 1000;
111
113 std::string strAddedNode;
117};
118
119struct CNodeStats;
121
123 CSerializedNetMsg() = default;
126 // No copying, only moves.
129
132 copy.data = data;
133 copy.m_type = m_type;
134 return copy;
135 }
136
137 std::vector<uint8_t> data;
138 std::string m_type;
139};
140
141const std::vector<std::string> CONNECTION_TYPE_DOC{
142 "outbound-full-relay (default automatic connections)",
143 "block-relay-only (does not relay transactions or addresses)",
144 "inbound (initiated by the peer)",
145 "manual (added via addnode RPC or -addnode/-connect configuration options)",
146 "addr-fetch (short-lived automatic connection for soliciting addresses)",
147 "feeler (short-lived automatic connection for testing addresses)"};
148
155void Discover();
156
157uint16_t GetListenPort();
158
159enum {
160 // unknown
162 // address a local interface listens on
164 // address explicit bound to
166 // address reported by PCP
168 // address explicitly specified (-externalip=)
170
173
174bool IsPeerAddrLocalGood(CNode *pnode);
176std::optional<CService> GetLocalAddrForPeer(CNode &node);
177
182void SetReachable(enum Network net, bool reachable);
184bool IsReachable(enum Network net);
186bool IsReachable(const CNetAddr &addr);
187
188bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
189bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
190void RemoveLocal(const CService &addr);
191bool SeenLocal(const CService &addr);
192bool IsLocal(const CService &addr);
193bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
194CService GetLocalAddress(const CNetAddr &addrPeer);
195
196extern bool fDiscover;
197extern bool fListen;
198
201 uint16_t nPort;
202};
203
205extern std::map<CNetAddr, LocalServiceInfo>
207
208extern const std::string NET_MESSAGE_TYPE_OTHER;
209typedef std::map</* message type */ std::string, /* total bytes */ uint64_t>
211
219 std::chrono::seconds m_last_send;
220 std::chrono::seconds m_last_recv;
221 std::chrono::seconds m_last_msg_start;
222 std::chrono::seconds m_last_tx_time;
223 std::chrono::seconds m_last_proof_time;
224 std::chrono::seconds m_last_block_time;
225 std::chrono::seconds m_connected;
226 int64_t nTimeOffset;
227 std::string m_addr_name;
229 std::string cleanSubVer;
231 // We requested high bandwidth connection to peer
233 // Peer requested high bandwidth connection
236 uint64_t nSendBytes;
238 uint64_t nRecvBytes;
242 std::chrono::microseconds m_last_ping_time;
243 std::chrono::microseconds m_min_ping_time;
244 // Our address, as reported by the peer
245 std::string addrLocal;
246 // Address of this peer
248 // Bind address of our side of the connection
250 // Network the peer connected through
252 uint32_t m_mapped_as;
254 std::optional<double> m_availabilityScore;
255};
256
263public:
267 std::chrono::microseconds m_time{0};
269 uint32_t m_message_size{0};
272 std::string m_type;
273
274 CNetMessage(DataStream &&recv_in) : m_recv(std::move(recv_in)) {}
275 // Only one CNetMessage object will exist for the same message on either
276 // the receive or processing queue. For performance reasons we therefore
277 // delete the copy constructor and assignment operator to avoid the
278 // possibility of copying CNetMessage objects.
280 CNetMessage(const CNetMessage &) = delete;
283};
284
291public:
292 // returns true if the current deserialization is complete
293 virtual bool Complete() const = 0;
295 virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
296 // decomposes a message from the context
297 virtual CNetMessage GetMessage(std::chrono::microseconds time,
298 bool &reject_message) = 0;
299 virtual bool HasData() const = 0;
300
302};
303
305private:
307 // Only for logging
311
312 // Parsing header (false) or data (true)
314 // Partially received header.
316 // Complete header.
318 // Received message data.
320 uint32_t nHdrPos;
321 uint32_t nDataPos;
322
323 const uint256 &GetMessageHash() const;
324 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
325 int readData(Span<const uint8_t> msg_bytes);
326
327 void Reset() {
328 vRecv.clear();
329 hdrbuf.clear();
330 hdrbuf.resize(24);
331 in_data = false;
332 nHdrPos = 0;
333 nDataPos = 0;
335 hasher.Reset();
336 }
337
338public:
339 explicit V1TransportDeserializer(const Config &config, const NodeId node_id)
340 : m_config(config), m_node_id(node_id) {
341 Reset();
342 }
343
344 bool Complete() const override {
345 if (!in_data) {
346 return false;
347 }
348
349 return (hdr.nMessageSize == nDataPos);
350 }
351
352 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
353 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
354 if (ret < 0) {
355 Reset();
356 } else {
357 msg_bytes = msg_bytes.subspan(ret);
358 }
359 return ret;
360 }
361
362 CNetMessage GetMessage(std::chrono::microseconds time,
363 bool &reject_message) override;
364
365 bool HasData() const override { return in_data || nHdrPos > 0; }
366};
367
372public:
373 // prepare message for transport (header construction, error-correction
374 // computation, payload encryption, etc.)
375 virtual void prepareForTransport(const Config &config,
377 std::vector<uint8_t> &header) const = 0;
379};
380
382public:
383 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
384 std::vector<uint8_t> &header) const override;
385};
386
388 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
390 bool prefer_evict = false;
392};
393
395class CNode {
396public:
397 // Used only by SocketHandler thread
398 const std::unique_ptr<TransportDeserializer> m_deserializer;
399 const std::unique_ptr<const TransportSerializer> m_serializer;
400
402
412 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
413
415 size_t nSendSize GUARDED_BY(cs_vSend){0};
417 size_t nSendOffset GUARDED_BY(cs_vSend){0};
418 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
419 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
423
424 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
425 std::atomic<uint64_t> nInflightBytes{0};
426
427 std::atomic<std::chrono::seconds> m_last_send{0s};
428 std::atomic<std::chrono::seconds> m_last_recv{0s};
429 std::atomic<std::chrono::seconds> m_last_msg_start{0s};
430
432 const std::chrono::seconds m_connected;
433 std::atomic<int64_t> nTimeOffset{0};
434 // Address of this peer
436 // Bind address of our side of the connection
438 const std::string m_addr_name;
441 const bool m_inbound_onion;
442 std::atomic<int> nVersion{0};
443 // The nonce provided by the remote host.
444 uint64_t nRemoteHostNonce{0};
445 // The extra entropy provided by the remote host.
452 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
453 // This peer is preferred for eviction.
454 const bool m_prefer_evict{false};
455 bool HasPermission(NetPermissionFlags permission) const {
457 }
458 std::atomic_bool fSuccessfullyConnected{false};
459 // Setting fDisconnect to true will cause the node to be disconnected the
460 // next time DisconnectNodes() runs
461 std::atomic_bool fDisconnect{false};
463 std::atomic<int> nRefCount{0};
464
465 const uint64_t nKeyedNetGroup;
466 std::atomic_bool fPauseRecv{false};
467 std::atomic_bool fPauseSend{false};
468
470
474
482 std::optional<std::pair<CNetMessage, bool>> PollMessage()
484
489 void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes)
491 mapSendBytesPerMsgType[msg_type] += sent_bytes;
492 }
493
495 switch (m_conn_type) {
499 return true;
504 return false;
505 } // no default case, so the compiler can warn about missing cases
506
507 assert(false);
508 }
509
510 bool IsFullOutboundConn() const {
513 }
514
516
517 bool IsBlockOnlyConn() const {
519 }
520
522
523 bool IsAddrFetchConn() const {
525 }
526
527 bool IsInboundConn() const {
529 }
530
533 }
534
536 switch (m_conn_type) {
540 return false;
545 return true;
546 } // no default case, so the compiler can warn about missing cases
547
548 assert(false);
549 }
550
563
564 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
565 std::atomic<bool> m_bip152_highbandwidth_to{false};
566 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
567 std::atomic<bool> m_bip152_highbandwidth_from{false};
568
573 std::atomic_bool m_has_all_wanted_services{false};
574
579 std::atomic_bool m_relays_txs{false};
580
585 std::atomic_bool m_bloom_filter_loaded{false};
586
587 // True if we know this peer is using Avalanche (at least polling)
588 std::atomic<bool> m_avalanche_enabled{false};
589
591 // Pubkey used to verify signatures on Avalanche messages from this peer
592 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
593
595 void invsPolled(uint32_t count);
596
598 void invsVoted(uint32_t count);
599
616 void updateAvailabilityScore(double decayFactor);
617 double getAvailabilityScore() const;
618
619 // Store the next time we will consider a getavaaddr message from this peer
620 std::chrono::seconds m_nextGetAvaAddr{0};
621
622 // The last time the node sent us a faulty message
623 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
635
637
645 std::atomic<std::chrono::seconds> m_last_block_time{0s};
646
653 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
654
661 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
662
664 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
665
670 std::atomic<std::chrono::microseconds> m_min_ping_time{
671 std::chrono::microseconds::max()};
672
673 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
674 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
675 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
676 const std::string &addrNameIn, ConnectionType conn_type_in,
677 bool inbound_onion, CNodeOptions &&node_opts = {});
678 CNode(const CNode &) = delete;
679 CNode &operator=(const CNode &) = delete;
680
685 void PongReceived(std::chrono::microseconds ping_time) {
686 m_last_ping_time = ping_time;
687 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
688 }
689
690 NodeId GetId() const { return id; }
691
692 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
693 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
694
695 int GetRefCount() const {
696 assert(nRefCount >= 0);
697 return nRefCount;
698 }
699
709 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
710 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
711
712 void SetCommonVersion(int greatest_common_version) {
714 m_greatest_common_version = greatest_common_version;
715 }
717
720 void SetAddrLocal(const CService &addrLocalIn)
722
724 nRefCount++;
725 return this;
726 }
727
728 void Release() { nRefCount--; }
729
731
732 void copyStats(CNodeStats &stats)
735
736 std::string ConnectionTypeAsString() const {
738 }
739
740 void pauseRecv(bool pause);
741
742private:
743 const NodeId id;
744 const uint64_t nLocalHostNonce;
745 const uint64_t nLocalExtraEntropy;
747
748 const size_t m_recv_flood_size;
749 // Used only by SocketHandler thread
750 std::list<CNetMessage> vRecvMsg;
751
753 std::list<CNetMessage>
755 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
756
757 // Our address, as reported by the peer
760
766 std::atomic<uint64_t> invCounters{0};
767
769 std::atomic<double> availabilityScore{0.};
770
771 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
772 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
773
783 std::unique_ptr<i2p::sam::Session>
784 m_i2p_sam_session GUARDED_BY(m_sock_mutex);
785};
786
791public:
796
798 virtual void InitializeNode(const Config &config, CNode &node,
799 ServiceFlags our_services) = 0;
800
802 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
803
813 virtual bool ProcessMessages(const Config &config, CNode *pnode,
814 std::atomic<bool> &interrupt)
816
824 virtual bool SendMessages(const Config &config, CNode *pnode)
826
827protected:
834};
835
836namespace {
837struct CConnmanTest;
838}
839
841class CConnman {
842public:
843 struct Options {
849 int nMaxAddnode = 0;
850 int nMaxFeeler = 0;
852 std::vector<NetEventsInterface *> m_msgproc;
853 BanMan *m_banman = nullptr;
854 unsigned int nSendBufferMaxSize = 0;
855 unsigned int nReceiveFloodSize = 0;
856 uint64_t nMaxOutboundLimit = 0;
858 std::vector<std::string> vSeedNodes;
859 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
860 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
861 std::vector<NetWhitebindPermissions> vWhiteBinds;
862 std::vector<CService> vBinds;
863 std::vector<CService> onion_binds;
868 std::vector<std::string> m_specified_outgoing;
869 std::vector<std::string> m_added_nodes;
873 };
874
875 void Init(const Options &connOptions)
877 nLocalServices = connOptions.nLocalServices;
878 nMaxConnections = connOptions.nMaxConnections;
879 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
880 nMaxAddnode = connOptions.nMaxAddnode;
881 nMaxFeeler = connOptions.nMaxFeeler;
882 {
883 // Lock cs_main to prevent a potential race with the peer validation
884 // logic thread.
887 std::min(connOptions.m_max_outbound_full_relay,
888 connOptions.nMaxConnections);
889 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
890 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
894 }
895 m_client_interface = connOptions.uiInterface;
896 m_banman = connOptions.m_banman;
897 m_msgproc = connOptions.m_msgproc;
898 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
899 nReceiveFloodSize = connOptions.nReceiveFloodSize;
901 std::chrono::seconds{connOptions.m_peer_connect_timeout};
902 {
904 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
905 }
906 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
907 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
908 {
910 m_added_nodes = connOptions.m_added_nodes;
911 }
912 m_onion_binds = connOptions.onion_binds;
913 whitelist_forcerelay = connOptions.whitelist_forcerelay;
914 whitelist_relay = connOptions.whitelist_relay;
915 }
916
917 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
918 AddrMan &addrmanIn, bool network_active = true);
919 virtual ~CConnman();
920
921 bool Start(CScheduler &scheduler, const Options &options)
924
925 void StopThreads();
926 void StopNodes();
927 void Stop() {
928 StopThreads();
929 StopNodes();
930 };
931
933 bool GetNetworkActive() const { return fNetworkActive; };
935 void SetNetworkActive(bool active);
936 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
937 CSemaphoreGrant *grantOutbound,
938 const char *strDest, ConnectionType conn_type)
940 bool CheckIncomingNonce(uint64_t nonce);
941
942 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
943
944 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
945
946 using NodeFn = std::function<void(CNode *)>;
947 void ForEachNode(const NodeFn &func) {
949 for (auto &&node : m_nodes) {
951 func(node);
952 }
953 }
954 };
955
956 void ForEachNode(const NodeFn &func) const {
958 for (auto &&node : m_nodes) {
960 func(node);
961 }
962 }
963 };
964
965 // Addrman functions
976 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
977 std::optional<Network> network) const;
984 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
985 size_t max_pct);
986
987 // This allows temporarily exceeding m_max_outbound_full_relay, with the
988 // goal of finding a peer that is better than all our current peers.
989 void SetTryNewOutboundPeer(bool flag);
990 bool GetTryNewOutboundPeer() const;
991
993 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
995 }
996
997 // Return the number of outbound peers we have in excess of our target (eg,
998 // if we previously called SetTryNewOutboundPeer(true), and have since set
999 // to false, we may have extra peers that we wish to disconnect). This may
1000 // return a value less than (num_outbound_connections - num_outbound_slots)
1001 // in cases where some outbound connections are not yet fully connected, or
1002 // not yet fully disconnected.
1003 int GetExtraFullOutboundCount() const;
1004 // Count the number of block-relay-only peers we have over our limit.
1005 int GetExtraBlockRelayCount() const;
1006
1007 bool AddNode(const std::string &node)
1009 bool RemoveAddedNode(const std::string &node)
1011 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
1013
1028 bool AddConnection(const std::string &address, ConnectionType conn_type)
1030
1031 size_t GetNodeCount(ConnectionDirection) const;
1032 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1033 bool GetNodeStats(NodeId id, CNodeStats &stats) const;
1034 bool DisconnectNode(const std::string &node);
1035 bool DisconnectNode(const CSubNet &subnet);
1036 bool DisconnectNode(const CNetAddr &addr);
1037 bool DisconnectNode(NodeId id);
1038
1046
1051 };
1054 }
1055
1056 uint64_t GetMaxOutboundTarget() const;
1057 std::chrono::seconds GetMaxOutboundTimeframe() const;
1058
1062 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1063
1066 uint64_t GetOutboundTargetBytesLeft() const;
1067
1070 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1071
1072 uint64_t GetTotalBytesRecv() const;
1073 uint64_t GetTotalBytesSent() const;
1074
1076 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1077
1079
1085 std::chrono::seconds now) const;
1086
1087private:
1089 public:
1090 std::shared_ptr<Sock> sock;
1092 NetPermissions::AddFlag(flags, m_permissions);
1093 }
1094 ListenSocket(std::shared_ptr<Sock> sock_,
1095 NetPermissionFlags permissions_)
1096 : sock(sock_), m_permissions(permissions_) {}
1097
1098 private:
1100 };
1101
1102 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1103 NetPermissionFlags permissions);
1104 bool Bind(const CService &addr, unsigned int flags,
1105 NetPermissionFlags permissions);
1106 bool InitBinds(const Options &options);
1107
1111 void AddAddrFetch(const std::string &strDest)
1113 void ProcessAddrFetch()
1116 void
1117 ThreadOpenConnections(std::vector<std::string> connect,
1118 std::function<void(const CAddress &, ConnectionType)>
1119 mockOpenConnection)
1124 void AcceptConnection(const ListenSocket &hListenSocket);
1125
1134 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1135 NetPermissionFlags permission_flags,
1136 const CAddress &addr_bind,
1137 const CAddress &addr);
1138
1139 void DisconnectNodes();
1142 bool InactivityCheck(const CNode &node) const;
1143
1149 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1150
1156
1163 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1164 const Sock::EventsPerSock &events_per_sock)
1166
1171 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1172
1176
1177 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1178
1179 CNode *FindNode(const CNetAddr &ip);
1180 CNode *FindNode(const CSubNet &subNet);
1181 CNode *FindNode(const std::string &addrName);
1182 CNode *FindNode(const CService &addr);
1183
1188 bool AlreadyConnectedToAddress(const CAddress &addr);
1189
1191 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1192 bool fCountFailure, ConnectionType conn_type)
1194 ;
1196 NetPermissionFlags &flags, const CNetAddr &addr,
1197 const std::vector<NetWhitelistPermissions> &ranges) const;
1198
1199 void DeleteNode(CNode *pnode);
1200
1202
1207 std::pair<size_t, bool> SocketSendData(CNode &node) const
1209
1210 void DumpAddresses();
1211
1212 // Network stats
1213 void RecordBytesRecv(uint64_t bytes);
1214 void RecordBytesSent(uint64_t bytes);
1215
1220
1221 // Whether the node should be passed out in ForEach* callbacks
1222 static bool NodeFullyConnected(const CNode *pnode);
1223
1225
1226 // Network usage totals
1228 std::atomic<uint64_t> nTotalBytesRecv{0};
1229 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1230
1231 // outbound limit & stats
1232 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1233 std::chrono::seconds
1234 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1235 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1236
1237 // P2P timeout in seconds
1238 std::chrono::seconds m_peer_connect_timeout;
1239
1240 // Whitelisted ranges. Any node connecting from these is automatically
1241 // whitelisted (as well as those connecting to whitelisted binds).
1242 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1243 // Whitelisted ranges for outgoing connections.
1244 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1245
1246 unsigned int nSendBufferMaxSize{0};
1247 unsigned int nReceiveFloodSize{0};
1248
1249 std::vector<ListenSocket> vhListenSocket;
1250 std::atomic<bool> fNetworkActive{true};
1253 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1255 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1257 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1258 std::list<CNode *> m_nodes_disconnected;
1260 std::atomic<NodeId> nLastNodeId{0};
1261 unsigned int nPrevNodeCount{0};
1262
1270 std::vector<CAddress> m_addrs_response_cache;
1271 std::chrono::microseconds m_cache_entry_expiration{0};
1272 };
1273
1288 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1289
1301 std::atomic<ServiceFlags> nLocalServices;
1302
1303 std::unique_ptr<CSemaphore> semOutbound;
1304 std::unique_ptr<CSemaphore> semAddnode;
1306
1307 // How many full-relay (tx, block, addr) outbound peers we want
1309
1310 // How many block-relay only outbound peers we want
1311 // We do not relay tx or addr messages with these peers
1313
1314 // How many avalanche enabled outbound peers we want
1316
1322 // FIXME m_msgproc is a terrible name
1323 std::vector<NetEventsInterface *> m_msgproc;
1329
1334 std::vector<CAddress> m_anchors;
1335
1337 const uint64_t nSeed0, nSeed1;
1338
1340 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1341
1342 std::condition_variable condMsgProc;
1344 std::atomic<bool> flagInterruptMsgProc{false};
1345
1353
1359 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1360
1367
1373
1379 std::atomic_bool m_start_extra_block_relay_peers{false};
1380
1385 std::vector<CService> m_onion_binds;
1386
1391
1399 std::queue<std::unique_ptr<i2p::sam::Session>>
1401
1406 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1407
1413
1419
1420 std::atomic_bool inflight_throttle{false};
1421
1428 public:
1429 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1430 {
1431 LOCK(connman.m_nodes_mutex);
1432 m_nodes_copy = connman.m_nodes;
1433 for (auto &node : m_nodes_copy) {
1434 node->AddRef();
1435 }
1436 }
1437 if (shuffle) {
1438 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1440 }
1441 }
1442
1444 for (auto &node : m_nodes_copy) {
1445 node->Release();
1446 }
1447 }
1448
1449 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1450
1451 private:
1452 std::vector<CNode *> m_nodes_copy;
1453 };
1454
1455 friend struct ::CConnmanTest;
1456 friend struct ConnmanTestMsg;
1457};
1458
1459std::string getSubVersionEB(uint64_t MaxBlockSize);
1460std::string userAgent(const Config &config);
1461
1463void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1464 Span<const uint8_t> data, bool is_incoming);
1465
1469extern std::function<void(const CAddress &addr, const std::string &msg_type,
1470 Span<const uint8_t> data, bool is_incoming)>
1472
1473#endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:546
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:68
Definition: banman.h:59
A CService with information about it as peer.
Definition: protocol.h:442
Signals for UI communication.
Definition: ui_interface.h:25
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1427
const std::vector< CNode * > & Nodes() const
Definition: net.h:1449
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1429
std::vector< CNode * > m_nodes_copy
Definition: net.h:1452
Definition: net.h:841
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1418
std::condition_variable condMsgProc
Definition: net.h:1342
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1229
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1175
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1234
std::thread threadMessageHandler
Definition: net.h:1365
void ForEachNode(const NodeFn &func)
Definition: net.h:947
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
Definition: net.cpp:2993
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1052
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3009
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1242
CClientUIInterface * m_client_interface
Definition: net.h:1321
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2272
void ForEachNode(const NodeFn &func) const
Definition: net.h:956
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3204
void DeleteNode(CNode *pnode)
Definition: net.cpp:2774
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2865
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:986
bool GetNetworkActive() const
Definition: net.h:933
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:394
int m_max_outbound
Definition: net.h:1319
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
Definition: net.h:1406
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1729
void Stop()
Definition: net.h:927
int m_max_outbound_block_relay
Definition: net.h:1312
std::thread threadI2PAcceptIncoming
Definition: net.h:1366
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1733
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1344
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2695
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1566
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1361
std::vector< std::string > m_added_nodes GUARDED_BY(m_added_nodes_mutex)
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Do the read/write for connected sockets that are ready for IO.
Definition: net.cpp:1423
NodeId GetNewNodeId()
Definition: net.cpp:2498
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1352
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1304
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2561
std::atomic< NodeId > nLastNodeId
Definition: net.h:1260
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2969
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1761
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1558
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1328
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:3032
std::thread threadDNSAddressSeed
Definition: net.h:1361
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1301
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2323
const uint64_t nSeed1
Definition: net.h:1337
void StartExtraBlockRelayPeers()
Definition: net.h:992
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1334
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2989
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1412
friend struct ConnmanTestMsg
Definition: net.h:1456
unsigned int nPrevNodeCount
Definition: net.h:1261
void NotifyNumConnectionsChanged()
Definition: net.cpp:1275
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3052
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2920
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1238
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.
Definition: net.h:1372
bool InitBinds(const Options &options)
Definition: net.cpp:2524
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:135
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1232
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1249
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:2222
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2120
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3216
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2984
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1303
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2189
RecursiveMutex cs_totalBytesSent
Definition: net.h:1227
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2502
std::thread threadOpenConnections
Definition: net.h:1364
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2877
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1710
Mutex m_addr_fetches_mutex
Definition: net.h:1254
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1294
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:354
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2895
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2132
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1337
unsigned int nReceiveFloodSize
Definition: net.h:1247
int GetExtraFullOutboundCount() const
Definition: net.cpp:1745
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3043
std::pair< size_t, bool > SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
(Try to) send data from node's vSendMsg.
Definition: net.cpp:909
RecursiveMutex m_nodes_mutex
Definition: net.h:1259
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...
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3154
int nMaxConnections
Definition: net.h:1305
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2487
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2788
std::function< void(CNode *)> NodeFn
Definition: net.h:946
void SetNetworkActive(bool active)
Definition: net.cpp:2473
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1258
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake.
Definition: net.h:1049
AddrMan & addrman
Definition: net.h:1252
std::atomic_bool inflight_throttle
Definition: net.h:1420
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1395
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3220
Mutex mutexMsgProc
Definition: net.h:1343
bool fAddressesInitialized
Definition: net.h:1251
virtual ~CConnman()
Definition: net.cpp:2782
void StopThreads()
Definition: net.cpp:2718
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2853
std::thread threadOpenAddedConnections
Definition: net.h:1363
Mutex m_added_nodes_mutex
Definition: net.h:1256
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:604
const Config * config
Definition: net.h:1224
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:875
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:399
int m_max_outbound_full_relay
Definition: net.h:1308
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1390
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1317
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2965
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1289
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1550
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition: net.cpp:1066
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3158
void StopNodes()
Definition: net.cpp:2739
bool GetUseAddrmanOutgoing() const
Definition: net.h:934
unsigned int nSendBufferMaxSize
Definition: net.h:1246
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1359
bool m_use_addrman_outgoing
Definition: net.h:1320
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1244
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:1288
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1228
std::atomic< bool > fNetworkActive
Definition: net.h:1250
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1379
void DisconnectNodes()
Definition: net.cpp:1225
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1537
void DumpAddresses()
Definition: net.cpp:1701
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:1385
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:426
int nMaxFeeler
Definition: net.h:1318
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1323
std::thread threadSocketHandler
Definition: net.h:1362
uint64_t GetTotalBytesSent() const
Definition: net.cpp:3047
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1775
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1037
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2361
int m_max_avalanche_outbound
Definition: net.h:1315
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:22
CHash256 & Reset()
Definition: hash.h:41
Message header.
Definition: protocol.h:34
uint32_t nMessageSize
Definition: protocol.h:71
Network address.
Definition: netaddress.h:114
Transport protocol agnostic message container.
Definition: net.h:262
CNetMessage(CNetMessage &&)=default
uint32_t m_message_size
size of the payload
Definition: net.h:269
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:267
CNetMessage(DataStream &&recv_in)
Definition: net.h:274
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:271
std::string m_type
Definition: net.h:272
DataStream m_recv
received message data
Definition: net.h:265
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition: net.h:395
Mutex cs_avalanche_pubkey
Definition: net.h:590
const CAddress addrBind
Definition: net.h:437
bool IsFeelerConn() const
Definition: net.h:521
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:432
bool ExpectServicesFromConn() const
Definition: net.h:535
std::atomic< int > nVersion
Definition: net.h:442
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:573
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:424
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:769
bool IsInboundConn() const
Definition: net.h:527
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:455
std::atomic_bool fPauseRecv
Definition: net.h:466
void pauseRecv(bool pause)
Definition: net.cpp:698
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:494
NodeId GetId() const
Definition: net.h:690
bool IsManualConn() const
Definition: net.h:515
std::atomic< int64_t > nTimeOffset
Definition: net.h:433
const std::string m_addr_name
Definition: net.h:438
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:736
void SetCommonVersion(int greatest_common_version)
Definition: net.h:712
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:565
std::list< CNetMessage > vRecvMsg
Definition: net.h:750
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:579
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:567
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:685
std::atomic_bool fSuccessfullyConnected
Definition: net.h:458
const bool m_prefer_evict
Definition: net.h:454
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:755
bool IsAddrFetchConn() const
Definition: net.h:523
uint64_t GetLocalNonce() const
Definition: net.h:692
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions &&node_opts={})
Definition: net.cpp:3085
const CAddress addr
Definition: net.h:435
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:631
CSemaphoreGrant grantOutbound
Definition: net.h:462
std::atomic< std::chrono::seconds > m_last_msg_start
Definition: net.h:429
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:465
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...
std::atomic< int > nRefCount
Definition: net.h:463
std::atomic< int > m_greatest_common_version
Definition: net.h:746
bool IsBlockOnlyConn() const
Definition: net.h:517
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition: net.cpp:3121
int GetCommonVersion() const
Definition: net.h:716
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:510
uint64_t nRemoteHostNonce
Definition: net.h:444
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:451
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:399
Mutex cs_vSend
Definition: net.h:420
CNode * AddRef()
Definition: net.h:723
std::atomic_bool fPauseSend
Definition: net.h:467
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:620
uint64_t nRemoteExtraEntropy
Definition: net.h:446
int GetRefCount() const
Definition: net.h:695
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
Definition: net.cpp:3138
uint64_t GetLocalExtraEntropy() const
Definition: net.h:693
SteadyMilliseconds m_last_poll
Definition: net.h:636
double getAvailabilityScore() const
Definition: net.cpp:3079
Mutex m_msg_process_queue_mutex
Definition: net.h:752
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:417
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:585
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:469
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:644
const size_t m_recv_flood_size
Definition: net.h:748
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:648
const uint64_t nLocalHostNonce
Definition: net.h:744
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:664
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3064
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:415
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
Definition: net.h:623
const uint64_t nLocalExtraEntropy
Definition: net.h:745
const NetPermissionFlags m_permission_flags
Definition: net.h:401
bool ReceiveMsgBytes(const Config &config, Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:710
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:3056
Mutex m_addr_local_mutex
Definition: net.h:758
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:441
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:670
const NodeId id
Definition: net.h:743
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
Definition: net.h:628
void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes) EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
Account for the total size of a sent message in the per msg type connection stats.
Definition: net.h:489
std::atomic< std::chrono::seconds > m_last_proof_time
UNIX epoch time of the last proof received from this peer that we had not yet seen (e....
Definition: net.h:661
Mutex cs_vRecv
Definition: net.h:422
std::atomic< bool > m_avalanche_enabled
Definition: net.h:588
std::optional< CPubKey > m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey)
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:645
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:398
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:418
std::atomic< uint64_t > invCounters
The inventories polled and voted counters since last score computation, stored as a pair of uint32_t ...
Definition: net.h:766
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:421
std::atomic_bool fDisconnect
Definition: net.h:461
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:428
std::atomic< int > m_avalanche_message_fault_score
This score is incremented for every new faulty message received when m_avalanche_message_fault_counte...
Definition: net.h:634
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:653
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:625
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:3060
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:594
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:427
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
bool IsAvalancheOutboundConnection() const
Definition: net.h:531
void Release()
Definition: net.h:728
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:452
std::atomic< uint64_t > nInflightBytes
Definition: net.h:425
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
RAII-style semaphore lock.
Definition: sync.h:397
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:573
SipHash-2-4.
Definition: siphash.h:14
A helper class for interruptible sleeps.
Definition: config.h:19
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:118
void resize(size_type n, value_type c=value_type{})
Definition: streams.h:153
void clear()
Definition: streams.h:161
Fast randomness source.
Definition: random.h:411
Different type to mark Mutex at global scope.
Definition: sync.h:144
Interface for message handling.
Definition: net.h:790
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:795
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
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:27
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:219
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:290
virtual bool HasData() const =0
virtual ~TransportDeserializer()
Definition: net.h:301
virtual bool Complete() const =0
virtual CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message)=0
virtual int Read(const Config &config, Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
The TransportSerializer prepares messages for the network transport.
Definition: net.h:371
virtual ~TransportSerializer()
Definition: net.h:378
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const =0
CMessageHeader hdr
Definition: net.h:317
CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message) override
Definition: net.cpp:849
const uint256 & GetMessageHash() const
Definition: net.cpp:840
const NodeId m_node_id
Definition: net.h:308
const Config & m_config
Definition: net.h:306
bool HasData() const override
Definition: net.h:365
uint32_t nDataPos
Definition: net.h:321
uint32_t nHdrPos
Definition: net.h:320
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:352
V1TransportDeserializer(const Config &config, const NodeId node_id)
Definition: net.h:339
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:823
bool Complete() const override
Definition: net.h:344
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:775
CHash256 hasher
Definition: net.h:309
DataStream hdrbuf
Definition: net.h:315
uint256 data_hash
Definition: net.h:310
DataStream vRecv
Definition: net.h:319
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition: net.cpp:893
void SetNull()
Definition: uint256.h:41
256-bit opaque blob.
Definition: uint256.h:129
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ 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.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
int64_t NodeId
Definition: eviction.h:16
#define LogPrint(category,...)
Definition: logging.h:452
@ NET
Definition: logging.h:69
Definition: messages.h:12
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:240
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:141
uint16_t GetListenPort()
Definition: net.cpp:140
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:95
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:349
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:224
void RemoveLocal(const CService &addr)
Definition: net.cpp:314
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:71
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:65
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:78
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:281
bool fDiscover
Definition: net.cpp:128
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:109
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:103
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:99
static const size_t DEFAULT_MAXINFLIGHTBUFFER
Definition: net.h:110
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:105
bool fListen
Definition: net.cpp:129
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:97
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:69
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:108
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:85
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:246
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:115
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:320
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:107
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3308
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
Definition: net.cpp:3242
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:130
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:87
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:89
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:175
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:67
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:101
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3276
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:210
static const bool DEFAULT_DNSSEED
Definition: net.h:106
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:76
@ LOCAL_NONE
Definition: net.h:161
@ LOCAL_MAPPED
Definition: net.h:167
@ LOCAL_MANUAL
Definition: net.h:169
@ LOCAL_MAX
Definition: net.h:171
@ LOCAL_BIND
Definition: net.h:165
@ LOCAL_IF
Definition: net.h:163
std::string userAgent(const Config &config)
Definition: net.cpp:3256
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:80
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:2461
bool IsReachable(enum Network net)
Definition: net.cpp:328
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:338
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:37
ConnectionDirection
Definition: netbase.h:37
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:512
bool fInbound
Definition: net.h:116
CService resolvedAddress
Definition: net.h:114
bool fConnected
Definition: net.h:115
std::string strAddedNode
Definition: net.h:113
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1269
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1271
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1270
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1091
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1094
NetPermissionFlags m_permissions
Definition: net.h:1099
std::shared_ptr< Sock > sock
Definition: net.h:1090
int m_max_outbound_block_relay
Definition: net.h:847
unsigned int nReceiveFloodSize
Definition: net.h:855
int m_max_outbound_full_relay
Definition: net.h:846
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:861
uint64_t nMaxOutboundLimit
Definition: net.h:856
CClientUIInterface * uiInterface
Definition: net.h:851
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:859
int m_max_avalanche_outbound
Definition: net.h:848
std::vector< CService > onion_binds
Definition: net.h:863
int nMaxFeeler
Definition: net.h:850
std::vector< std::string > m_specified_outgoing
Definition: net.h:868
bool whitelist_relay
Definition: net.h:872
int nMaxConnections
Definition: net.h:845
ServiceFlags nLocalServices
Definition: net.h:844
std::vector< std::string > m_added_nodes
Definition: net.h:869
int64_t m_peer_connect_timeout
Definition: net.h:857
std::vector< CService > vBinds
Definition: net.h:862
unsigned int nSendBufferMaxSize
Definition: net.h:854
bool m_i2p_accept_incoming
Definition: net.h:870
std::vector< std::string > vSeedNodes
Definition: net.h:858
BanMan * m_banman
Definition: net.h:853
bool m_use_addrman_outgoing
Definition: net.h:867
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:852
bool whitelist_forcerelay
Definition: net.h:871
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:866
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:860
int nMaxAddnode
Definition: net.h:849
NetPermissionFlags permission_flags
Definition: net.h:389
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition: net.h:388
bool prefer_evict
Definition: net.h:390
size_t recv_flood_size
Definition: net.h:391
POD that contains various stats about a node.
Definition: net.h:217
std::string addrLocal
Definition: net.h:245
CAddress addrBind
Definition: net.h:249
uint64_t nRecvBytes
Definition: net.h:238
std::chrono::microseconds m_last_ping_time
Definition: net.h:242
uint32_t m_mapped_as
Definition: net.h:252
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:239
bool fInbound
Definition: net.h:230
uint64_t nSendBytes
Definition: net.h:236
std::chrono::seconds m_last_recv
Definition: net.h:220
std::optional< double > m_availabilityScore
Definition: net.h:254
uint64_t nInflightBytes
Definition: net.h:240
std::chrono::seconds m_last_proof_time
Definition: net.h:223
ConnectionType m_conn_type
Definition: net.h:253
std::chrono::seconds m_last_send
Definition: net.h:219
std::chrono::seconds m_last_tx_time
Definition: net.h:222
CAddress addr
Definition: net.h:247
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:237
std::chrono::microseconds m_min_ping_time
Definition: net.h:243
int64_t nTimeOffset
Definition: net.h:226
std::chrono::seconds m_connected
Definition: net.h:225
bool m_bip152_highbandwidth_from
Definition: net.h:234
bool m_bip152_highbandwidth_to
Definition: net.h:232
std::string m_addr_name
Definition: net.h:227
int nVersion
Definition: net.h:228
std::chrono::seconds m_last_block_time
Definition: net.h:224
Network m_network
Definition: net.h:251
NodeId nodeid
Definition: net.h:218
std::string cleanSubVer
Definition: net.h:229
int m_starting_height
Definition: net.h:235
std::chrono::seconds m_last_msg_start
Definition: net.h:221
NetPermissionFlags m_permission_flags
Definition: net.h:241
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:130
std::vector< uint8_t > data
Definition: net.h:137
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:138
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:201
int nScore
Definition: net.h:200
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:306
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:33
assert(!tx.IsCoinBase())