Bitcoin ABC 0.30.7
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>
24#include <nodeid.h>
25#include <protocol.h>
26#include <pubkey.h>
27#include <radix.h>
28#include <random.h>
29#include <span.h>
30#include <streams.h>
31#include <sync.h>
32#include <threadinterrupt.h>
33#include <uint256.h>
34#include <util/check.h>
35#include <util/sock.h>
36#include <util/time.h>
37
38#include <atomic>
39#include <condition_variable>
40#include <cstdint>
41#include <deque>
42#include <functional>
43#include <list>
44#include <map>
45#include <memory>
46#include <thread>
47#include <vector>
48
49class AddrMan;
50class BanMan;
51class Config;
52class CNode;
53class CScheduler;
54struct bilingual_str;
55
60static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
62static constexpr auto FEELER_INTERVAL = 2min;
64static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
66static const unsigned int MAX_SUBVERSION_LENGTH = 256;
73static const int MAX_ADDNODE_CONNECTIONS = 8;
82static const int MAX_FEELER_CONNECTIONS = 1;
84static const bool DEFAULT_LISTEN = true;
90static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
92static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
94static const bool DEFAULT_BLOCKSONLY = false;
96static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
98static const int NUM_FDS_MESSAGE_CAPTURE = 1;
99
100static const bool DEFAULT_FORCEDNSSEED = false;
101static const bool DEFAULT_DNSSEED = true;
102static const bool DEFAULT_FIXEDSEEDS = true;
103static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
104static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
105
107 std::string strAddedNode;
111};
112
113struct CNodeStats;
115
117 CSerializedNetMsg() = default;
120 // No copying, only moves.
123
126 copy.data = data;
127 copy.m_type = m_type;
128 return copy;
129 }
130
131 std::vector<uint8_t> data;
132 std::string m_type;
133};
134
135const std::vector<std::string> CONNECTION_TYPE_DOC{
136 "outbound-full-relay (default automatic connections)",
137 "block-relay-only (does not relay transactions or addresses)",
138 "inbound (initiated by the peer)",
139 "manual (added via addnode RPC or -addnode/-connect configuration options)",
140 "addr-fetch (short-lived automatic connection for soliciting addresses)",
141 "feeler (short-lived automatic connection for testing addresses)"};
142
148enum class ConnectionType {
154 INBOUND,
155
163
170 MANUAL,
171
188 FEELER,
189
200
208
214};
215
217std::string ConnectionTypeAsString(ConnectionType conn_type);
218
225void Discover();
226
227uint16_t GetListenPort();
228
229enum {
230 // unknown
232 // address a local interface listens on
234 // address explicit bound to
236 // address reported by UPnP or NAT-PMP
238 // address explicitly specified (-externalip=)
240
243
244bool IsPeerAddrLocalGood(CNode *pnode);
246std::optional<CService> GetLocalAddrForPeer(CNode &node);
247
252void SetReachable(enum Network net, bool reachable);
254bool IsReachable(enum Network net);
256bool IsReachable(const CNetAddr &addr);
257
258bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
259bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
260void RemoveLocal(const CService &addr);
261bool SeenLocal(const CService &addr);
262bool IsLocal(const CService &addr);
263bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
264CService GetLocalAddress(const CNetAddr &addrPeer);
265
266extern bool fDiscover;
267extern bool fListen;
268
271 uint16_t nPort;
272};
273
275extern std::map<CNetAddr, LocalServiceInfo>
277
278extern const std::string NET_MESSAGE_COMMAND_OTHER;
279// Command, total bytes
280typedef std::map<std::string, uint64_t> mapMsgCmdSize;
281
289 std::chrono::seconds m_last_send;
290 std::chrono::seconds m_last_recv;
291 std::chrono::seconds m_last_tx_time;
292 std::chrono::seconds m_last_proof_time;
293 std::chrono::seconds m_last_block_time;
294 std::chrono::seconds m_connected;
295 int64_t nTimeOffset;
296 std::string m_addr_name;
298 std::string cleanSubVer;
300 // We requested high bandwidth connection to peer
302 // Peer requested high bandwidth connection
305 uint64_t nSendBytes;
307 uint64_t nRecvBytes;
310 std::chrono::microseconds m_last_ping_time;
311 std::chrono::microseconds m_min_ping_time;
312 // Our address, as reported by the peer
313 std::string addrLocal;
314 // Address of this peer
316 // Bind address of our side of the connection
318 // Network the peer connected through
320 uint32_t m_mapped_as;
322 std::optional<double> m_availabilityScore;
323};
324
331public:
335 std::chrono::microseconds m_time{0};
336 bool m_valid_netmagic = false;
337 bool m_valid_header = false;
338 bool m_valid_checksum = false;
340 uint32_t m_message_size{0};
343 std::string m_type;
344
345 CNetMessage(CDataStream &&recv_in) : m_recv(std::move(recv_in)) {}
346
347 void SetVersion(int nVersionIn) { m_recv.SetVersion(nVersionIn); }
348};
349
356public:
357 // returns true if the current deserialization is complete
358 virtual bool Complete() const = 0;
359 // set the serialization context version
360 virtual void SetVersion(int version) = 0;
362 virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
363 // decomposes a message from the context
364 virtual CNetMessage GetMessage(const Config &config,
365 std::chrono::microseconds time) = 0;
367};
368
370private:
373
374 // Parsing header (false) or data (true)
376 // Partially received header.
378 // Complete header.
380 // Received message data.
382 uint32_t nHdrPos;
383 uint32_t nDataPos;
384
385 const uint256 &GetMessageHash() const;
386 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
387 int readData(Span<const uint8_t> msg_bytes);
388
389 void Reset() {
390 vRecv.clear();
391 hdrbuf.clear();
392 hdrbuf.resize(24);
393 in_data = false;
394 nHdrPos = 0;
395 nDataPos = 0;
397 hasher.Reset();
398 }
399
400public:
402 const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn,
403 int nVersionIn)
404 : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn),
405 vRecv(nTypeIn, nVersionIn) {
406 Reset();
407 }
408
409 bool Complete() const override {
410 if (!in_data) {
411 return false;
412 }
413
414 return (hdr.nMessageSize == nDataPos);
415 }
416
417 void SetVersion(int nVersionIn) override {
418 hdrbuf.SetVersion(nVersionIn);
419 vRecv.SetVersion(nVersionIn);
420 }
421 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
422 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
423 if (ret < 0) {
424 Reset();
425 } else {
426 msg_bytes = msg_bytes.subspan(ret);
427 }
428 return ret;
429 }
430
431 CNetMessage GetMessage(const Config &config,
432 std::chrono::microseconds time) override;
433};
434
439public:
440 // prepare message for transport (header construction, error-correction
441 // computation, payload encryption, etc.)
442 virtual void prepareForTransport(const Config &config,
444 std::vector<uint8_t> &header) = 0;
446};
447
449public:
450 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
451 std::vector<uint8_t> &header) override;
452};
453
456 bool prefer_evict = false;
457};
458
460class CNode {
461 friend class CConnman;
462 friend struct ConnmanTestMsg;
463
464public:
465 std::unique_ptr<TransportDeserializer> m_deserializer;
466 std::unique_ptr<TransportSerializer> m_serializer;
467
469
479 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
480
482 size_t nSendSize GUARDED_BY(cs_vSend){0};
484 size_t nSendOffset GUARDED_BY(cs_vSend){0};
485 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
486 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
490
492 std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
494
495 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
496
497 std::atomic<std::chrono::seconds> m_last_send{0s};
498 std::atomic<std::chrono::seconds> m_last_recv{0s};
500 const std::chrono::seconds m_connected;
501 std::atomic<int64_t> nTimeOffset{0};
502 // Address of this peer
504 // Bind address of our side of the connection
506 const std::string m_addr_name;
509 const bool m_inbound_onion;
510 std::atomic<int> nVersion{0};
511 // The nonce provided by the remote host.
512 uint64_t nRemoteHostNonce{0};
513 // The extra entropy provided by the remote host.
520 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
521 // This peer is preferred for eviction.
522 const bool m_prefer_evict{false};
523 bool HasPermission(NetPermissionFlags permission) const {
525 }
526 std::atomic_bool fSuccessfullyConnected{false};
527 // Setting fDisconnect to true will cause the node to be disconnected the
528 // next time DisconnectNodes() runs
529 std::atomic_bool fDisconnect{false};
531 std::atomic<int> nRefCount{0};
532
533 const uint64_t nKeyedNetGroup;
534 std::atomic_bool fPauseRecv{false};
535 std::atomic_bool fPauseSend{false};
536
538 switch (m_conn_type) {
542 return true;
547 return false;
548 } // no default case, so the compiler can warn about missing cases
549
550 assert(false);
551 }
552
553 bool IsFullOutboundConn() const {
556 }
557
559
560 bool IsBlockOnlyConn() const {
562 }
563
565
566 bool IsAddrFetchConn() const {
568 }
569
570 bool IsInboundConn() const {
572 }
573
576 }
577
579 switch (m_conn_type) {
583 return false;
588 return true;
589 } // no default case, so the compiler can warn about missing cases
590
591 assert(false);
592 }
593
606
607 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
608 std::atomic<bool> m_bip152_highbandwidth_to{false};
609 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
610 std::atomic<bool> m_bip152_highbandwidth_from{false};
611
616 std::atomic_bool m_has_all_wanted_services{false};
617
622 std::atomic_bool m_relays_txs{false};
623
628 std::atomic_bool m_bloom_filter_loaded{false};
629
630 // True if we know this peer is using Avalanche (at least polling)
631 std::atomic<bool> m_avalanche_enabled{false};
632
634 // Pubkey used to verify signatures on Avalanche messages from this peer
635 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
636
638 void invsPolled(uint32_t count);
639
641 void invsVoted(uint32_t count);
642
659 void updateAvailabilityScore(double decayFactor);
660 double getAvailabilityScore() const;
661
662 // Store the next time we will consider a getavaaddr message from this peer
663 std::chrono::seconds m_nextGetAvaAddr{0};
664
665 // The last time the node sent us a faulty message
666 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
667 // How much faulty messages did this node accumulate
669
671
679 std::atomic<std::chrono::seconds> m_last_block_time{0s};
680
687 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
688
695 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
696
698 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
699
704 std::atomic<std::chrono::microseconds> m_min_ping_time{
705 std::chrono::microseconds::max()};
706
707 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
708 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
709 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
710 const std::string &addrNameIn, ConnectionType conn_type_in,
711 bool inbound_onion, CNodeOptions &&node_opts = {});
712 CNode(const CNode &) = delete;
713 CNode &operator=(const CNode &) = delete;
714
719 void PongReceived(std::chrono::microseconds ping_time) {
720 m_last_ping_time = ping_time;
721 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
722 }
723
724 NodeId GetId() const { return id; }
725
726 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
727 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
728
729 int GetRefCount() const {
730 assert(nRefCount >= 0);
731 return nRefCount;
732 }
733
743 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
744 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
745
746 void SetCommonVersion(int greatest_common_version) {
748 m_greatest_common_version = greatest_common_version;
749 }
751
754 void SetAddrLocal(const CService &addrLocalIn)
756
758 nRefCount++;
759 return this;
760 }
761
762 void Release() { nRefCount--; }
763
765
766 void copyStats(CNodeStats &stats)
769
770 std::string ConnectionTypeAsString() const {
772 }
773
774private:
775 const NodeId id;
776 const uint64_t nLocalHostNonce;
777 const uint64_t nLocalExtraEntropy;
780
781 // Used only by SocketHandler thread
782 std::list<CNetMessage> vRecvMsg;
783
784 // Our address, as reported by the peer
787
793 std::atomic<uint64_t> invCounters{0};
794
796 std::atomic<double> availabilityScore{0.};
797
798 mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
799 mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
800};
801
806public:
811
813 virtual void InitializeNode(const Config &config, CNode &node,
814 ServiceFlags our_services) = 0;
815
817 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
818
828 virtual bool ProcessMessages(const Config &config, CNode *pnode,
829 std::atomic<bool> &interrupt)
831
839 virtual bool SendMessages(const Config &config, CNode *pnode)
841
842protected:
849};
850
851namespace {
852struct CConnmanTest;
853}
854
856class CConnman {
857public:
858 struct Options {
864 int nMaxAddnode = 0;
865 int nMaxFeeler = 0;
867 std::vector<NetEventsInterface *> m_msgproc;
868 BanMan *m_banman = nullptr;
869 unsigned int nSendBufferMaxSize = 0;
870 unsigned int nReceiveFloodSize = 0;
871 uint64_t nMaxOutboundLimit = 0;
873 std::vector<std::string> vSeedNodes;
874 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
875 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
876 std::vector<NetWhitebindPermissions> vWhiteBinds;
877 std::vector<CService> vBinds;
878 std::vector<CService> onion_binds;
883 std::vector<std::string> m_specified_outgoing;
884 std::vector<std::string> m_added_nodes;
888 };
889
890 void Init(const Options &connOptions)
892 nLocalServices = connOptions.nLocalServices;
893 nMaxConnections = connOptions.nMaxConnections;
894 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
895 nMaxAddnode = connOptions.nMaxAddnode;
896 nMaxFeeler = connOptions.nMaxFeeler;
897 {
898 // Lock cs_main to prevent a potential race with the peer validation
899 // logic thread.
902 std::min(connOptions.m_max_outbound_full_relay,
903 connOptions.nMaxConnections);
904 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
905 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
909 }
910 m_client_interface = connOptions.uiInterface;
911 m_banman = connOptions.m_banman;
912 m_msgproc = connOptions.m_msgproc;
913 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
914 nReceiveFloodSize = connOptions.nReceiveFloodSize;
916 std::chrono::seconds{connOptions.m_peer_connect_timeout};
917 {
919 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
920 }
921 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
922 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
923 {
925 m_added_nodes = connOptions.m_added_nodes;
926 }
927 m_onion_binds = connOptions.onion_binds;
928 whitelist_forcerelay = connOptions.whitelist_forcerelay;
929 whitelist_relay = connOptions.whitelist_relay;
930 }
931
932 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
933 AddrMan &addrmanIn, bool network_active = true);
934 ~CConnman();
935
936 bool Start(CScheduler &scheduler, const Options &options)
939
940 void StopThreads();
941 void StopNodes();
942 void Stop() {
943 StopThreads();
944 StopNodes();
945 };
946
948 bool GetNetworkActive() const { return fNetworkActive; };
950 void SetNetworkActive(bool active);
951 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
952 CSemaphoreGrant *grantOutbound,
953 const char *strDest, ConnectionType conn_type);
954 bool CheckIncomingNonce(uint64_t nonce);
955
956 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
957
958 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
959
960 using NodeFn = std::function<void(CNode *)>;
961 void ForEachNode(const NodeFn &func) {
963 for (auto &&node : m_nodes) {
965 func(node);
966 }
967 }
968 };
969
970 void ForEachNode(const NodeFn &func) const {
972 for (auto &&node : m_nodes) {
974 func(node);
975 }
976 }
977 };
978
979 // Addrman functions
990 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
991 std::optional<Network> network) const;
998 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
999 size_t max_pct);
1000
1001 // This allows temporarily exceeding m_max_outbound_full_relay, with the
1002 // goal of finding a peer that is better than all our current peers.
1003 void SetTryNewOutboundPeer(bool flag);
1004 bool GetTryNewOutboundPeer() const;
1005
1007 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
1009 }
1010
1011 // Return the number of outbound peers we have in excess of our target (eg,
1012 // if we previously called SetTryNewOutboundPeer(true), and have since set
1013 // to false, we may have extra peers that we wish to disconnect). This may
1014 // return a value less than (num_outbound_connections - num_outbound_slots)
1015 // in cases where some outbound connections are not yet fully connected, or
1016 // not yet fully disconnected.
1017 int GetExtraFullOutboundCount() const;
1018 // Count the number of block-relay-only peers we have over our limit.
1019 int GetExtraBlockRelayCount() const;
1020
1021 bool AddNode(const std::string &node)
1023 bool RemoveAddedNode(const std::string &node)
1025 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
1027
1042 bool AddConnection(const std::string &address, ConnectionType conn_type);
1043
1044 size_t GetNodeCount(ConnectionDirection) const;
1045 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1046 bool DisconnectNode(const std::string &node);
1047 bool DisconnectNode(const CSubNet &subnet);
1048 bool DisconnectNode(const CNetAddr &addr);
1049 bool DisconnectNode(NodeId id);
1050
1058
1059 uint64_t GetMaxOutboundTarget() const;
1060 std::chrono::seconds GetMaxOutboundTimeframe() const;
1061
1065 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1066
1069 uint64_t GetOutboundTargetBytesLeft() const;
1070
1073 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1074
1075 uint64_t GetTotalBytesRecv() const;
1076 uint64_t GetTotalBytesSent() const;
1077
1079 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1080
1081 unsigned int GetReceiveFloodSize() const;
1082
1084
1090 std::chrono::seconds now) const;
1091
1092private:
1094 public:
1095 std::shared_ptr<Sock> sock;
1097 NetPermissions::AddFlag(flags, m_permissions);
1098 }
1099 ListenSocket(std::shared_ptr<Sock> sock_,
1100 NetPermissionFlags permissions_)
1101 : sock(sock_), m_permissions(permissions_) {}
1102
1103 private:
1105 };
1106
1107 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1108 NetPermissionFlags permissions);
1109 bool Bind(const CService &addr, unsigned int flags,
1110 NetPermissionFlags permissions);
1111 bool InitBinds(const Options &options);
1112
1115 void AddAddrFetch(const std::string &strDest)
1118 void
1119 ThreadOpenConnections(std::vector<std::string> connect,
1120 std::function<void(const CAddress &, ConnectionType)>
1121 mockOpenConnection)
1126 void AcceptConnection(const ListenSocket &hListenSocket);
1127
1136 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1137 NetPermissionFlags permission_flags,
1138 const CAddress &addr_bind,
1139 const CAddress &addr);
1140
1141 void DisconnectNodes();
1144 bool InactivityCheck(const CNode &node) const;
1145
1151 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1152
1158
1165 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1166 const Sock::EventsPerSock &events_per_sock)
1168
1173 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1174
1178
1179 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1180
1181 CNode *FindNode(const CNetAddr &ip);
1182 CNode *FindNode(const CSubNet &subNet);
1183 CNode *FindNode(const std::string &addrName);
1184 CNode *FindNode(const CService &addr);
1185
1190 bool AlreadyConnectedToAddress(const CAddress &addr);
1191
1193 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1194 bool fCountFailure, ConnectionType conn_type);
1196 NetPermissionFlags &flags, const CNetAddr &addr,
1197 const std::vector<NetWhitelistPermissions> &ranges) const;
1198
1199 void DeleteNode(CNode *pnode);
1200
1202
1207 std::pair<size_t, bool> SocketSendData(CNode &node) const
1209
1210 void DumpAddresses();
1211
1212 // Network stats
1213 void RecordBytesRecv(uint64_t bytes);
1214 void RecordBytesSent(uint64_t bytes);
1215
1220
1221 // Whether the node should be passed out in ForEach* callbacks
1222 static bool NodeFullyConnected(const CNode *pnode);
1223
1225
1226 // Network usage totals
1228 std::atomic<uint64_t> nTotalBytesRecv{0};
1229 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1230
1231 // outbound limit & stats
1232 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1233 std::chrono::seconds
1234 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1235 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1236
1237 // P2P timeout in seconds
1238 std::chrono::seconds m_peer_connect_timeout;
1239
1240 // Whitelisted ranges. Any node connecting from these is automatically
1241 // whitelisted (as well as those connecting to whitelisted binds).
1242 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1243 // Whitelisted ranges for outgoing connections.
1244 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1245
1246 unsigned int nSendBufferMaxSize{0};
1247 unsigned int nReceiveFloodSize{0};
1248
1249 std::vector<ListenSocket> vhListenSocket;
1250 std::atomic<bool> fNetworkActive{true};
1253 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1255 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1257 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1258 std::list<CNode *> m_nodes_disconnected;
1260 std::atomic<NodeId> nLastNodeId{0};
1261 unsigned int nPrevNodeCount{0};
1262
1270 std::vector<CAddress> m_addrs_response_cache;
1271 std::chrono::microseconds m_cache_entry_expiration{0};
1272 };
1273
1288 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1289
1301
1302 std::unique_ptr<CSemaphore> semOutbound;
1303 std::unique_ptr<CSemaphore> semAddnode;
1305
1306 // How many full-relay (tx, block, addr) outbound peers we want
1308
1309 // How many block-relay only outbound peers we want
1310 // We do not relay tx or addr messages with these peers
1312
1313 // How many avalanche enabled outbound peers we want
1315
1321 // FIXME m_msgproc is a terrible name
1322 std::vector<NetEventsInterface *> m_msgproc;
1328
1333 std::vector<CAddress> m_anchors;
1334
1336 const uint64_t nSeed0, nSeed1;
1337
1339 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1340
1341 std::condition_variable condMsgProc;
1343 std::atomic<bool> flagInterruptMsgProc{false};
1344
1352
1357 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1358
1365
1371
1377 std::atomic_bool m_start_extra_block_relay_peers{false};
1378
1383 std::vector<CService> m_onion_binds;
1384
1390
1396
1403 public:
1404 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1405 {
1406 LOCK(connman.m_nodes_mutex);
1407 m_nodes_copy = connman.m_nodes;
1408 for (auto &node : m_nodes_copy) {
1409 node->AddRef();
1410 }
1411 }
1412 if (shuffle) {
1413 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1415 }
1416 }
1417
1419 for (auto &node : m_nodes_copy) {
1420 node->Release();
1421 }
1422 }
1423
1424 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1425
1426 private:
1427 std::vector<CNode *> m_nodes_copy;
1428 };
1429
1430 friend struct ::CConnmanTest;
1431 friend struct ConnmanTestMsg;
1432};
1433
1434std::string getSubVersionEB(uint64_t MaxBlockSize);
1435std::string userAgent(const Config &config);
1436
1438void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1439 Span<const uint8_t> data, bool is_incoming);
1440
1444extern std::function<void(const CAddress &addr, const std::string &msg_type,
1445 Span<const uint8_t> data, bool is_incoming)>
1447
1450 std::chrono::seconds m_connected;
1451 std::chrono::microseconds m_min_ping_time;
1452 std::chrono::seconds m_last_block_time;
1453 std::chrono::seconds m_last_proof_time;
1454 std::chrono::seconds m_last_tx_time;
1463};
1464
1472[[nodiscard]] std::optional<NodeId>
1473SelectNodeToEvict(std::vector<NodeEvictionCandidate> &&vEvictionCandidates);
1474
1498 std::vector<NodeEvictionCandidate> &vEvictionCandidates);
1499
1500#endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:541
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:68
Definition: banman.h:58
A CService with information about it as peer.
Definition: protocol.h:442
Signals for UI communication.
Definition: ui_interface.h:24
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1402
const std::vector< CNode * > & Nodes() const
Definition: net.h:1424
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1404
std::vector< CNode * > m_nodes_copy
Definition: net.h:1427
Definition: net.h:856
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1395
std::condition_variable condMsgProc
Definition: net.h:1341
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1229
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1234
std::thread threadMessageHandler
Definition: net.h:1363
void ForEachNode(const NodeFn &func)
Definition: net.h:961
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:3194
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:3210
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1242
CClientUIInterface * m_client_interface
Definition: net.h:1320
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2473
void ForEachNode(const NodeFn &func) const
Definition: net.h:970
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3379
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1415
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:424
void DeleteNode(CNode *pnode)
Definition: net.cpp:2988
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3080
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1232
bool GetNetworkActive() const
Definition: net.h:948
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:391
int m_max_outbound
Definition: net.h:1318
ServiceFlags nLocalServices
Services this node offers.
Definition: net.h:1300
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1933
void Stop()
Definition: net.h:942
int m_max_outbound_block_relay
Definition: net.h:1311
std::thread threadI2PAcceptIncoming
Definition: net.h:1364
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1937
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1343
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:3257
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2392
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2909
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1771
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1573
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:1627
NodeId GetNewNodeId()
Definition: net.cpp:2720
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1351
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1303
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2773
std::atomic< NodeId > nLastNodeId
Definition: net.h:1260
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:3170
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1965
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1763
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1327
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:3233
std::thread threadDNSAddressSeed
Definition: net.h:1359
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2524
const uint64_t nSeed1
Definition: net.h:1336
void StartExtraBlockRelayPeers()
Definition: net.h:1006
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1333
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:3190
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1389
friend struct ConnmanTestMsg
Definition: net.h:1431
unsigned int nPrevNodeCount
Definition: net.h:1261
void NotifyNumConnectionsChanged()
Definition: net.cpp:1514
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3253
bool DisconnectNode(const std::string &node)
Definition: net.cpp:3121
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1238
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay.
Definition: net.h:1370
bool InitBinds(const Options &options)
Definition: net.cpp:2746
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:132
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1232
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1249
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2323
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3391
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:3185
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1302
RecursiveMutex cs_totalBytesSent
Definition: net.h:1227
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2724
std::thread threadOpenConnections
Definition: net.h:1362
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3092
Mutex m_addr_fetches_mutex
Definition: net.h:1254
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1533
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:351
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:3110
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2335
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1336
unsigned int nReceiveFloodSize
Definition: net.h:1247
int GetExtraFullOutboundCount() const
Definition: net.cpp:1949
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3244
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:846
RecursiveMutex m_nodes_mutex
Definition: net.h:1259
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3329
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:1915
int nMaxConnections
Definition: net.h:1304
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2709
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:3002
std::function< void(CNode *)> NodeFn
Definition: net.h:960
void SetNetworkActive(bool active)
Definition: net.cpp:2695
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1258
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2424
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
AddrMan & addrman
Definition: net.h:1252
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1599
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3395
Mutex mutexMsgProc
Definition: net.h:1342
bool fAddressesInitialized
Definition: net.h:1251
~CConnman()
Definition: net.cpp:2996
void StopThreads()
Definition: net.cpp:2932
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3068
std::thread threadOpenAddedConnections
Definition: net.h:1361
Mutex m_added_nodes_mutex
Definition: net.h:1256
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:578
const Config * config
Definition: net.h:1224
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:890
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:396
int m_max_outbound_full_relay
Definition: net.h:1307
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1316
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3166
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:1528
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1755
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:1315
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3333
void StopNodes()
Definition: net.cpp:2953
bool GetUseAddrmanOutgoing() const
Definition: net.h:949
unsigned int nSendBufferMaxSize
Definition: net.h:1246
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1357
bool m_use_addrman_outgoing
Definition: net.h:1319
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1244
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
Definition: net.h:1288
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1228
std::atomic< bool > fNetworkActive
Definition: net.h:1250
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1377
void DisconnectNodes()
Definition: net.cpp:1464
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1742
void DumpAddresses()
Definition: net.cpp:1906
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:1383
int nMaxFeeler
Definition: net.h:1317
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1322
std::thread threadSocketHandler
Definition: net.h:1360
uint64_t GetTotalBytesSent() const
Definition: net.cpp:3248
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1979
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1286
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2562
int m_max_avalanche_outbound
Definition: net.h:1314
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:177
void SetVersion(int n)
Definition: streams.h:338
void resize(size_type n, value_type c=value_type{})
Definition: streams.h:225
void clear()
Definition: streams.h:233
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:23
CHash256 & Reset()
Definition: hash.h:42
Message header.
Definition: protocol.h:34
uint32_t nMessageSize
Definition: protocol.h:71
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
Network address.
Definition: netaddress.h:121
Transport protocol agnostic message container.
Definition: net.h:330
CNetMessage(CDataStream &&recv_in)
Definition: net.h:345
uint32_t m_message_size
size of the payload
Definition: net.h:340
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:335
CDataStream m_recv
received message data
Definition: net.h:333
void SetVersion(int nVersionIn)
Definition: net.h:347
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:342
std::string m_type
Definition: net.h:343
bool m_valid_checksum
Definition: net.h:338
bool m_valid_header
Definition: net.h:337
bool m_valid_netmagic
Definition: net.h:336
Information about a peer.
Definition: net.h:460
RecursiveMutex cs_vProcessMsg
Definition: net.h:491
Mutex cs_avalanche_pubkey
Definition: net.h:633
const CAddress addrBind
Definition: net.h:505
bool IsFeelerConn() const
Definition: net.h:564
mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend)
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:500
bool ExpectServicesFromConn() const
Definition: net.h:578
std::atomic< int > nVersion
Definition: net.h:510
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:616
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:495
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:796
bool IsInboundConn() const
Definition: net.h:570
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:523
std::atomic_bool fPauseRecv
Definition: net.h:534
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:537
NodeId GetId() const
Definition: net.h:724
bool IsManualConn() const
Definition: net.h:558
std::atomic< int64_t > nTimeOffset
Definition: net.h:501
const std::string m_addr_name
Definition: net.h:506
mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv)
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:770
void SetCommonVersion(int greatest_common_version)
Definition: net.h:746
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:608
std::list< CNetMessage > vRecvMsg
Definition: net.h:782
size_t nProcessQueueSize
Definition: net.h:493
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:622
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:610
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:719
std::atomic_bool fSuccessfullyConnected
Definition: net.h:526
const bool m_prefer_evict
Definition: net.h:522
bool IsAddrFetchConn() const
Definition: net.h:566
uint64_t GetLocalNonce() const
Definition: net.h:726
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:3290
const CAddress addr
Definition: net.h:503
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:626
CSemaphoreGrant grantOutbound
Definition: net.h:530
const uint64_t nKeyedNetGroup
Definition: net.h:533
friend struct ConnmanTestMsg
Definition: net.h:462
std::atomic< int > nRefCount
Definition: net.h:531
std::atomic< int > m_greatest_common_version
Definition: net.h:779
bool IsBlockOnlyConn() const
Definition: net.h:560
int GetCommonVersion() const
Definition: net.h:750
bool IsFullOutboundConn() const
Definition: net.h:553
uint64_t nRemoteHostNonce
Definition: net.h:512
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:466
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:519
Mutex cs_vSend
Definition: net.h:487
CNode * AddRef()
Definition: net.h:757
std::atomic_bool fPauseSend
Definition: net.h:535
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:663
uint64_t nRemoteExtraEntropy
Definition: net.h:514
int GetRefCount() const
Definition: net.h:729
uint64_t GetLocalExtraEntropy() const
Definition: net.h:727
SteadyMilliseconds m_last_poll
Definition: net.h:670
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:465
double getAvailabilityScore() const
Definition: net.cpp:3284
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:484
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:628
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:778
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:638
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:642
const uint64_t nLocalHostNonce
Definition: net.h:776
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:698
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:3269
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:482
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:666
const uint64_t nLocalExtraEntropy
Definition: net.h:777
const NetPermissionFlags m_permission_flags
Definition: net.h:468
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:690
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:3261
Mutex m_addr_local_mutex
Definition: net.h:785
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:509
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:704
const NodeId id
Definition: net.h:775
std::atomic< int > m_avalanche_message_fault_counter
Definition: net.h:668
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:695
Mutex cs_vRecv
Definition: net.h:489
std::atomic< bool > m_avalanche_enabled
Definition: net.h:631
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:679
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:485
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:793
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:488
std::atomic_bool fDisconnect
Definition: net.h:529
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:498
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:687
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:620
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:3265
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:569
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:497
bool IsAvalancheOutboundConnection() const
Definition: net.h:574
std::list< CNetMessage > vProcessMsg GUARDED_BY(cs_vProcessMsg)
void Release()
Definition: net.h:762
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:520
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:545
SipHash-2-4.
Definition: siphash.h:13
A helper class for interruptible sleeps.
Definition: config.h:19
Fast randomness source.
Definition: random.h:156
Different type to mark Mutex at global scope.
Definition: sync.h:144
Interface for message handling.
Definition: net.h:805
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:810
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:218
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:355
virtual ~TransportDeserializer()
Definition: net.h:366
virtual bool Complete() const =0
virtual CNetMessage GetMessage(const Config &config, std::chrono::microseconds time)=0
virtual void SetVersion(int version)=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:438
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header)=0
virtual ~TransportSerializer()
Definition: net.h:445
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
Definition: net.cpp:787
CDataStream vRecv
Definition: net.h:381
CMessageHeader hdr
Definition: net.h:379
const uint256 & GetMessageHash() const
Definition: net.cpp:778
uint32_t nDataPos
Definition: net.h:383
uint32_t nHdrPos
Definition: net.h:382
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:421
void SetVersion(int nVersionIn) override
Definition: net.h:417
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:761
bool Complete() const override
Definition: net.h:409
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:728
CHash256 hasher
Definition: net.h:371
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:401
CDataStream hdrbuf
Definition: net.h:377
uint256 data_hash
Definition: net.h:372
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) override
Definition: net.cpp:830
void SetNull()
Definition: uint256.h:41
256-bit opaque blob.
Definition: uint256.h:129
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
#define LogPrint(category,...)
Definition: logging.h:238
@ NET
Definition: logging.h:40
Definition: init.h:28
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:237
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:135
uint16_t GetListenPort()
Definition: net.cpp:137
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:90
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:346
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:221
void RemoveLocal(const CService &addr)
Definition: net.cpp:311
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:66
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:60
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:73
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:278
bool fDiscover
Definition: net.cpp:125
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:104
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:98
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:94
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:100
bool fListen
Definition: net.cpp:126
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:92
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:64
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:103
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:112
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:80
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:243
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition: net.cpp:1137
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:317
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:102
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:3482
ConnectionType
Different types of connections to a peer.
Definition: net.h:148
@ 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.
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:280
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:3417
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:127
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:82
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:84
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:173
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:62
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:96
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:1042
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:3451
static const bool DEFAULT_DNSSEED
Definition: net.h:101
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:71
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:599
@ LOCAL_NONE
Definition: net.h:231
@ LOCAL_MAPPED
Definition: net.h:237
@ LOCAL_MANUAL
Definition: net.h:239
@ LOCAL_MAX
Definition: net.h:241
@ LOCAL_BIND
Definition: net.h:235
@ LOCAL_IF
Definition: net.h:233
std::string userAgent(const Config &config)
Definition: net.cpp:3431
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:75
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:2642
bool IsReachable(enum Network net)
Definition: net.cpp:325
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:335
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:44
ConnectionDirection
Definition: netbase.h:32
int64_t NodeId
Definition: nodeid.h:10
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:291
bool fInbound
Definition: net.h:110
CService resolvedAddress
Definition: net.h:108
bool fConnected
Definition: net.h:109
std::string strAddedNode
Definition: net.h:107
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1269
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1271
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1270
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1096
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1099
NetPermissionFlags m_permissions
Definition: net.h:1104
std::shared_ptr< Sock > sock
Definition: net.h:1095
int m_max_outbound_block_relay
Definition: net.h:862
unsigned int nReceiveFloodSize
Definition: net.h:870
int m_max_outbound_full_relay
Definition: net.h:861
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:876
uint64_t nMaxOutboundLimit
Definition: net.h:871
CClientUIInterface * uiInterface
Definition: net.h:866
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:874
int m_max_avalanche_outbound
Definition: net.h:863
std::vector< CService > onion_binds
Definition: net.h:878
int nMaxFeeler
Definition: net.h:865
std::vector< std::string > m_specified_outgoing
Definition: net.h:883
bool whitelist_relay
Definition: net.h:887
int nMaxConnections
Definition: net.h:860
ServiceFlags nLocalServices
Definition: net.h:859
std::vector< std::string > m_added_nodes
Definition: net.h:884
int64_t m_peer_connect_timeout
Definition: net.h:872
std::vector< CService > vBinds
Definition: net.h:877
unsigned int nSendBufferMaxSize
Definition: net.h:869
bool m_i2p_accept_incoming
Definition: net.h:885
std::vector< std::string > vSeedNodes
Definition: net.h:873
BanMan * m_banman
Definition: net.h:868
bool m_use_addrman_outgoing
Definition: net.h:882
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:867
bool whitelist_forcerelay
Definition: net.h:886
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:881
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:875
int nMaxAddnode
Definition: net.h:864
NetPermissionFlags permission_flags
Definition: net.h:455
bool prefer_evict
Definition: net.h:456
POD that contains various stats about a node.
Definition: net.h:287
std::string addrLocal
Definition: net.h:313
CAddress addrBind
Definition: net.h:317
uint64_t nRecvBytes
Definition: net.h:307
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:306
std::chrono::microseconds m_last_ping_time
Definition: net.h:310
uint32_t m_mapped_as
Definition: net.h:320
bool fInbound
Definition: net.h:299
uint64_t nSendBytes
Definition: net.h:305
std::chrono::seconds m_last_recv
Definition: net.h:290
std::optional< double > m_availabilityScore
Definition: net.h:322
std::chrono::seconds m_last_proof_time
Definition: net.h:292
ConnectionType m_conn_type
Definition: net.h:321
std::chrono::seconds m_last_send
Definition: net.h:289
std::chrono::seconds m_last_tx_time
Definition: net.h:291
CAddress addr
Definition: net.h:315
std::chrono::microseconds m_min_ping_time
Definition: net.h:311
int64_t nTimeOffset
Definition: net.h:295
std::chrono::seconds m_connected
Definition: net.h:294
bool m_bip152_highbandwidth_from
Definition: net.h:303
bool m_bip152_highbandwidth_to
Definition: net.h:301
std::string m_addr_name
Definition: net.h:296
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:308
int nVersion
Definition: net.h:297
std::chrono::seconds m_last_block_time
Definition: net.h:293
Network m_network
Definition: net.h:319
NodeId nodeid
Definition: net.h:288
std::string cleanSubVer
Definition: net.h:298
int m_starting_height
Definition: net.h:304
NetPermissionFlags m_permission_flags
Definition: net.h:309
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:124
std::vector< uint8_t > data
Definition: net.h:131
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:132
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:271
int nScore
Definition: net.h:270
std::chrono::seconds m_last_tx_time
Definition: net.h:1454
Network m_network
Definition: net.h:1461
double availabilityScore
Definition: net.h:1462
std::chrono::seconds m_connected
Definition: net.h:1450
std::chrono::seconds m_last_block_time
Definition: net.h:1452
bool fRelevantServices
Definition: net.h:1455
std::chrono::microseconds m_min_ping_time
Definition: net.h:1451
std::chrono::seconds m_last_proof_time
Definition: net.h:1453
uint64_t nKeyedNetGroup
Definition: net.h:1458
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())
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:14