Bitcoin ABC 0.32.12
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 = 4096;
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;
110
112 std::string strAddedNode;
116};
117
118struct CNodeStats;
120
122 CSerializedNetMsg() = default;
125 // No copying, only moves.
128
131 copy.data = data;
132 copy.m_type = m_type;
133 return copy;
134 }
135
136 std::vector<uint8_t> data;
137 std::string m_type;
138};
139
140const std::vector<std::string> CONNECTION_TYPE_DOC{
141 "outbound-full-relay (default automatic connections)",
142 "block-relay-only (does not relay transactions or addresses)",
143 "inbound (initiated by the peer)",
144 "manual (added via addnode RPC or -addnode/-connect configuration options)",
145 "addr-fetch (short-lived automatic connection for soliciting addresses)",
146 "feeler (short-lived automatic connection for testing addresses)"};
147
154void Discover();
155
156uint16_t GetListenPort();
157
158enum {
159 // unknown
161 // address a local interface listens on
163 // address explicit bound to
165 // address reported by UPnP or NAT-PMP
167 // address explicitly specified (-externalip=)
169
172
173bool IsPeerAddrLocalGood(CNode *pnode);
175std::optional<CService> GetLocalAddrForPeer(CNode &node);
176
181void SetReachable(enum Network net, bool reachable);
183bool IsReachable(enum Network net);
185bool IsReachable(const CNetAddr &addr);
186
187bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
188bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
189void RemoveLocal(const CService &addr);
190bool SeenLocal(const CService &addr);
191bool IsLocal(const CService &addr);
192bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
193CService GetLocalAddress(const CNetAddr &addrPeer);
194
195extern bool fDiscover;
196extern bool fListen;
197
200 uint16_t nPort;
201};
202
204extern std::map<CNetAddr, LocalServiceInfo>
206
207extern const std::string NET_MESSAGE_TYPE_OTHER;
208typedef std::map</* message type */ std::string, /* total bytes */ uint64_t>
210
218 std::chrono::seconds m_last_send;
219 std::chrono::seconds m_last_recv;
220 std::chrono::seconds m_last_tx_time;
221 std::chrono::seconds m_last_proof_time;
222 std::chrono::seconds m_last_block_time;
223 std::chrono::seconds m_connected;
224 int64_t nTimeOffset;
225 std::string m_addr_name;
227 std::string cleanSubVer;
229 // We requested high bandwidth connection to peer
231 // Peer requested high bandwidth connection
234 uint64_t nSendBytes;
236 uint64_t nRecvBytes;
239 std::chrono::microseconds m_last_ping_time;
240 std::chrono::microseconds m_min_ping_time;
241 // Our address, as reported by the peer
242 std::string addrLocal;
243 // Address of this peer
245 // Bind address of our side of the connection
247 // Network the peer connected through
249 uint32_t m_mapped_as;
251 std::optional<double> m_availabilityScore;
252};
253
260public:
264 std::chrono::microseconds m_time{0};
265 bool m_valid_netmagic = false;
266 bool m_valid_header = false;
267 bool m_valid_checksum = false;
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(const Config &config,
298 std::chrono::microseconds time) = 0;
300};
301
303private:
306
307 // Parsing header (false) or data (true)
309 // Partially received header.
311 // Complete header.
313 // Received message data.
315 uint32_t nHdrPos;
316 uint32_t nDataPos;
317
318 const uint256 &GetMessageHash() const;
319 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
320 int readData(Span<const uint8_t> msg_bytes);
321
322 void Reset() {
323 vRecv.clear();
324 hdrbuf.clear();
325 hdrbuf.resize(24);
326 in_data = false;
327 nHdrPos = 0;
328 nDataPos = 0;
330 hasher.Reset();
331 }
332
333public:
335 const CMessageHeader::MessageMagic &pchMessageStartIn)
336 : hdr(pchMessageStartIn) {
337 Reset();
338 }
339
340 bool Complete() const override {
341 if (!in_data) {
342 return false;
343 }
344
345 return (hdr.nMessageSize == nDataPos);
346 }
347
348 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
349 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
350 if (ret < 0) {
351 Reset();
352 } else {
353 msg_bytes = msg_bytes.subspan(ret);
354 }
355 return ret;
356 }
357
358 CNetMessage GetMessage(const Config &config,
359 std::chrono::microseconds time) override;
360};
361
366public:
367 // prepare message for transport (header construction, error-correction
368 // computation, payload encryption, etc.)
369 virtual void prepareForTransport(const Config &config,
371 std::vector<uint8_t> &header) const = 0;
373};
374
376public:
377 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
378 std::vector<uint8_t> &header) const override;
379};
380
382 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
384 bool prefer_evict = false;
386};
387
389class CNode {
390public:
391 // Used only by SocketHandler thread
392 const std::unique_ptr<TransportDeserializer> m_deserializer;
393 const std::unique_ptr<const TransportSerializer> m_serializer;
394
396
406 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
407
409 size_t nSendSize GUARDED_BY(cs_vSend){0};
411 size_t nSendOffset GUARDED_BY(cs_vSend){0};
412 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
413 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
417
418 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
419
420 std::atomic<std::chrono::seconds> m_last_send{0s};
421 std::atomic<std::chrono::seconds> m_last_recv{0s};
423 const std::chrono::seconds m_connected;
424 std::atomic<int64_t> nTimeOffset{0};
425 // Address of this peer
427 // Bind address of our side of the connection
429 const std::string m_addr_name;
432 const bool m_inbound_onion;
433 std::atomic<int> nVersion{0};
434 // The nonce provided by the remote host.
435 uint64_t nRemoteHostNonce{0};
436 // The extra entropy provided by the remote host.
443 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
444 // This peer is preferred for eviction.
445 const bool m_prefer_evict{false};
446 bool HasPermission(NetPermissionFlags permission) const {
448 }
449 std::atomic_bool fSuccessfullyConnected{false};
450 // Setting fDisconnect to true will cause the node to be disconnected the
451 // next time DisconnectNodes() runs
452 std::atomic_bool fDisconnect{false};
454 std::atomic<int> nRefCount{0};
455
456 const uint64_t nKeyedNetGroup;
457 std::atomic_bool fPauseRecv{false};
458 std::atomic_bool fPauseSend{false};
459
461
465
473 std::optional<std::pair<CNetMessage, bool>> PollMessage()
475
480 void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes)
482 mapSendBytesPerMsgType[msg_type] += sent_bytes;
483 }
484
486 switch (m_conn_type) {
490 return true;
495 return false;
496 } // no default case, so the compiler can warn about missing cases
497
498 assert(false);
499 }
500
501 bool IsFullOutboundConn() const {
504 }
505
507
508 bool IsBlockOnlyConn() const {
510 }
511
513
514 bool IsAddrFetchConn() const {
516 }
517
518 bool IsInboundConn() const {
520 }
521
524 }
525
527 switch (m_conn_type) {
531 return false;
536 return true;
537 } // no default case, so the compiler can warn about missing cases
538
539 assert(false);
540 }
541
554
555 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
556 std::atomic<bool> m_bip152_highbandwidth_to{false};
557 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
558 std::atomic<bool> m_bip152_highbandwidth_from{false};
559
564 std::atomic_bool m_has_all_wanted_services{false};
565
570 std::atomic_bool m_relays_txs{false};
571
576 std::atomic_bool m_bloom_filter_loaded{false};
577
578 // True if we know this peer is using Avalanche (at least polling)
579 std::atomic<bool> m_avalanche_enabled{false};
580
582 // Pubkey used to verify signatures on Avalanche messages from this peer
583 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
584
586 void invsPolled(uint32_t count);
587
589 void invsVoted(uint32_t count);
590
607 void updateAvailabilityScore(double decayFactor);
608 double getAvailabilityScore() const;
609
610 // Store the next time we will consider a getavaaddr message from this peer
611 std::chrono::seconds m_nextGetAvaAddr{0};
612
613 // The last time the node sent us a faulty message
614 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
626
628
636 std::atomic<std::chrono::seconds> m_last_block_time{0s};
637
644 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
645
652 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
653
655 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
656
661 std::atomic<std::chrono::microseconds> m_min_ping_time{
662 std::chrono::microseconds::max()};
663
664 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
665 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
666 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
667 const std::string &addrNameIn, ConnectionType conn_type_in,
668 bool inbound_onion, CNodeOptions &&node_opts = {});
669 CNode(const CNode &) = delete;
670 CNode &operator=(const CNode &) = delete;
671
676 void PongReceived(std::chrono::microseconds ping_time) {
677 m_last_ping_time = ping_time;
678 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
679 }
680
681 NodeId GetId() const { return id; }
682
683 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
684 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
685
686 int GetRefCount() const {
687 assert(nRefCount >= 0);
688 return nRefCount;
689 }
690
700 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
701 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
702
703 void SetCommonVersion(int greatest_common_version) {
705 m_greatest_common_version = greatest_common_version;
706 }
708
711 void SetAddrLocal(const CService &addrLocalIn)
713
715 nRefCount++;
716 return this;
717 }
718
719 void Release() { nRefCount--; }
720
722
723 void copyStats(CNodeStats &stats)
726
727 std::string ConnectionTypeAsString() const {
729 }
730
731private:
732 const NodeId id;
733 const uint64_t nLocalHostNonce;
734 const uint64_t nLocalExtraEntropy;
736
737 const size_t m_recv_flood_size;
738 // Used only by SocketHandler thread
739 std::list<CNetMessage> vRecvMsg;
740
742 std::list<CNetMessage>
744 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
745
746 // Our address, as reported by the peer
749
755 std::atomic<uint64_t> invCounters{0};
756
758 std::atomic<double> availabilityScore{0.};
759
760 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
761 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
762
772 std::unique_ptr<i2p::sam::Session>
773 m_i2p_sam_session GUARDED_BY(m_sock_mutex);
774};
775
780public:
785
787 virtual void InitializeNode(const Config &config, CNode &node,
788 ServiceFlags our_services) = 0;
789
791 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
792
802 virtual bool ProcessMessages(const Config &config, CNode *pnode,
803 std::atomic<bool> &interrupt)
805
813 virtual bool SendMessages(const Config &config, CNode *pnode)
815
816protected:
823};
824
825namespace {
826struct CConnmanTest;
827}
828
830class CConnman {
831public:
832 struct Options {
838 int nMaxAddnode = 0;
839 int nMaxFeeler = 0;
841 std::vector<NetEventsInterface *> m_msgproc;
842 BanMan *m_banman = nullptr;
843 unsigned int nSendBufferMaxSize = 0;
844 unsigned int nReceiveFloodSize = 0;
845 uint64_t nMaxOutboundLimit = 0;
847 std::vector<std::string> vSeedNodes;
848 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
849 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
850 std::vector<NetWhitebindPermissions> vWhiteBinds;
851 std::vector<CService> vBinds;
852 std::vector<CService> onion_binds;
857 std::vector<std::string> m_specified_outgoing;
858 std::vector<std::string> m_added_nodes;
862 };
863
864 void Init(const Options &connOptions)
866 nLocalServices = connOptions.nLocalServices;
867 nMaxConnections = connOptions.nMaxConnections;
868 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
869 nMaxAddnode = connOptions.nMaxAddnode;
870 nMaxFeeler = connOptions.nMaxFeeler;
871 {
872 // Lock cs_main to prevent a potential race with the peer validation
873 // logic thread.
876 std::min(connOptions.m_max_outbound_full_relay,
877 connOptions.nMaxConnections);
878 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
879 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
883 }
884 m_client_interface = connOptions.uiInterface;
885 m_banman = connOptions.m_banman;
886 m_msgproc = connOptions.m_msgproc;
887 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
888 nReceiveFloodSize = connOptions.nReceiveFloodSize;
890 std::chrono::seconds{connOptions.m_peer_connect_timeout};
891 {
893 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
894 }
895 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
896 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
897 {
899 m_added_nodes = connOptions.m_added_nodes;
900 }
901 m_onion_binds = connOptions.onion_binds;
902 whitelist_forcerelay = connOptions.whitelist_forcerelay;
903 whitelist_relay = connOptions.whitelist_relay;
904 }
905
906 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
907 AddrMan &addrmanIn, bool network_active = true);
908 virtual ~CConnman();
909
910 bool Start(CScheduler &scheduler, const Options &options)
913
914 void StopThreads();
915 void StopNodes();
916 void Stop() {
917 StopThreads();
918 StopNodes();
919 };
920
922 bool GetNetworkActive() const { return fNetworkActive; };
924 void SetNetworkActive(bool active);
925 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
926 CSemaphoreGrant *grantOutbound,
927 const char *strDest, ConnectionType conn_type)
929 bool CheckIncomingNonce(uint64_t nonce);
930
931 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
932
933 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
934
935 using NodeFn = std::function<void(CNode *)>;
936 void ForEachNode(const NodeFn &func) {
938 for (auto &&node : m_nodes) {
940 func(node);
941 }
942 }
943 };
944
945 void ForEachNode(const NodeFn &func) const {
947 for (auto &&node : m_nodes) {
949 func(node);
950 }
951 }
952 };
953
954 // Addrman functions
965 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
966 std::optional<Network> network) const;
973 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
974 size_t max_pct);
975
976 // This allows temporarily exceeding m_max_outbound_full_relay, with the
977 // goal of finding a peer that is better than all our current peers.
978 void SetTryNewOutboundPeer(bool flag);
979 bool GetTryNewOutboundPeer() const;
980
982 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
984 }
985
986 // Return the number of outbound peers we have in excess of our target (eg,
987 // if we previously called SetTryNewOutboundPeer(true), and have since set
988 // to false, we may have extra peers that we wish to disconnect). This may
989 // return a value less than (num_outbound_connections - num_outbound_slots)
990 // in cases where some outbound connections are not yet fully connected, or
991 // not yet fully disconnected.
992 int GetExtraFullOutboundCount() const;
993 // Count the number of block-relay-only peers we have over our limit.
994 int GetExtraBlockRelayCount() const;
995
996 bool AddNode(const std::string &node)
998 bool RemoveAddedNode(const std::string &node)
1000 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
1002
1017 bool AddConnection(const std::string &address, ConnectionType conn_type)
1019
1020 size_t GetNodeCount(ConnectionDirection) const;
1021 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1022 bool GetNodeStats(NodeId id, CNodeStats &stats) const;
1023 bool DisconnectNode(const std::string &node);
1024 bool DisconnectNode(const CSubNet &subnet);
1025 bool DisconnectNode(const CNetAddr &addr);
1026 bool DisconnectNode(NodeId id);
1027
1035
1040 };
1043 }
1044
1045 uint64_t GetMaxOutboundTarget() const;
1046 std::chrono::seconds GetMaxOutboundTimeframe() const;
1047
1051 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1052
1055 uint64_t GetOutboundTargetBytesLeft() const;
1056
1059 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1060
1061 uint64_t GetTotalBytesRecv() const;
1062 uint64_t GetTotalBytesSent() const;
1063
1065 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1066
1068
1074 std::chrono::seconds now) const;
1075
1076private:
1078 public:
1079 std::shared_ptr<Sock> sock;
1081 NetPermissions::AddFlag(flags, m_permissions);
1082 }
1083 ListenSocket(std::shared_ptr<Sock> sock_,
1084 NetPermissionFlags permissions_)
1085 : sock(sock_), m_permissions(permissions_) {}
1086
1087 private:
1089 };
1090
1091 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1092 NetPermissionFlags permissions);
1093 bool Bind(const CService &addr, unsigned int flags,
1094 NetPermissionFlags permissions);
1095 bool InitBinds(const Options &options);
1096
1100 void AddAddrFetch(const std::string &strDest)
1102 void ProcessAddrFetch()
1105 void
1106 ThreadOpenConnections(std::vector<std::string> connect,
1107 std::function<void(const CAddress &, ConnectionType)>
1108 mockOpenConnection)
1113 void AcceptConnection(const ListenSocket &hListenSocket);
1114
1123 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1124 NetPermissionFlags permission_flags,
1125 const CAddress &addr_bind,
1126 const CAddress &addr);
1127
1128 void DisconnectNodes();
1131 bool InactivityCheck(const CNode &node) const;
1132
1138 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1139
1145
1152 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1153 const Sock::EventsPerSock &events_per_sock)
1155
1160 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1161
1165
1166 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1167
1168 CNode *FindNode(const CNetAddr &ip);
1169 CNode *FindNode(const CSubNet &subNet);
1170 CNode *FindNode(const std::string &addrName);
1171 CNode *FindNode(const CService &addr);
1172
1177 bool AlreadyConnectedToAddress(const CAddress &addr);
1178
1180 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1181 bool fCountFailure, ConnectionType conn_type)
1183 ;
1185 NetPermissionFlags &flags, const CNetAddr &addr,
1186 const std::vector<NetWhitelistPermissions> &ranges) const;
1187
1188 void DeleteNode(CNode *pnode);
1189
1191
1196 std::pair<size_t, bool> SocketSendData(CNode &node) const
1198
1199 void DumpAddresses();
1200
1201 // Network stats
1202 void RecordBytesRecv(uint64_t bytes);
1203 void RecordBytesSent(uint64_t bytes);
1204
1209
1210 // Whether the node should be passed out in ForEach* callbacks
1211 static bool NodeFullyConnected(const CNode *pnode);
1212
1214
1215 // Network usage totals
1217 std::atomic<uint64_t> nTotalBytesRecv{0};
1218 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1219
1220 // outbound limit & stats
1221 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1222 std::chrono::seconds
1223 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1224 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1225
1226 // P2P timeout in seconds
1227 std::chrono::seconds m_peer_connect_timeout;
1228
1229 // Whitelisted ranges. Any node connecting from these is automatically
1230 // whitelisted (as well as those connecting to whitelisted binds).
1231 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1232 // Whitelisted ranges for outgoing connections.
1233 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1234
1235 unsigned int nSendBufferMaxSize{0};
1236 unsigned int nReceiveFloodSize{0};
1237
1238 std::vector<ListenSocket> vhListenSocket;
1239 std::atomic<bool> fNetworkActive{true};
1242 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1244 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1246 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1247 std::list<CNode *> m_nodes_disconnected;
1249 std::atomic<NodeId> nLastNodeId{0};
1250 unsigned int nPrevNodeCount{0};
1251
1259 std::vector<CAddress> m_addrs_response_cache;
1260 std::chrono::microseconds m_cache_entry_expiration{0};
1261 };
1262
1277 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1278
1290 std::atomic<ServiceFlags> nLocalServices;
1291
1292 std::unique_ptr<CSemaphore> semOutbound;
1293 std::unique_ptr<CSemaphore> semAddnode;
1295
1296 // How many full-relay (tx, block, addr) outbound peers we want
1298
1299 // How many block-relay only outbound peers we want
1300 // We do not relay tx or addr messages with these peers
1302
1303 // How many avalanche enabled outbound peers we want
1305
1311 // FIXME m_msgproc is a terrible name
1312 std::vector<NetEventsInterface *> m_msgproc;
1318
1323 std::vector<CAddress> m_anchors;
1324
1326 const uint64_t nSeed0, nSeed1;
1327
1329 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1330
1331 std::condition_variable condMsgProc;
1333 std::atomic<bool> flagInterruptMsgProc{false};
1334
1342
1348 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1349
1356
1362
1368 std::atomic_bool m_start_extra_block_relay_peers{false};
1369
1374 std::vector<CService> m_onion_binds;
1375
1380
1388 std::queue<std::unique_ptr<i2p::sam::Session>>
1390
1395 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1396
1402
1408
1415 public:
1416 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1417 {
1418 LOCK(connman.m_nodes_mutex);
1419 m_nodes_copy = connman.m_nodes;
1420 for (auto &node : m_nodes_copy) {
1421 node->AddRef();
1422 }
1423 }
1424 if (shuffle) {
1425 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1427 }
1428 }
1429
1431 for (auto &node : m_nodes_copy) {
1432 node->Release();
1433 }
1434 }
1435
1436 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1437
1438 private:
1439 std::vector<CNode *> m_nodes_copy;
1440 };
1441
1442 friend struct ::CConnmanTest;
1443 friend struct ConnmanTestMsg;
1444};
1445
1446std::string getSubVersionEB(uint64_t MaxBlockSize);
1447std::string userAgent(const Config &config);
1448
1450void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1451 Span<const uint8_t> data, bool is_incoming);
1452
1456extern std::function<void(const CAddress &addr, const std::string &msg_type,
1457 Span<const uint8_t> data, bool is_incoming)>
1459
1460#endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:542
#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:443
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:1414
const std::vector< CNode * > & Nodes() const
Definition: net.h:1436
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1416
std::vector< CNode * > m_nodes_copy
Definition: net.h:1439
Definition: net.h:830
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1407
std::condition_variable condMsgProc
Definition: net.h:1331
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1218
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:1117
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1223
std::thread threadMessageHandler
Definition: net.h:1354
void ForEachNode(const NodeFn &func)
Definition: net.h:936
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:2924
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1041
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:2940
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1231
CClientUIInterface * m_client_interface
Definition: net.h:1310
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2164
void ForEachNode(const NodeFn &func) const
Definition: net.h:945
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3135
void DeleteNode(CNode *pnode)
Definition: net.cpp:2705
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2796
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:928
bool GetNetworkActive() const
Definition: net.h:922
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:393
int m_max_outbound
Definition: net.h:1308
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:1395
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1621
void Stop()
Definition: net.h:916
int m_max_outbound_block_relay
Definition: net.h:1301
std::thread threadI2PAcceptIncoming
Definition: net.h:1355
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1625
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1333
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2626
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1458
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1276
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:1330
NodeId GetNewNodeId()
Definition: net.cpp:2429
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1341
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1293
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2492
std::atomic< NodeId > nLastNodeId
Definition: net.h:1249
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2900
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1653
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1450
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1317
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:2963
std::thread threadDNSAddressSeed
Definition: net.h:1350
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1290
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2215
const uint64_t nSeed1
Definition: net.h:1326
void StartExtraBlockRelayPeers()
Definition: net.h:981
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1323
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2920
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1401
friend struct ConnmanTestMsg
Definition: net.h:1443
unsigned int nPrevNodeCount
Definition: net.h:1250
void NotifyNumConnectionsChanged()
Definition: net.cpp:1217
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2983
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2851
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1227
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:1361
bool InitBinds(const Options &options)
Definition: net.cpp:2455
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:134
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1221
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1238
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:2114
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2012
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3147
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2915
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1292
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2081
RecursiveMutex cs_totalBytesSent
Definition: net.h:1216
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2433
std::thread threadOpenConnections
Definition: net.h:1353
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2808
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1602
Mutex m_addr_fetches_mutex
Definition: net.h:1243
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1236
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:353
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2826
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2024
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1326
unsigned int nReceiveFloodSize
Definition: net.h:1236
int GetExtraFullOutboundCount() const
Definition: net.cpp:1637
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2974
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:851
RecursiveMutex m_nodes_mutex
Definition: net.h:1248
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:3085
int nMaxConnections
Definition: net.h:1294
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2418
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:2719
std::function< void(CNode *)> NodeFn
Definition: net.h:935
void SetNetworkActive(bool active)
Definition: net.cpp:2404
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1247
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:1038
AddrMan & addrman
Definition: net.h:1241
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1302
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3151
Mutex mutexMsgProc
Definition: net.h:1332
bool fAddressesInitialized
Definition: net.h:1240
virtual ~CConnman()
Definition: net.cpp:2713
void StopThreads()
Definition: net.cpp:2649
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2784
std::thread threadOpenAddedConnections
Definition: net.h:1352
Mutex m_added_nodes_mutex
Definition: net.h:1245
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:602
const Config * config
Definition: net.h:1213
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:864
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:398
int m_max_outbound_full_relay
Definition: net.h:1297
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1379
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1306
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2896
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:1231
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1442
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:1008
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3089
void StopNodes()
Definition: net.cpp:2670
bool GetUseAddrmanOutgoing() const
Definition: net.h:923
unsigned int nSendBufferMaxSize
Definition: net.h:1235
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1348
bool m_use_addrman_outgoing
Definition: net.h:1309
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1233
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:1277
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1217
std::atomic< bool > fNetworkActive
Definition: net.h:1239
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1368
void DisconnectNodes()
Definition: net.cpp:1167
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1429
void DumpAddresses()
Definition: net.cpp:1593
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:1374
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:424
int nMaxFeeler
Definition: net.h:1307
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1312
std::thread threadSocketHandler
Definition: net.h:1351
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2978
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1667
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:979
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2253
int m_max_avalanche_outbound
Definition: net.h:1304
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:72
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:47
Network address.
Definition: netaddress.h:114
Transport protocol agnostic message container.
Definition: net.h:259
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:264
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
bool m_valid_checksum
Definition: net.h:267
bool m_valid_header
Definition: net.h:266
DataStream m_recv
received message data
Definition: net.h:262
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
bool m_valid_netmagic
Definition: net.h:265
Information about a peer.
Definition: net.h:389
Mutex cs_avalanche_pubkey
Definition: net.h:581
const CAddress addrBind
Definition: net.h:428
bool IsFeelerConn() const
Definition: net.h:512
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:423
bool ExpectServicesFromConn() const
Definition: net.h:526
std::atomic< int > nVersion
Definition: net.h:433
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:564
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:418
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:758
bool IsInboundConn() const
Definition: net.h:518
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:446
std::atomic_bool fPauseRecv
Definition: net.h:457
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:485
NodeId GetId() const
Definition: net.h:681
bool IsManualConn() const
Definition: net.h:506
std::atomic< int64_t > nTimeOffset
Definition: net.h:424
const std::string m_addr_name
Definition: net.h:429
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:727
void SetCommonVersion(int greatest_common_version)
Definition: net.h:703
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:556
std::list< CNetMessage > vRecvMsg
Definition: net.h:739
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:570
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:558
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:676
std::atomic_bool fSuccessfullyConnected
Definition: net.h:449
const bool m_prefer_evict
Definition: net.h:445
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:744
bool IsAddrFetchConn() const
Definition: net.h:514
uint64_t GetLocalNonce() const
Definition: net.h:683
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:3016
const CAddress addr
Definition: net.h:426
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:629
CSemaphoreGrant grantOutbound
Definition: net.h:453
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:456
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:454
std::atomic< int > m_greatest_common_version
Definition: net.h:735
bool IsBlockOnlyConn() const
Definition: net.h:508
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition: net.cpp:3052
int GetCommonVersion() const
Definition: net.h:707
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:501
uint64_t nRemoteHostNonce
Definition: net.h:435
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:442
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:393
Mutex cs_vSend
Definition: net.h:414
CNode * AddRef()
Definition: net.h:714
std::atomic_bool fPauseSend
Definition: net.h:458
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:611
uint64_t nRemoteExtraEntropy
Definition: net.h:437
int GetRefCount() const
Definition: net.h:686
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:3069
uint64_t GetLocalExtraEntropy() const
Definition: net.h:684
SteadyMilliseconds m_last_poll
Definition: net.h:627
double getAvailabilityScore() const
Definition: net.cpp:3010
Mutex m_msg_process_queue_mutex
Definition: net.h:741
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:411
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:576
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:460
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:642
const size_t m_recv_flood_size
Definition: net.h:737
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:646
const uint64_t nLocalHostNonce
Definition: net.h:733
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:655
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:2995
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:409
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:614
const uint64_t nLocalExtraEntropy
Definition: net.h:734
const NetPermissionFlags m_permission_flags
Definition: net.h:395
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:694
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2987
Mutex m_addr_local_mutex
Definition: net.h:747
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:432
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:661
const NodeId id
Definition: net.h:732
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
Definition: net.h:619
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:480
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:652
Mutex cs_vRecv
Definition: net.h:416
std::atomic< bool > m_avalanche_enabled
Definition: net.h:579
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:636
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:392
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:412
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:755
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:415
std::atomic_bool fDisconnect
Definition: net.h:452
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:421
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:625
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:644
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:623
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:2991
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:592
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:420
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
bool IsAvalancheOutboundConnection() const
Definition: net.h:522
void Release()
Definition: net.h:719
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:443
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:779
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:784
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 ~TransportDeserializer()
Definition: net.h:299
virtual bool Complete() const =0
virtual CNetMessage GetMessage(const Config &config, std::chrono::microseconds time)=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:365
virtual ~TransportSerializer()
Definition: net.h:372
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const =0
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
Definition: net.cpp:792
CMessageHeader hdr
Definition: net.h:312
const uint256 & GetMessageHash() const
Definition: net.cpp:783
uint32_t nDataPos
Definition: net.h:316
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn)
Definition: net.h:334
uint32_t nHdrPos
Definition: net.h:315
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:348
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:766
bool Complete() const override
Definition: net.h:340
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:733
CHash256 hasher
Definition: net.h:304
DataStream hdrbuf
Definition: net.h:310
uint256 data_hash
Definition: net.h:305
DataStream vRecv
Definition: net.h:314
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition: net.cpp:835
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: init.h:31
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:239
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:140
uint16_t GetListenPort()
Definition: net.cpp:139
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:348
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:223
void RemoveLocal(const CService &addr)
Definition: net.cpp:313
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:280
bool fDiscover
Definition: net.cpp:127
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 bool DEFAULT_FORCEDNSSEED
Definition: net.h:105
bool fListen
Definition: net.cpp:128
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:245
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:114
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:319
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:3239
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:3173
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:129
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:174
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:3207
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:209
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:160
@ LOCAL_MAPPED
Definition: net.h:166
@ LOCAL_MANUAL
Definition: net.h:168
@ LOCAL_MAX
Definition: net.h:170
@ LOCAL_BIND
Definition: net.h:164
@ LOCAL_IF
Definition: net.h:162
std::string userAgent(const Config &config)
Definition: net.cpp:3187
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:2353
bool IsReachable(enum Network net)
Definition: net.cpp:327
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:337
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:336
@ NODE_NONE
Definition: protocol.h:339
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:115
CService resolvedAddress
Definition: net.h:113
bool fConnected
Definition: net.h:114
std::string strAddedNode
Definition: net.h:112
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1258
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1260
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1259
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1080
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1083
NetPermissionFlags m_permissions
Definition: net.h:1088
std::shared_ptr< Sock > sock
Definition: net.h:1079
int m_max_outbound_block_relay
Definition: net.h:836
unsigned int nReceiveFloodSize
Definition: net.h:844
int m_max_outbound_full_relay
Definition: net.h:835
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:850
uint64_t nMaxOutboundLimit
Definition: net.h:845
CClientUIInterface * uiInterface
Definition: net.h:840
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:848
int m_max_avalanche_outbound
Definition: net.h:837
std::vector< CService > onion_binds
Definition: net.h:852
int nMaxFeeler
Definition: net.h:839
std::vector< std::string > m_specified_outgoing
Definition: net.h:857
bool whitelist_relay
Definition: net.h:861
int nMaxConnections
Definition: net.h:834
ServiceFlags nLocalServices
Definition: net.h:833
std::vector< std::string > m_added_nodes
Definition: net.h:858
int64_t m_peer_connect_timeout
Definition: net.h:846
std::vector< CService > vBinds
Definition: net.h:851
unsigned int nSendBufferMaxSize
Definition: net.h:843
bool m_i2p_accept_incoming
Definition: net.h:859
std::vector< std::string > vSeedNodes
Definition: net.h:847
BanMan * m_banman
Definition: net.h:842
bool m_use_addrman_outgoing
Definition: net.h:856
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:841
bool whitelist_forcerelay
Definition: net.h:860
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:855
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:849
int nMaxAddnode
Definition: net.h:838
NetPermissionFlags permission_flags
Definition: net.h:383
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition: net.h:382
bool prefer_evict
Definition: net.h:384
size_t recv_flood_size
Definition: net.h:385
POD that contains various stats about a node.
Definition: net.h:216
std::string addrLocal
Definition: net.h:242
CAddress addrBind
Definition: net.h:246
uint64_t nRecvBytes
Definition: net.h:236
std::chrono::microseconds m_last_ping_time
Definition: net.h:239
uint32_t m_mapped_as
Definition: net.h:249
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:237
bool fInbound
Definition: net.h:228
uint64_t nSendBytes
Definition: net.h:234
std::chrono::seconds m_last_recv
Definition: net.h:219
std::optional< double > m_availabilityScore
Definition: net.h:251
std::chrono::seconds m_last_proof_time
Definition: net.h:221
ConnectionType m_conn_type
Definition: net.h:250
std::chrono::seconds m_last_send
Definition: net.h:218
std::chrono::seconds m_last_tx_time
Definition: net.h:220
CAddress addr
Definition: net.h:244
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:235
std::chrono::microseconds m_min_ping_time
Definition: net.h:240
int64_t nTimeOffset
Definition: net.h:224
std::chrono::seconds m_connected
Definition: net.h:223
bool m_bip152_highbandwidth_from
Definition: net.h:232
bool m_bip152_highbandwidth_to
Definition: net.h:230
std::string m_addr_name
Definition: net.h:225
int nVersion
Definition: net.h:226
std::chrono::seconds m_last_block_time
Definition: net.h:222
Network m_network
Definition: net.h:248
NodeId nodeid
Definition: net.h:217
std::string cleanSubVer
Definition: net.h:227
int m_starting_height
Definition: net.h:233
NetPermissionFlags m_permission_flags
Definition: net.h:238
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:129
std::vector< uint8_t > data
Definition: net.h:136
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:137
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:200
int nScore
Definition: net.h:199
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())