Bitcoin ABC 0.32.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.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 <thread>
49#include <vector>
50
51class AddrMan;
52class BanMan;
53class Config;
54class CNode;
55class CScheduler;
57struct bilingual_str;
58
63static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
65static constexpr auto FEELER_INTERVAL = 2min;
67static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
69static const unsigned int MAX_SUBVERSION_LENGTH = 256;
76static const int MAX_ADDNODE_CONNECTIONS = 8;
85static const int MAX_FEELER_CONNECTIONS = 1;
87static const bool DEFAULT_LISTEN = true;
93static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
95static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
97static const bool DEFAULT_BLOCKSONLY = false;
99static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
101static const int NUM_FDS_MESSAGE_CAPTURE = 1;
102
103static const bool DEFAULT_FORCEDNSSEED = false;
104static const bool DEFAULT_DNSSEED = true;
105static const bool DEFAULT_FIXEDSEEDS = true;
106static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
107static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
108
110 std::string strAddedNode;
114};
115
116struct CNodeStats;
118
120 CSerializedNetMsg() = default;
123 // No copying, only moves.
126
129 copy.data = data;
130 copy.m_type = m_type;
131 return copy;
132 }
133
134 std::vector<uint8_t> data;
135 std::string m_type;
136};
137
138const std::vector<std::string> CONNECTION_TYPE_DOC{
139 "outbound-full-relay (default automatic connections)",
140 "block-relay-only (does not relay transactions or addresses)",
141 "inbound (initiated by the peer)",
142 "manual (added via addnode RPC or -addnode/-connect configuration options)",
143 "addr-fetch (short-lived automatic connection for soliciting addresses)",
144 "feeler (short-lived automatic connection for testing addresses)"};
145
152void Discover();
153
154uint16_t GetListenPort();
155
156enum {
157 // unknown
159 // address a local interface listens on
161 // address explicit bound to
163 // address reported by UPnP or NAT-PMP
165 // address explicitly specified (-externalip=)
167
170
171bool IsPeerAddrLocalGood(CNode *pnode);
173std::optional<CService> GetLocalAddrForPeer(CNode &node);
174
179void SetReachable(enum Network net, bool reachable);
181bool IsReachable(enum Network net);
183bool IsReachable(const CNetAddr &addr);
184
185bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
186bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
187void RemoveLocal(const CService &addr);
188bool SeenLocal(const CService &addr);
189bool IsLocal(const CService &addr);
190bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
191CService GetLocalAddress(const CNetAddr &addrPeer);
192
193extern bool fDiscover;
194extern bool fListen;
195
198 uint16_t nPort;
199};
200
202extern std::map<CNetAddr, LocalServiceInfo>
204
205extern const std::string NET_MESSAGE_TYPE_OTHER;
206typedef std::map</* message type */ std::string, /* total bytes */ uint64_t>
208
216 std::chrono::seconds m_last_send;
217 std::chrono::seconds m_last_recv;
218 std::chrono::seconds m_last_tx_time;
219 std::chrono::seconds m_last_proof_time;
220 std::chrono::seconds m_last_block_time;
221 std::chrono::seconds m_connected;
222 int64_t nTimeOffset;
223 std::string m_addr_name;
225 std::string cleanSubVer;
227 // We requested high bandwidth connection to peer
229 // Peer requested high bandwidth connection
232 uint64_t nSendBytes;
234 uint64_t nRecvBytes;
237 std::chrono::microseconds m_last_ping_time;
238 std::chrono::microseconds m_min_ping_time;
239 // Our address, as reported by the peer
240 std::string addrLocal;
241 // Address of this peer
243 // Bind address of our side of the connection
245 // Network the peer connected through
247 uint32_t m_mapped_as;
249 std::optional<double> m_availabilityScore;
250};
251
258public:
262 std::chrono::microseconds m_time{0};
263 bool m_valid_netmagic = false;
264 bool m_valid_header = false;
265 bool m_valid_checksum = false;
267 uint32_t m_message_size{0};
270 std::string m_type;
271
272 CNetMessage(DataStream &&recv_in) : m_recv(std::move(recv_in)) {}
273 // Only one CNetMessage object will exist for the same message on either
274 // the receive or processing queue. For performance reasons we therefore
275 // delete the copy constructor and assignment operator to avoid the
276 // possibility of copying CNetMessage objects.
278 CNetMessage(const CNetMessage &) = delete;
281};
282
289public:
290 // returns true if the current deserialization is complete
291 virtual bool Complete() const = 0;
293 virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
294 // decomposes a message from the context
295 virtual CNetMessage GetMessage(const Config &config,
296 std::chrono::microseconds time) = 0;
298};
299
301private:
304
305 // Parsing header (false) or data (true)
307 // Partially received header.
309 // Complete header.
311 // Received message data.
313 uint32_t nHdrPos;
314 uint32_t nDataPos;
315
316 const uint256 &GetMessageHash() const;
317 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
318 int readData(Span<const uint8_t> msg_bytes);
319
320 void Reset() {
321 vRecv.clear();
322 hdrbuf.clear();
323 hdrbuf.resize(24);
324 in_data = false;
325 nHdrPos = 0;
326 nDataPos = 0;
328 hasher.Reset();
329 }
330
331public:
333 const CMessageHeader::MessageMagic &pchMessageStartIn)
334 : hdr(pchMessageStartIn) {
335 Reset();
336 }
337
338 bool Complete() const override {
339 if (!in_data) {
340 return false;
341 }
342
343 return (hdr.nMessageSize == nDataPos);
344 }
345
346 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
347 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
348 if (ret < 0) {
349 Reset();
350 } else {
351 msg_bytes = msg_bytes.subspan(ret);
352 }
353 return ret;
354 }
355
356 CNetMessage GetMessage(const Config &config,
357 std::chrono::microseconds time) override;
358};
359
364public:
365 // prepare message for transport (header construction, error-correction
366 // computation, payload encryption, etc.)
367 virtual void prepareForTransport(const Config &config,
369 std::vector<uint8_t> &header) const = 0;
371};
372
374public:
375 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
376 std::vector<uint8_t> &header) const override;
377};
378
381 bool prefer_evict = false;
383};
384
386class CNode {
387public:
388 // Used only by SocketHandler thread
389 const std::unique_ptr<TransportDeserializer> m_deserializer;
390 const std::unique_ptr<const TransportSerializer> m_serializer;
391
393
403 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
404
406 size_t nSendSize GUARDED_BY(cs_vSend){0};
408 size_t nSendOffset GUARDED_BY(cs_vSend){0};
409 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
410 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
414
415 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
416
417 std::atomic<std::chrono::seconds> m_last_send{0s};
418 std::atomic<std::chrono::seconds> m_last_recv{0s};
420 const std::chrono::seconds m_connected;
421 std::atomic<int64_t> nTimeOffset{0};
422 // Address of this peer
424 // Bind address of our side of the connection
426 const std::string m_addr_name;
429 const bool m_inbound_onion;
430 std::atomic<int> nVersion{0};
431 // The nonce provided by the remote host.
432 uint64_t nRemoteHostNonce{0};
433 // The extra entropy provided by the remote host.
440 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
441 // This peer is preferred for eviction.
442 const bool m_prefer_evict{false};
443 bool HasPermission(NetPermissionFlags permission) const {
445 }
446 std::atomic_bool fSuccessfullyConnected{false};
447 // Setting fDisconnect to true will cause the node to be disconnected the
448 // next time DisconnectNodes() runs
449 std::atomic_bool fDisconnect{false};
451 std::atomic<int> nRefCount{0};
452
453 const uint64_t nKeyedNetGroup;
454 std::atomic_bool fPauseRecv{false};
455 std::atomic_bool fPauseSend{false};
456
458
462
470 std::optional<std::pair<CNetMessage, bool>> PollMessage()
472
477 void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes)
479 mapSendBytesPerMsgType[msg_type] += sent_bytes;
480 }
481
483 switch (m_conn_type) {
487 return true;
492 return false;
493 } // no default case, so the compiler can warn about missing cases
494
495 assert(false);
496 }
497
498 bool IsFullOutboundConn() const {
501 }
502
504
505 bool IsBlockOnlyConn() const {
507 }
508
510
511 bool IsAddrFetchConn() const {
513 }
514
515 bool IsInboundConn() const {
517 }
518
521 }
522
524 switch (m_conn_type) {
528 return false;
533 return true;
534 } // no default case, so the compiler can warn about missing cases
535
536 assert(false);
537 }
538
551
552 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
553 std::atomic<bool> m_bip152_highbandwidth_to{false};
554 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
555 std::atomic<bool> m_bip152_highbandwidth_from{false};
556
561 std::atomic_bool m_has_all_wanted_services{false};
562
567 std::atomic_bool m_relays_txs{false};
568
573 std::atomic_bool m_bloom_filter_loaded{false};
574
575 // True if we know this peer is using Avalanche (at least polling)
576 std::atomic<bool> m_avalanche_enabled{false};
577
579 // Pubkey used to verify signatures on Avalanche messages from this peer
580 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
581
583 void invsPolled(uint32_t count);
584
586 void invsVoted(uint32_t count);
587
604 void updateAvailabilityScore(double decayFactor);
605 double getAvailabilityScore() const;
606
607 // Store the next time we will consider a getavaaddr message from this peer
608 std::chrono::seconds m_nextGetAvaAddr{0};
609
610 // The last time the node sent us a faulty message
611 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
623
625
633 std::atomic<std::chrono::seconds> m_last_block_time{0s};
634
641 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
642
649 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
650
652 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
653
658 std::atomic<std::chrono::microseconds> m_min_ping_time{
659 std::chrono::microseconds::max()};
660
661 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
662 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
663 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
664 const std::string &addrNameIn, ConnectionType conn_type_in,
665 bool inbound_onion, CNodeOptions &&node_opts = {});
666 CNode(const CNode &) = delete;
667 CNode &operator=(const CNode &) = delete;
668
673 void PongReceived(std::chrono::microseconds ping_time) {
674 m_last_ping_time = ping_time;
675 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
676 }
677
678 NodeId GetId() const { return id; }
679
680 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
681 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
682
683 int GetRefCount() const {
684 assert(nRefCount >= 0);
685 return nRefCount;
686 }
687
697 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
698 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
699
700 void SetCommonVersion(int greatest_common_version) {
702 m_greatest_common_version = greatest_common_version;
703 }
705
708 void SetAddrLocal(const CService &addrLocalIn)
710
712 nRefCount++;
713 return this;
714 }
715
716 void Release() { nRefCount--; }
717
719
720 void copyStats(CNodeStats &stats)
723
724 std::string ConnectionTypeAsString() const {
726 }
727
728private:
729 const NodeId id;
730 const uint64_t nLocalHostNonce;
731 const uint64_t nLocalExtraEntropy;
733
734 const size_t m_recv_flood_size;
735 // Used only by SocketHandler thread
736 std::list<CNetMessage> vRecvMsg;
737
739 std::list<CNetMessage>
741 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
742
743 // Our address, as reported by the peer
746
752 std::atomic<uint64_t> invCounters{0};
753
755 std::atomic<double> availabilityScore{0.};
756
757 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
758 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
759};
760
765public:
770
772 virtual void InitializeNode(const Config &config, CNode &node,
773 ServiceFlags our_services) = 0;
774
776 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
777
787 virtual bool ProcessMessages(const Config &config, CNode *pnode,
788 std::atomic<bool> &interrupt)
790
798 virtual bool SendMessages(const Config &config, CNode *pnode)
800
801protected:
808};
809
810namespace {
811struct CConnmanTest;
812}
813
815class CConnman {
816public:
817 struct Options {
823 int nMaxAddnode = 0;
824 int nMaxFeeler = 0;
826 std::vector<NetEventsInterface *> m_msgproc;
827 BanMan *m_banman = nullptr;
828 unsigned int nSendBufferMaxSize = 0;
829 unsigned int nReceiveFloodSize = 0;
830 uint64_t nMaxOutboundLimit = 0;
832 std::vector<std::string> vSeedNodes;
833 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
834 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
835 std::vector<NetWhitebindPermissions> vWhiteBinds;
836 std::vector<CService> vBinds;
837 std::vector<CService> onion_binds;
842 std::vector<std::string> m_specified_outgoing;
843 std::vector<std::string> m_added_nodes;
847 };
848
849 void Init(const Options &connOptions)
851 nLocalServices = connOptions.nLocalServices;
852 nMaxConnections = connOptions.nMaxConnections;
853 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
854 nMaxAddnode = connOptions.nMaxAddnode;
855 nMaxFeeler = connOptions.nMaxFeeler;
856 {
857 // Lock cs_main to prevent a potential race with the peer validation
858 // logic thread.
861 std::min(connOptions.m_max_outbound_full_relay,
862 connOptions.nMaxConnections);
863 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
864 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
868 }
869 m_client_interface = connOptions.uiInterface;
870 m_banman = connOptions.m_banman;
871 m_msgproc = connOptions.m_msgproc;
872 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
873 nReceiveFloodSize = connOptions.nReceiveFloodSize;
875 std::chrono::seconds{connOptions.m_peer_connect_timeout};
876 {
878 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
879 }
880 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
881 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
882 {
884 m_added_nodes = connOptions.m_added_nodes;
885 }
886 m_onion_binds = connOptions.onion_binds;
887 whitelist_forcerelay = connOptions.whitelist_forcerelay;
888 whitelist_relay = connOptions.whitelist_relay;
889 }
890
891 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
892 AddrMan &addrmanIn, bool network_active = true);
893 ~CConnman();
894
895 bool Start(CScheduler &scheduler, const Options &options)
898
899 void StopThreads();
900 void StopNodes();
901 void Stop() {
902 StopThreads();
903 StopNodes();
904 };
905
907 bool GetNetworkActive() const { return fNetworkActive; };
909 void SetNetworkActive(bool active);
910 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
911 CSemaphoreGrant *grantOutbound,
912 const char *strDest, ConnectionType conn_type);
913 bool CheckIncomingNonce(uint64_t nonce);
914
915 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
916
917 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
918
919 using NodeFn = std::function<void(CNode *)>;
920 void ForEachNode(const NodeFn &func) {
922 for (auto &&node : m_nodes) {
924 func(node);
925 }
926 }
927 };
928
929 void ForEachNode(const NodeFn &func) const {
931 for (auto &&node : m_nodes) {
933 func(node);
934 }
935 }
936 };
937
938 // Addrman functions
949 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
950 std::optional<Network> network) const;
957 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
958 size_t max_pct);
959
960 // This allows temporarily exceeding m_max_outbound_full_relay, with the
961 // goal of finding a peer that is better than all our current peers.
962 void SetTryNewOutboundPeer(bool flag);
963 bool GetTryNewOutboundPeer() const;
964
966 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
968 }
969
970 // Return the number of outbound peers we have in excess of our target (eg,
971 // if we previously called SetTryNewOutboundPeer(true), and have since set
972 // to false, we may have extra peers that we wish to disconnect). This may
973 // return a value less than (num_outbound_connections - num_outbound_slots)
974 // in cases where some outbound connections are not yet fully connected, or
975 // not yet fully disconnected.
976 int GetExtraFullOutboundCount() const;
977 // Count the number of block-relay-only peers we have over our limit.
978 int GetExtraBlockRelayCount() const;
979
980 bool AddNode(const std::string &node)
982 bool RemoveAddedNode(const std::string &node)
984 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
986
1001 bool AddConnection(const std::string &address, ConnectionType conn_type);
1002
1003 size_t GetNodeCount(ConnectionDirection) const;
1004 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1005 bool GetNodeStats(NodeId id, CNodeStats &stats) const;
1006 bool DisconnectNode(const std::string &node);
1007 bool DisconnectNode(const CSubNet &subnet);
1008 bool DisconnectNode(const CNetAddr &addr);
1009 bool DisconnectNode(NodeId id);
1010
1018
1023 };
1026 }
1027
1028 uint64_t GetMaxOutboundTarget() const;
1029 std::chrono::seconds GetMaxOutboundTimeframe() const;
1030
1034 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1035
1038 uint64_t GetOutboundTargetBytesLeft() const;
1039
1042 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1043
1044 uint64_t GetTotalBytesRecv() const;
1045 uint64_t GetTotalBytesSent() const;
1046
1048 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1049
1051
1057 std::chrono::seconds now) const;
1058
1059private:
1061 public:
1062 std::shared_ptr<Sock> sock;
1064 NetPermissions::AddFlag(flags, m_permissions);
1065 }
1066 ListenSocket(std::shared_ptr<Sock> sock_,
1067 NetPermissionFlags permissions_)
1068 : sock(sock_), m_permissions(permissions_) {}
1069
1070 private:
1072 };
1073
1074 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1075 NetPermissionFlags permissions);
1076 bool Bind(const CService &addr, unsigned int flags,
1077 NetPermissionFlags permissions);
1078 bool InitBinds(const Options &options);
1079
1082 void AddAddrFetch(const std::string &strDest)
1085 void
1086 ThreadOpenConnections(std::vector<std::string> connect,
1087 std::function<void(const CAddress &, ConnectionType)>
1088 mockOpenConnection)
1093 void AcceptConnection(const ListenSocket &hListenSocket);
1094
1103 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1104 NetPermissionFlags permission_flags,
1105 const CAddress &addr_bind,
1106 const CAddress &addr);
1107
1108 void DisconnectNodes();
1111 bool InactivityCheck(const CNode &node) const;
1112
1118 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1119
1125
1132 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1133 const Sock::EventsPerSock &events_per_sock)
1135
1140 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1141
1145
1146 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1147
1148 CNode *FindNode(const CNetAddr &ip);
1149 CNode *FindNode(const CSubNet &subNet);
1150 CNode *FindNode(const std::string &addrName);
1151 CNode *FindNode(const CService &addr);
1152
1157 bool AlreadyConnectedToAddress(const CAddress &addr);
1158
1160 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1161 bool fCountFailure, ConnectionType conn_type);
1163 NetPermissionFlags &flags, const CNetAddr &addr,
1164 const std::vector<NetWhitelistPermissions> &ranges) const;
1165
1166 void DeleteNode(CNode *pnode);
1167
1169
1174 std::pair<size_t, bool> SocketSendData(CNode &node) const
1176
1177 void DumpAddresses();
1178
1179 // Network stats
1180 void RecordBytesRecv(uint64_t bytes);
1181 void RecordBytesSent(uint64_t bytes);
1182
1187
1188 // Whether the node should be passed out in ForEach* callbacks
1189 static bool NodeFullyConnected(const CNode *pnode);
1190
1192
1193 // Network usage totals
1195 std::atomic<uint64_t> nTotalBytesRecv{0};
1196 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1197
1198 // outbound limit & stats
1199 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1200 std::chrono::seconds
1201 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1202 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1203
1204 // P2P timeout in seconds
1205 std::chrono::seconds m_peer_connect_timeout;
1206
1207 // Whitelisted ranges. Any node connecting from these is automatically
1208 // whitelisted (as well as those connecting to whitelisted binds).
1209 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1210 // Whitelisted ranges for outgoing connections.
1211 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1212
1213 unsigned int nSendBufferMaxSize{0};
1214 unsigned int nReceiveFloodSize{0};
1215
1216 std::vector<ListenSocket> vhListenSocket;
1217 std::atomic<bool> fNetworkActive{true};
1220 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1222 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1224 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1225 std::list<CNode *> m_nodes_disconnected;
1227 std::atomic<NodeId> nLastNodeId{0};
1228 unsigned int nPrevNodeCount{0};
1229
1237 std::vector<CAddress> m_addrs_response_cache;
1238 std::chrono::microseconds m_cache_entry_expiration{0};
1239 };
1240
1255 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1256
1268 std::atomic<ServiceFlags> nLocalServices;
1269
1270 std::unique_ptr<CSemaphore> semOutbound;
1271 std::unique_ptr<CSemaphore> semAddnode;
1273
1274 // How many full-relay (tx, block, addr) outbound peers we want
1276
1277 // How many block-relay only outbound peers we want
1278 // We do not relay tx or addr messages with these peers
1280
1281 // How many avalanche enabled outbound peers we want
1283
1289 // FIXME m_msgproc is a terrible name
1290 std::vector<NetEventsInterface *> m_msgproc;
1296
1301 std::vector<CAddress> m_anchors;
1302
1304 const uint64_t nSeed0, nSeed1;
1305
1307 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1308
1309 std::condition_variable condMsgProc;
1311 std::atomic<bool> flagInterruptMsgProc{false};
1312
1320
1325 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1326
1333
1339
1345 std::atomic_bool m_start_extra_block_relay_peers{false};
1346
1351 std::vector<CService> m_onion_binds;
1352
1358
1364
1371 public:
1372 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1373 {
1374 LOCK(connman.m_nodes_mutex);
1375 m_nodes_copy = connman.m_nodes;
1376 for (auto &node : m_nodes_copy) {
1377 node->AddRef();
1378 }
1379 }
1380 if (shuffle) {
1381 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1383 }
1384 }
1385
1387 for (auto &node : m_nodes_copy) {
1388 node->Release();
1389 }
1390 }
1391
1392 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1393
1394 private:
1395 std::vector<CNode *> m_nodes_copy;
1396 };
1397
1398 friend struct ::CConnmanTest;
1399 friend struct ConnmanTestMsg;
1400};
1401
1402std::string getSubVersionEB(uint64_t MaxBlockSize);
1403std::string userAgent(const Config &config);
1404
1406void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1407 Span<const uint8_t> data, bool is_incoming);
1408
1412extern std::function<void(const CAddress &addr, const std::string &msg_type,
1413 Span<const uint8_t> data, bool is_incoming)>
1415
1416#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:1370
const std::vector< CNode * > & Nodes() const
Definition: net.h:1392
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1372
std::vector< CNode * > m_nodes_copy
Definition: net.h:1395
Definition: net.h:815
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1363
std::condition_variable condMsgProc
Definition: net.h:1309
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1196
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1201
std::thread threadMessageHandler
Definition: net.h:1331
void ForEachNode(const NodeFn &func)
Definition: net.h:920
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:2878
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1024
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:2894
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1209
CClientUIInterface * m_client_interface
Definition: net.h:1288
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2134
void ForEachNode(const NodeFn &func) const
Definition: net.h:929
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3088
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1092
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:427
void DeleteNode(CNode *pnode)
Definition: net.cpp:2659
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2750
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:911
bool GetNetworkActive() const
Definition: net.h:907
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:1286
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1594
void Stop()
Definition: net.h:901
int m_max_outbound_block_relay
Definition: net.h:1279
std::thread threadI2PAcceptIncoming
Definition: net.h:1332
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1598
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1311
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2053
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2580
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1432
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1250
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:1304
NodeId GetNewNodeId()
Definition: net.cpp:2381
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1319
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1271
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2444
std::atomic< NodeId > nLastNodeId
Definition: net.h:1227
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2854
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1626
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1424
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1295
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:2917
std::thread threadDNSAddressSeed
Definition: net.h:1327
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1268
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2185
const uint64_t nSeed1
Definition: net.h:1304
void StartExtraBlockRelayPeers()
Definition: net.h:965
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1301
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2874
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1357
friend struct ConnmanTestMsg
Definition: net.h:1399
unsigned int nPrevNodeCount
Definition: net.h:1228
void NotifyNumConnectionsChanged()
Definition: net.cpp:1191
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2937
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2805
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1205
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:1338
bool InitBinds(const Options &options)
Definition: net.cpp:2407
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:1199
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1216
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:1984
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3100
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2869
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1270
RecursiveMutex cs_totalBytesSent
Definition: net.h:1194
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2385
std::thread threadOpenConnections
Definition: net.h:1330
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2762
Mutex m_addr_fetches_mutex
Definition: net.h:1221
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1210
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:354
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2780
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:1996
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1304
unsigned int nReceiveFloodSize
Definition: net.h:1214
int GetExtraFullOutboundCount() const
Definition: net.cpp:1610
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2928
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:834
RecursiveMutex m_nodes_mutex
Definition: net.h:1226
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3038
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:1576
int nMaxConnections
Definition: net.h:1272
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2370
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:2673
std::function< void(CNode *)> NodeFn
Definition: net.h:919
void SetNetworkActive(bool active)
Definition: net.cpp:2356
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1225
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2085
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:1021
AddrMan & addrman
Definition: net.h:1219
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1276
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3104
Mutex mutexMsgProc
Definition: net.h:1310
bool fAddressesInitialized
Definition: net.h:1218
~CConnman()
Definition: net.cpp:2667
void StopThreads()
Definition: net.cpp:2603
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2738
std::thread threadOpenAddedConnections
Definition: net.h:1329
Mutex m_added_nodes_mutex
Definition: net.h:1223
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:585
const Config * config
Definition: net.h:1191
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:849
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:399
int m_max_outbound_full_relay
Definition: net.h:1275
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1284
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2850
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:1205
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1416
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:991
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3042
void StopNodes()
Definition: net.cpp:2624
bool GetUseAddrmanOutgoing() const
Definition: net.h:908
unsigned int nSendBufferMaxSize
Definition: net.h:1213
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1325
bool m_use_addrman_outgoing
Definition: net.h:1287
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1211
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:1255
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1195
std::atomic< bool > fNetworkActive
Definition: net.h:1217
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1345
void DisconnectNodes()
Definition: net.cpp:1141
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1403
void DumpAddresses()
Definition: net.cpp:1567
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:1351
int nMaxFeeler
Definition: net.h:1285
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1290
std::thread threadSocketHandler
Definition: net.h:1328
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2932
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1640
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:962
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2223
int m_max_avalanche_outbound
Definition: net.h:1282
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:257
CNetMessage(CNetMessage &&)=default
uint32_t m_message_size
size of the payload
Definition: net.h:267
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:262
CNetMessage(DataStream &&recv_in)
Definition: net.h:272
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:269
std::string m_type
Definition: net.h:270
bool m_valid_checksum
Definition: net.h:265
bool m_valid_header
Definition: net.h:264
DataStream m_recv
received message data
Definition: net.h:260
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
bool m_valid_netmagic
Definition: net.h:263
Information about a peer.
Definition: net.h:386
Mutex cs_avalanche_pubkey
Definition: net.h:578
const CAddress addrBind
Definition: net.h:425
bool IsFeelerConn() const
Definition: net.h:509
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:420
bool ExpectServicesFromConn() const
Definition: net.h:523
std::atomic< int > nVersion
Definition: net.h:430
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:561
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:415
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:755
bool IsInboundConn() const
Definition: net.h:515
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:443
std::atomic_bool fPauseRecv
Definition: net.h:454
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:482
NodeId GetId() const
Definition: net.h:678
bool IsManualConn() const
Definition: net.h:503
std::atomic< int64_t > nTimeOffset
Definition: net.h:421
const std::string m_addr_name
Definition: net.h:426
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:724
void SetCommonVersion(int greatest_common_version)
Definition: net.h:700
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:553
std::list< CNetMessage > vRecvMsg
Definition: net.h:736
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:567
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:555
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:673
std::atomic_bool fSuccessfullyConnected
Definition: net.h:446
const bool m_prefer_evict
Definition: net.h:442
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:741
bool IsAddrFetchConn() const
Definition: net.h:511
uint64_t GetLocalNonce() const
Definition: net.h:680
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:2970
const CAddress addr
Definition: net.h:423
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:612
CSemaphoreGrant grantOutbound
Definition: net.h:450
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:453
std::atomic< int > nRefCount
Definition: net.h:451
std::atomic< int > m_greatest_common_version
Definition: net.h:732
bool IsBlockOnlyConn() const
Definition: net.h:505
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition: net.cpp:3005
int GetCommonVersion() const
Definition: net.h:704
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:498
uint64_t nRemoteHostNonce
Definition: net.h:432
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:439
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:390
Mutex cs_vSend
Definition: net.h:411
CNode * AddRef()
Definition: net.h:711
std::atomic_bool fPauseSend
Definition: net.h:455
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:608
uint64_t nRemoteExtraEntropy
Definition: net.h:434
int GetRefCount() const
Definition: net.h:683
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:3022
uint64_t GetLocalExtraEntropy() const
Definition: net.h:681
SteadyMilliseconds m_last_poll
Definition: net.h:624
double getAvailabilityScore() const
Definition: net.cpp:2964
Mutex m_msg_process_queue_mutex
Definition: net.h:738
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:408
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:573
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:457
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:625
const size_t m_recv_flood_size
Definition: net.h:734
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:629
const uint64_t nLocalHostNonce
Definition: net.h:730
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:652
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:2949
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:406
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:611
const uint64_t nLocalExtraEntropy
Definition: net.h:731
const NetPermissionFlags m_permission_flags
Definition: net.h:392
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:677
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2941
Mutex m_addr_local_mutex
Definition: net.h:744
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:429
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:658
const NodeId id
Definition: net.h:729
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
Definition: net.h:616
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:477
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:649
Mutex cs_vRecv
Definition: net.h:413
std::atomic< bool > m_avalanche_enabled
Definition: net.h:576
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:633
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:389
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:409
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:752
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:412
std::atomic_bool fDisconnect
Definition: net.h:449
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:418
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:622
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:641
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:606
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:2945
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:576
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:417
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
bool IsAvalancheOutboundConnection() const
Definition: net.h:519
void Release()
Definition: net.h:716
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:440
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:764
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:769
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.
Definition: sock.h:28
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:288
virtual ~TransportDeserializer()
Definition: net.h:297
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:363
virtual ~TransportSerializer()
Definition: net.h:370
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:775
CMessageHeader hdr
Definition: net.h:310
const uint256 & GetMessageHash() const
Definition: net.cpp:766
uint32_t nDataPos
Definition: net.h:314
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn)
Definition: net.h:332
uint32_t nHdrPos
Definition: net.h:313
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:346
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:749
bool Complete() const override
Definition: net.h:338
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:716
CHash256 hasher
Definition: net.h:302
DataStream hdrbuf
Definition: net.h:308
uint256 data_hash
Definition: net.h:303
DataStream vRecv
Definition: net.h:312
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition: net.cpp:818
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:240
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:138
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:93
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:69
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:63
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:76
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:281
bool fDiscover
Definition: net.cpp:127
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:107
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:101
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:97
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:103
bool fListen
Definition: net.cpp:128
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:95
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:67
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:106
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:83
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:114
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:105
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:3192
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:3126
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:129
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:85
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:87
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:65
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:99
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:3160
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:207
static const bool DEFAULT_DNSSEED
Definition: net.h:104
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:74
@ LOCAL_NONE
Definition: net.h:158
@ LOCAL_MAPPED
Definition: net.h:164
@ LOCAL_MANUAL
Definition: net.h:166
@ LOCAL_MAX
Definition: net.h:168
@ LOCAL_BIND
Definition: net.h:162
@ LOCAL_IF
Definition: net.h:160
std::string userAgent(const Config &config)
Definition: net.cpp:3140
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:78
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:2303
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:32
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:113
CService resolvedAddress
Definition: net.h:111
bool fConnected
Definition: net.h:112
std::string strAddedNode
Definition: net.h:110
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1236
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1238
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1237
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1063
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1066
NetPermissionFlags m_permissions
Definition: net.h:1071
std::shared_ptr< Sock > sock
Definition: net.h:1062
int m_max_outbound_block_relay
Definition: net.h:821
unsigned int nReceiveFloodSize
Definition: net.h:829
int m_max_outbound_full_relay
Definition: net.h:820
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:835
uint64_t nMaxOutboundLimit
Definition: net.h:830
CClientUIInterface * uiInterface
Definition: net.h:825
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:833
int m_max_avalanche_outbound
Definition: net.h:822
std::vector< CService > onion_binds
Definition: net.h:837
int nMaxFeeler
Definition: net.h:824
std::vector< std::string > m_specified_outgoing
Definition: net.h:842
bool whitelist_relay
Definition: net.h:846
int nMaxConnections
Definition: net.h:819
ServiceFlags nLocalServices
Definition: net.h:818
std::vector< std::string > m_added_nodes
Definition: net.h:843
int64_t m_peer_connect_timeout
Definition: net.h:831
std::vector< CService > vBinds
Definition: net.h:836
unsigned int nSendBufferMaxSize
Definition: net.h:828
bool m_i2p_accept_incoming
Definition: net.h:844
std::vector< std::string > vSeedNodes
Definition: net.h:832
BanMan * m_banman
Definition: net.h:827
bool m_use_addrman_outgoing
Definition: net.h:841
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:826
bool whitelist_forcerelay
Definition: net.h:845
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:840
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:834
int nMaxAddnode
Definition: net.h:823
NetPermissionFlags permission_flags
Definition: net.h:380
bool prefer_evict
Definition: net.h:381
size_t recv_flood_size
Definition: net.h:382
POD that contains various stats about a node.
Definition: net.h:214
std::string addrLocal
Definition: net.h:240
CAddress addrBind
Definition: net.h:244
uint64_t nRecvBytes
Definition: net.h:234
std::chrono::microseconds m_last_ping_time
Definition: net.h:237
uint32_t m_mapped_as
Definition: net.h:247
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:235
bool fInbound
Definition: net.h:226
uint64_t nSendBytes
Definition: net.h:232
std::chrono::seconds m_last_recv
Definition: net.h:217
std::optional< double > m_availabilityScore
Definition: net.h:249
std::chrono::seconds m_last_proof_time
Definition: net.h:219
ConnectionType m_conn_type
Definition: net.h:248
std::chrono::seconds m_last_send
Definition: net.h:216
std::chrono::seconds m_last_tx_time
Definition: net.h:218
CAddress addr
Definition: net.h:242
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:233
std::chrono::microseconds m_min_ping_time
Definition: net.h:238
int64_t nTimeOffset
Definition: net.h:222
std::chrono::seconds m_connected
Definition: net.h:221
bool m_bip152_highbandwidth_from
Definition: net.h:230
bool m_bip152_highbandwidth_to
Definition: net.h:228
std::string m_addr_name
Definition: net.h:223
int nVersion
Definition: net.h:224
std::chrono::seconds m_last_block_time
Definition: net.h:220
Network m_network
Definition: net.h:246
NodeId nodeid
Definition: net.h:215
std::string cleanSubVer
Definition: net.h:225
int m_starting_height
Definition: net.h:231
NetPermissionFlags m_permission_flags
Definition: net.h:236
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:127
std::vector< uint8_t > data
Definition: net.h:134
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:135
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:198
int nScore
Definition: net.h:197
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:306
static int count
Definition: tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:31
assert(!tx.IsCoinBase())