Bitcoin ABC 0.33.5
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Copyright (c) 2017-2019 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#ifndef BITCOIN_NET_H
8#define BITCOIN_NET_H
9
10#include <avalanche/proofid.h>
12#include <chainparams.h>
13#include <common/bloom.h>
14#include <compat/compat.h>
15#include <consensus/amount.h>
16#include <crypto/siphash.h>
17#include <hash.h>
18#include <i2p.h>
19#include <kernel/cs_main.h>
20#include <logging.h>
21#include <net_permissions.h>
22#include <netaddress.h>
23#include <netbase.h>
25#include <node/eviction.h>
27#include <nodeid.h>
28#include <protocol.h>
29#include <pubkey.h>
30#include <radix.h>
31#include <random.h>
32#include <span.h>
33#include <streams.h>
34#include <sync.h>
35#include <uint256.h>
36#include <util/check.h>
37#include <util/sock.h>
38#include <util/time.h>
39
40#include <atomic>
41#include <condition_variable>
42#include <cstdint>
43#include <deque>
44#include <functional>
45#include <list>
46#include <map>
47#include <memory>
48#include <optional>
49#include <queue>
50#include <thread>
51#include <vector>
52
53class AddrMan;
54class BanMan;
55class Config;
56class CNode;
57class CScheduler;
59struct bilingual_str;
60
65static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
67static constexpr auto FEELER_INTERVAL = 2min;
69static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
71static const unsigned int MAX_SUBVERSION_LENGTH = 256;
78static const int MAX_ADDNODE_CONNECTIONS = 8;
87static const int MAX_FEELER_CONNECTIONS = 1;
89static const bool DEFAULT_LISTEN = true;
95static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
97static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
99static const bool DEFAULT_BLOCKSONLY = false;
101static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
103static const int NUM_FDS_MESSAGE_CAPTURE = 1;
104
105static const bool DEFAULT_FORCEDNSSEED = false;
106static const bool DEFAULT_DNSSEED = true;
107static const bool DEFAULT_FIXEDSEEDS = true;
108static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
109static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
110
112 std::string strAddedNode;
116};
117
118struct CNodeStats;
120
122 CSerializedNetMsg() = default;
125 // No copying, only moves.
128
131 copy.data = data;
132 copy.m_type = m_type;
133 return copy;
134 }
135
136 std::vector<uint8_t> data;
137 std::string m_type;
138};
139
140const std::vector<std::string> CONNECTION_TYPE_DOC{
141 "outbound-full-relay (default automatic connections)",
142 "block-relay-only (does not relay transactions or addresses)",
143 "inbound (initiated by the peer)",
144 "manual (added via addnode RPC or -addnode/-connect configuration options)",
145 "addr-fetch (short-lived automatic connection for soliciting addresses)",
146 "feeler (short-lived automatic connection for testing addresses)"};
147
154void Discover();
155
156uint16_t GetListenPort();
157
158enum {
159 // unknown
161 // address a local interface listens on
163 // address explicit bound to
165 // address reported by PCP
167 // address explicitly specified (-externalip=)
169
172
173bool IsPeerAddrLocalGood(CNode *pnode);
175std::optional<CService> GetLocalAddrForPeer(CNode &node);
176
181void SetReachable(enum Network net, bool reachable);
183bool IsReachable(enum Network net);
185bool IsReachable(const CNetAddr &addr);
186
187bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
188bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
189void RemoveLocal(const CService &addr);
190bool SeenLocal(const CService &addr);
191bool IsLocal(const CService &addr);
192bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
193CService GetLocalAddress(const CNetAddr &addrPeer);
194
195extern bool fDiscover;
196extern bool fListen;
197
200 uint16_t nPort;
201};
202
204extern std::map<CNetAddr, LocalServiceInfo>
206
207extern const std::string NET_MESSAGE_TYPE_OTHER;
208typedef std::map</* message type */ std::string, /* total bytes */ uint64_t>
210
218 std::chrono::seconds m_last_send;
219 std::chrono::seconds m_last_recv;
220 std::chrono::seconds m_last_tx_time;
221 std::chrono::seconds m_last_proof_time;
222 std::chrono::seconds m_last_block_time;
223 std::chrono::seconds m_connected;
224 int64_t nTimeOffset;
225 std::string m_addr_name;
227 std::string cleanSubVer;
229 // We requested high bandwidth connection to peer
231 // Peer requested high bandwidth connection
234 uint64_t nSendBytes;
236 uint64_t nRecvBytes;
239 std::chrono::microseconds m_last_ping_time;
240 std::chrono::microseconds m_min_ping_time;
241 // Our address, as reported by the peer
242 std::string addrLocal;
243 // Address of this peer
245 // Bind address of our side of the connection
247 // Network the peer connected through
249 uint32_t m_mapped_as;
251 std::optional<double> m_availabilityScore;
252};
253
260public:
264 std::chrono::microseconds m_time{0};
266 uint32_t m_message_size{0};
269 std::string m_type;
270
271 CNetMessage(DataStream &&recv_in) : m_recv(std::move(recv_in)) {}
272 // Only one CNetMessage object will exist for the same message on either
273 // the receive or processing queue. For performance reasons we therefore
274 // delete the copy constructor and assignment operator to avoid the
275 // possibility of copying CNetMessage objects.
277 CNetMessage(const CNetMessage &) = delete;
280};
281
288public:
289 // returns true if the current deserialization is complete
290 virtual bool Complete() const = 0;
292 virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
293 // decomposes a message from the context
294 virtual std::optional<CNetMessage>
295 GetMessage(std::chrono::microseconds time, uint32_t &out_err) = 0;
297};
298
300private:
302 // Only for logging
306
307 // Parsing header (false) or data (true)
309 // Partially received header.
311 // Complete header.
313 // Received message data.
315 uint32_t nHdrPos;
316 uint32_t nDataPos;
317
318 const uint256 &GetMessageHash() const;
319 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
320 int readData(Span<const uint8_t> msg_bytes);
321
322 void Reset() {
323 vRecv.clear();
324 hdrbuf.clear();
325 hdrbuf.resize(24);
326 in_data = false;
327 nHdrPos = 0;
328 nDataPos = 0;
330 hasher.Reset();
331 }
332
333public:
334 explicit V1TransportDeserializer(const Config &config, const NodeId node_id)
335 : m_config(config), m_node_id(node_id) {
336 Reset();
337 }
338
339 bool Complete() const override {
340 if (!in_data) {
341 return false;
342 }
343
344 return (hdr.nMessageSize == nDataPos);
345 }
346
347 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
348 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
349 if (ret < 0) {
350 Reset();
351 } else {
352 msg_bytes = msg_bytes.subspan(ret);
353 }
354 return ret;
355 }
356
357 std::optional<CNetMessage> GetMessage(std::chrono::microseconds time,
358 uint32_t &out_err_raw_size) override;
359};
360
365public:
366 // prepare message for transport (header construction, error-correction
367 // computation, payload encryption, etc.)
368 virtual void prepareForTransport(const Config &config,
370 std::vector<uint8_t> &header) const = 0;
372};
373
375public:
376 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
377 std::vector<uint8_t> &header) const override;
378};
379
381 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
383 bool prefer_evict = false;
385};
386
388class CNode {
389public:
390 // Used only by SocketHandler thread
391 const std::unique_ptr<TransportDeserializer> m_deserializer;
392 const std::unique_ptr<const TransportSerializer> m_serializer;
393
395
405 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
406
408 size_t nSendSize GUARDED_BY(cs_vSend){0};
410 size_t nSendOffset GUARDED_BY(cs_vSend){0};
411 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
412 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
416
417 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
418
419 std::atomic<std::chrono::seconds> m_last_send{0s};
420 std::atomic<std::chrono::seconds> m_last_recv{0s};
422 const std::chrono::seconds m_connected;
423 std::atomic<int64_t> nTimeOffset{0};
424 // Address of this peer
426 // Bind address of our side of the connection
428 const std::string m_addr_name;
431 const bool m_inbound_onion;
432 std::atomic<int> nVersion{0};
433 // The nonce provided by the remote host.
434 uint64_t nRemoteHostNonce{0};
435 // The extra entropy provided by the remote host.
442 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
443 // This peer is preferred for eviction.
444 const bool m_prefer_evict{false};
445 bool HasPermission(NetPermissionFlags permission) const {
447 }
448 std::atomic_bool fSuccessfullyConnected{false};
449 // Setting fDisconnect to true will cause the node to be disconnected the
450 // next time DisconnectNodes() runs
451 std::atomic_bool fDisconnect{false};
453 std::atomic<int> nRefCount{0};
454
455 const uint64_t nKeyedNetGroup;
456 std::atomic_bool fPauseRecv{false};
457 std::atomic_bool fPauseSend{false};
458
460
464
472 std::optional<std::pair<CNetMessage, bool>> PollMessage()
474
479 void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes)
481 mapSendBytesPerMsgType[msg_type] += sent_bytes;
482 }
483
485 switch (m_conn_type) {
489 return true;
494 return false;
495 } // no default case, so the compiler can warn about missing cases
496
497 assert(false);
498 }
499
500 bool IsFullOutboundConn() const {
503 }
504
506
507 bool IsBlockOnlyConn() const {
509 }
510
512
513 bool IsAddrFetchConn() const {
515 }
516
517 bool IsInboundConn() const {
519 }
520
523 }
524
526 switch (m_conn_type) {
530 return false;
535 return true;
536 } // no default case, so the compiler can warn about missing cases
537
538 assert(false);
539 }
540
553
554 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
555 std::atomic<bool> m_bip152_highbandwidth_to{false};
556 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
557 std::atomic<bool> m_bip152_highbandwidth_from{false};
558
563 std::atomic_bool m_has_all_wanted_services{false};
564
569 std::atomic_bool m_relays_txs{false};
570
575 std::atomic_bool m_bloom_filter_loaded{false};
576
577 // True if we know this peer is using Avalanche (at least polling)
578 std::atomic<bool> m_avalanche_enabled{false};
579
581 // Pubkey used to verify signatures on Avalanche messages from this peer
582 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
583
585 void invsPolled(uint32_t count);
586
588 void invsVoted(uint32_t count);
589
606 void updateAvailabilityScore(double decayFactor);
607 double getAvailabilityScore() const;
608
609 // Store the next time we will consider a getavaaddr message from this peer
610 std::chrono::seconds m_nextGetAvaAddr{0};
611
612 // The last time the node sent us a faulty message
613 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
625
627
635 std::atomic<std::chrono::seconds> m_last_block_time{0s};
636
643 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
644
651 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
652
654 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
655
660 std::atomic<std::chrono::microseconds> m_min_ping_time{
661 std::chrono::microseconds::max()};
662
663 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
664 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
665 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
666 const std::string &addrNameIn, ConnectionType conn_type_in,
667 bool inbound_onion, CNodeOptions &&node_opts = {});
668 CNode(const CNode &) = delete;
669 CNode &operator=(const CNode &) = delete;
670
675 void PongReceived(std::chrono::microseconds ping_time) {
676 m_last_ping_time = ping_time;
677 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
678 }
679
680 NodeId GetId() const { return id; }
681
682 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
683 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
684
685 int GetRefCount() const {
686 assert(nRefCount >= 0);
687 return nRefCount;
688 }
689
699 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
700 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
701
702 void SetCommonVersion(int greatest_common_version) {
704 m_greatest_common_version = greatest_common_version;
705 }
707
710 void SetAddrLocal(const CService &addrLocalIn)
712
714 nRefCount++;
715 return this;
716 }
717
718 void Release() { nRefCount--; }
719
721
722 void copyStats(CNodeStats &stats)
725
726 std::string ConnectionTypeAsString() const {
728 }
729
730private:
731 const NodeId id;
732 const uint64_t nLocalHostNonce;
733 const uint64_t nLocalExtraEntropy;
735
736 const size_t m_recv_flood_size;
737 // Used only by SocketHandler thread
738 std::list<CNetMessage> vRecvMsg;
739
741 std::list<CNetMessage>
743 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
744
745 // Our address, as reported by the peer
748
754 std::atomic<uint64_t> invCounters{0};
755
757 std::atomic<double> availabilityScore{0.};
758
759 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
760 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
761
771 std::unique_ptr<i2p::sam::Session>
772 m_i2p_sam_session GUARDED_BY(m_sock_mutex);
773};
774
779public:
784
786 virtual void InitializeNode(const Config &config, CNode &node,
787 ServiceFlags our_services) = 0;
788
790 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
791
801 virtual bool ProcessMessages(const Config &config, CNode *pnode,
802 std::atomic<bool> &interrupt)
804
812 virtual bool SendMessages(const Config &config, CNode *pnode)
814
815protected:
822};
823
824namespace {
825struct CConnmanTest;
826}
827
829class CConnman {
830public:
831 struct Options {
837 int nMaxAddnode = 0;
838 int nMaxFeeler = 0;
840 std::vector<NetEventsInterface *> m_msgproc;
841 BanMan *m_banman = nullptr;
842 unsigned int nSendBufferMaxSize = 0;
843 unsigned int nReceiveFloodSize = 0;
844 uint64_t nMaxOutboundLimit = 0;
846 std::vector<std::string> vSeedNodes;
847 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
848 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
849 std::vector<NetWhitebindPermissions> vWhiteBinds;
850 std::vector<CService> vBinds;
851 std::vector<CService> onion_binds;
856 std::vector<std::string> m_specified_outgoing;
857 std::vector<std::string> m_added_nodes;
861 };
862
863 void Init(const Options &connOptions)
865 nLocalServices = connOptions.nLocalServices;
866 nMaxConnections = connOptions.nMaxConnections;
867 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
868 nMaxAddnode = connOptions.nMaxAddnode;
869 nMaxFeeler = connOptions.nMaxFeeler;
870 {
871 // Lock cs_main to prevent a potential race with the peer validation
872 // logic thread.
875 std::min(connOptions.m_max_outbound_full_relay,
876 connOptions.nMaxConnections);
877 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
878 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
882 }
883 m_client_interface = connOptions.uiInterface;
884 m_banman = connOptions.m_banman;
885 m_msgproc = connOptions.m_msgproc;
886 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
887 nReceiveFloodSize = connOptions.nReceiveFloodSize;
889 std::chrono::seconds{connOptions.m_peer_connect_timeout};
890 {
892 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
893 }
894 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
895 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
896 {
898 m_added_nodes = connOptions.m_added_nodes;
899 }
900 m_onion_binds = connOptions.onion_binds;
901 whitelist_forcerelay = connOptions.whitelist_forcerelay;
902 whitelist_relay = connOptions.whitelist_relay;
903 }
904
905 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
906 AddrMan &addrmanIn, bool network_active = true);
907 virtual ~CConnman();
908
909 bool Start(CScheduler &scheduler, const Options &options)
912
913 void StopThreads();
914 void StopNodes();
915 void Stop() {
916 StopThreads();
917 StopNodes();
918 };
919
921 bool GetNetworkActive() const { return fNetworkActive; };
923 void SetNetworkActive(bool active);
924 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
925 CSemaphoreGrant *grantOutbound,
926 const char *strDest, ConnectionType conn_type)
928 bool CheckIncomingNonce(uint64_t nonce);
929
930 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
931
932 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
933
934 using NodeFn = std::function<void(CNode *)>;
935 void ForEachNode(const NodeFn &func) {
937 for (auto &&node : m_nodes) {
939 func(node);
940 }
941 }
942 };
943
944 void ForEachNode(const NodeFn &func) const {
946 for (auto &&node : m_nodes) {
948 func(node);
949 }
950 }
951 };
952
953 // Addrman functions
964 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
965 std::optional<Network> network) const;
972 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
973 size_t max_pct);
974
975 // This allows temporarily exceeding m_max_outbound_full_relay, with the
976 // goal of finding a peer that is better than all our current peers.
977 void SetTryNewOutboundPeer(bool flag);
978 bool GetTryNewOutboundPeer() const;
979
981 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
983 }
984
985 // Return the number of outbound peers we have in excess of our target (eg,
986 // if we previously called SetTryNewOutboundPeer(true), and have since set
987 // to false, we may have extra peers that we wish to disconnect). This may
988 // return a value less than (num_outbound_connections - num_outbound_slots)
989 // in cases where some outbound connections are not yet fully connected, or
990 // not yet fully disconnected.
991 int GetExtraFullOutboundCount() const;
992 // Count the number of block-relay-only peers we have over our limit.
993 int GetExtraBlockRelayCount() const;
994
995 bool AddNode(const std::string &node)
997 bool RemoveAddedNode(const std::string &node)
999 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
1001
1016 bool AddConnection(const std::string &address, ConnectionType conn_type)
1018
1019 size_t GetNodeCount(ConnectionDirection) const;
1020 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1021 bool GetNodeStats(NodeId id, CNodeStats &stats) const;
1022 bool DisconnectNode(const std::string &node);
1023 bool DisconnectNode(const CSubNet &subnet);
1024 bool DisconnectNode(const CNetAddr &addr);
1025 bool DisconnectNode(NodeId id);
1026
1034
1039 };
1042 }
1043
1044 uint64_t GetMaxOutboundTarget() const;
1045 std::chrono::seconds GetMaxOutboundTimeframe() const;
1046
1050 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1051
1054 uint64_t GetOutboundTargetBytesLeft() const;
1055
1058 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1059
1060 uint64_t GetTotalBytesRecv() const;
1061 uint64_t GetTotalBytesSent() const;
1062
1064 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1065
1067
1073 std::chrono::seconds now) const;
1074
1075private:
1077 public:
1078 std::shared_ptr<Sock> sock;
1080 NetPermissions::AddFlag(flags, m_permissions);
1081 }
1082 ListenSocket(std::shared_ptr<Sock> sock_,
1083 NetPermissionFlags permissions_)
1084 : sock(sock_), m_permissions(permissions_) {}
1085
1086 private:
1088 };
1089
1090 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1091 NetPermissionFlags permissions);
1092 bool Bind(const CService &addr, unsigned int flags,
1093 NetPermissionFlags permissions);
1094 bool InitBinds(const Options &options);
1095
1099 void AddAddrFetch(const std::string &strDest)
1101 void ProcessAddrFetch()
1104 void
1105 ThreadOpenConnections(std::vector<std::string> connect,
1106 std::function<void(const CAddress &, ConnectionType)>
1107 mockOpenConnection)
1112 void AcceptConnection(const ListenSocket &hListenSocket);
1113
1122 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1123 NetPermissionFlags permission_flags,
1124 const CAddress &addr_bind,
1125 const CAddress &addr);
1126
1127 void DisconnectNodes();
1130 bool InactivityCheck(const CNode &node) const;
1131
1137 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1138
1144
1151 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1152 const Sock::EventsPerSock &events_per_sock)
1154
1159 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1160
1164
1165 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1166
1167 CNode *FindNode(const CNetAddr &ip);
1168 CNode *FindNode(const CSubNet &subNet);
1169 CNode *FindNode(const std::string &addrName);
1170 CNode *FindNode(const CService &addr);
1171
1176 bool AlreadyConnectedToAddress(const CAddress &addr);
1177
1179 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1180 bool fCountFailure, ConnectionType conn_type)
1182 ;
1184 NetPermissionFlags &flags, const CNetAddr &addr,
1185 const std::vector<NetWhitelistPermissions> &ranges) const;
1186
1187 void DeleteNode(CNode *pnode);
1188
1190
1195 std::pair<size_t, bool> SocketSendData(CNode &node) const
1197
1198 void DumpAddresses();
1199
1200 // Network stats
1201 void RecordBytesRecv(uint64_t bytes);
1202 void RecordBytesSent(uint64_t bytes);
1203
1208
1209 // Whether the node should be passed out in ForEach* callbacks
1210 static bool NodeFullyConnected(const CNode *pnode);
1211
1213
1214 // Network usage totals
1216 std::atomic<uint64_t> nTotalBytesRecv{0};
1217 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1218
1219 // outbound limit & stats
1220 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1221 std::chrono::seconds
1222 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1223 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1224
1225 // P2P timeout in seconds
1226 std::chrono::seconds m_peer_connect_timeout;
1227
1228 // Whitelisted ranges. Any node connecting from these is automatically
1229 // whitelisted (as well as those connecting to whitelisted binds).
1230 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1231 // Whitelisted ranges for outgoing connections.
1232 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1233
1234 unsigned int nSendBufferMaxSize{0};
1235 unsigned int nReceiveFloodSize{0};
1236
1237 std::vector<ListenSocket> vhListenSocket;
1238 std::atomic<bool> fNetworkActive{true};
1241 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1243 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1245 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1246 std::list<CNode *> m_nodes_disconnected;
1248 std::atomic<NodeId> nLastNodeId{0};
1249 unsigned int nPrevNodeCount{0};
1250
1258 std::vector<CAddress> m_addrs_response_cache;
1259 std::chrono::microseconds m_cache_entry_expiration{0};
1260 };
1261
1276 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1277
1289 std::atomic<ServiceFlags> nLocalServices;
1290
1291 std::unique_ptr<CSemaphore> semOutbound;
1292 std::unique_ptr<CSemaphore> semAddnode;
1294
1295 // How many full-relay (tx, block, addr) outbound peers we want
1297
1298 // How many block-relay only outbound peers we want
1299 // We do not relay tx or addr messages with these peers
1301
1302 // How many avalanche enabled outbound peers we want
1304
1310 // FIXME m_msgproc is a terrible name
1311 std::vector<NetEventsInterface *> m_msgproc;
1317
1322 std::vector<CAddress> m_anchors;
1323
1325 const uint64_t nSeed0, nSeed1;
1326
1328 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1329
1330 std::condition_variable condMsgProc;
1332 std::atomic<bool> flagInterruptMsgProc{false};
1333
1341
1347 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1348
1355
1361
1367 std::atomic_bool m_start_extra_block_relay_peers{false};
1368
1373 std::vector<CService> m_onion_binds;
1374
1379
1387 std::queue<std::unique_ptr<i2p::sam::Session>>
1389
1394 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1395
1401
1407
1414 public:
1415 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1416 {
1417 LOCK(connman.m_nodes_mutex);
1418 m_nodes_copy = connman.m_nodes;
1419 for (auto &node : m_nodes_copy) {
1420 node->AddRef();
1421 }
1422 }
1423 if (shuffle) {
1424 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1426 }
1427 }
1428
1430 for (auto &node : m_nodes_copy) {
1431 node->Release();
1432 }
1433 }
1434
1435 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1436
1437 private:
1438 std::vector<CNode *> m_nodes_copy;
1439 };
1440
1441 friend struct ::CConnmanTest;
1442 friend struct ConnmanTestMsg;
1443};
1444
1445std::string getSubVersionEB(uint64_t MaxBlockSize);
1446std::string userAgent(const Config &config);
1447
1449void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1450 Span<const uint8_t> data, bool is_incoming);
1451
1455extern std::function<void(const CAddress &addr, const std::string &msg_type,
1456 Span<const uint8_t> data, bool is_incoming)>
1458
1459#endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:546
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:68
Definition: banman.h:59
A CService with information about it as peer.
Definition: protocol.h:442
Signals for UI communication.
Definition: ui_interface.h:25
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1413
const std::vector< CNode * > & Nodes() const
Definition: net.h:1435
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1415
std::vector< CNode * > m_nodes_copy
Definition: net.h:1438
Definition: net.h:829
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1406
std::condition_variable condMsgProc
Definition: net.h:1330
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1217
bool AddConnection(const std::string &address, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1146
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1222
std::thread threadMessageHandler
Definition: net.h:1353
void ForEachNode(const NodeFn &func)
Definition: net.h:935
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:2914
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1040
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:2930
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1230
CClientUIInterface * m_client_interface
Definition: net.h:1309
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2193
void ForEachNode(const NodeFn &func) const
Definition: net.h:944
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3125
void DeleteNode(CNode *pnode)
Definition: net.cpp:2695
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2786
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:957
bool GetNetworkActive() const
Definition: net.h:921
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:1307
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
Definition: net.h:1394
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1650
void Stop()
Definition: net.h:915
int m_max_outbound_block_relay
Definition: net.h:1300
std::thread threadI2PAcceptIncoming
Definition: net.h:1354
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1654
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1332
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2616
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1487
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1305
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:1359
NodeId GetNewNodeId()
Definition: net.cpp:2419
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1340
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1292
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2482
std::atomic< NodeId > nLastNodeId
Definition: net.h:1248
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2890
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1682
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1479
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1316
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:2953
std::thread threadDNSAddressSeed
Definition: net.h:1349
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1289
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2244
const uint64_t nSeed1
Definition: net.h:1325
void StartExtraBlockRelayPeers()
Definition: net.h:980
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1322
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2910
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1400
friend struct ConnmanTestMsg
Definition: net.h:1442
unsigned int nPrevNodeCount
Definition: net.h:1249
void NotifyNumConnectionsChanged()
Definition: net.cpp:1246
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2973
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2841
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1226
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:1360
bool InitBinds(const Options &options)
Definition: net.cpp:2445
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:135
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1220
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1237
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:2143
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2041
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3137
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2905
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1291
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2110
RecursiveMutex cs_totalBytesSent
Definition: net.h:1215
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2423
std::thread threadOpenConnections
Definition: net.h:1352
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2798
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1631
Mutex m_addr_fetches_mutex
Definition: net.h:1242
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1265
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:354
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2816
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2053
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1325
unsigned int nReceiveFloodSize
Definition: net.h:1235
int GetExtraFullOutboundCount() const
Definition: net.cpp:1666
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2964
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:880
RecursiveMutex m_nodes_mutex
Definition: net.h:1247
std::queue< std::unique_ptr< i2p::sam::Session > > m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex)
A pool of created I2P SAM transient sessions that should be used instead of creating new ones in orde...
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3075
int nMaxConnections
Definition: net.h:1293
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2408
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:2709
std::function< void(CNode *)> NodeFn
Definition: net.h:934
void SetNetworkActive(bool active)
Definition: net.cpp:2394
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1246
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:1037
AddrMan & addrman
Definition: net.h:1240
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1331
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3141
Mutex mutexMsgProc
Definition: net.h:1331
bool fAddressesInitialized
Definition: net.h:1239
virtual ~CConnman()
Definition: net.cpp:2703
void StopThreads()
Definition: net.cpp:2639
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2774
std::thread threadOpenAddedConnections
Definition: net.h:1351
Mutex m_added_nodes_mutex
Definition: net.h:1244
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:604
const Config * config
Definition: net.h:1212
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:863
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:399
int m_max_outbound_full_relay
Definition: net.h:1296
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1378
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1305
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2886
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:1260
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1471
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:1037
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3079
void StopNodes()
Definition: net.cpp:2660
bool GetUseAddrmanOutgoing() const
Definition: net.h:922
unsigned int nSendBufferMaxSize
Definition: net.h:1234
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1347
bool m_use_addrman_outgoing
Definition: net.h:1308
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1232
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:1276
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1216
std::atomic< bool > fNetworkActive
Definition: net.h:1238
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1367
void DisconnectNodes()
Definition: net.cpp:1196
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1458
void DumpAddresses()
Definition: net.cpp:1622
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:1373
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:426
int nMaxFeeler
Definition: net.h:1306
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1311
std::thread threadSocketHandler
Definition: net.h:1350
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2968
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1696
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1008
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2282
int m_max_avalanche_outbound
Definition: net.h:1303
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:22
CHash256 & Reset()
Definition: hash.h:41
Message header.
Definition: protocol.h:34
uint32_t nMessageSize
Definition: protocol.h:71
Network address.
Definition: netaddress.h:114
Transport protocol agnostic message container.
Definition: net.h:259
CNetMessage(CNetMessage &&)=default
uint32_t m_message_size
size of the payload
Definition: net.h:266
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:264
CNetMessage(DataStream &&recv_in)
Definition: net.h:271
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:268
std::string m_type
Definition: net.h:269
DataStream m_recv
received message data
Definition: net.h:262
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition: net.h:388
Mutex cs_avalanche_pubkey
Definition: net.h:580
const CAddress addrBind
Definition: net.h:427
bool IsFeelerConn() const
Definition: net.h:511
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:422
bool ExpectServicesFromConn() const
Definition: net.h:525
std::atomic< int > nVersion
Definition: net.h:432
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:563
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:417
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:757
bool IsInboundConn() const
Definition: net.h:517
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:445
std::atomic_bool fPauseRecv
Definition: net.h:456
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:484
NodeId GetId() const
Definition: net.h:680
bool IsManualConn() const
Definition: net.h:505
std::atomic< int64_t > nTimeOffset
Definition: net.h:423
const std::string m_addr_name
Definition: net.h:428
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:726
void SetCommonVersion(int greatest_common_version)
Definition: net.h:702
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:555
std::list< CNetMessage > vRecvMsg
Definition: net.h:738
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:569
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:557
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:675
std::atomic_bool fSuccessfullyConnected
Definition: net.h:448
const bool m_prefer_evict
Definition: net.h:444
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:743
bool IsAddrFetchConn() const
Definition: net.h:513
uint64_t GetLocalNonce() const
Definition: net.h:682
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:3006
const CAddress addr
Definition: net.h:425
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:631
CSemaphoreGrant grantOutbound
Definition: net.h:452
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:455
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
std::atomic< int > nRefCount
Definition: net.h:453
std::atomic< int > m_greatest_common_version
Definition: net.h:734
bool IsBlockOnlyConn() const
Definition: net.h:507
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition: net.cpp:3042
int GetCommonVersion() const
Definition: net.h:706
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:500
uint64_t nRemoteHostNonce
Definition: net.h:434
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:441
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:392
Mutex cs_vSend
Definition: net.h:413
CNode * AddRef()
Definition: net.h:713
std::atomic_bool fPauseSend
Definition: net.h:457
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:610
uint64_t nRemoteExtraEntropy
Definition: net.h:436
int GetRefCount() const
Definition: net.h:685
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:3059
uint64_t GetLocalExtraEntropy() const
Definition: net.h:683
SteadyMilliseconds m_last_poll
Definition: net.h:626
double getAvailabilityScore() const
Definition: net.cpp:3000
Mutex m_msg_process_queue_mutex
Definition: net.h:740
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:410
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:575
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:459
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:644
const size_t m_recv_flood_size
Definition: net.h:736
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:648
const uint64_t nLocalHostNonce
Definition: net.h:732
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:654
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:2985
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:408
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:613
const uint64_t nLocalExtraEntropy
Definition: net.h:733
const NetPermissionFlags m_permission_flags
Definition: net.h:394
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:696
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2977
Mutex m_addr_local_mutex
Definition: net.h:746
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:431
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:660
const NodeId id
Definition: net.h:731
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
Definition: net.h:618
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:479
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:651
Mutex cs_vRecv
Definition: net.h:415
std::atomic< bool > m_avalanche_enabled
Definition: net.h:578
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:635
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:391
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:411
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:754
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:414
std::atomic_bool fDisconnect
Definition: net.h:451
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:420
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:624
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:643
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:625
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:2981
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:594
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:419
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
bool IsAvalancheOutboundConnection() const
Definition: net.h:521
void Release()
Definition: net.h:718
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:442
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:778
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:783
virtual bool ProcessMessages(const Config &config, CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool SendMessages(const Config &config, CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void InitializeNode(const Config &config, CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state, queue any initial messages)
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void FinalizeNode(const Config &config, const CNode &node)=0
Handle removal of a peer (clear state)
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:27
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:219
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:287
virtual ~TransportDeserializer()
Definition: net.h:296
virtual bool Complete() const =0
virtual std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err)=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:364
virtual ~TransportSerializer()
Definition: net.h:371
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const =0
CMessageHeader hdr
Definition: net.h:312
const uint256 & GetMessageHash() const
Definition: net.cpp:811
const NodeId m_node_id
Definition: net.h:303
const Config & m_config
Definition: net.h:301
uint32_t nDataPos
Definition: net.h:316
uint32_t nHdrPos
Definition: net.h:315
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:347
V1TransportDeserializer(const Config &config, const NodeId node_id)
Definition: net.h:334
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:794
std::optional< CNetMessage > GetMessage(std::chrono::microseconds time, uint32_t &out_err_raw_size) override
Definition: net.cpp:820
bool Complete() const override
Definition: net.h:339
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:746
CHash256 hasher
Definition: net.h:304
DataStream hdrbuf
Definition: net.h:310
uint256 data_hash
Definition: net.h:305
DataStream vRecv
Definition: net.h:314
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition: net.cpp:864
void SetNull()
Definition: uint256.h:41
256-bit opaque blob.
Definition: uint256.h:129
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
int64_t NodeId
Definition: eviction.h:16
#define LogPrint(category,...)
Definition: logging.h:452
@ NET
Definition: logging.h:69
Definition: messages.h:12
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:240
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:140
uint16_t GetListenPort()
Definition: net.cpp:140
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:95
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:349
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:224
void RemoveLocal(const CService &addr)
Definition: net.cpp:314
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:71
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:65
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:78
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:281
bool fDiscover
Definition: net.cpp:128
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:109
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:103
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:99
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:105
bool fListen
Definition: net.cpp:129
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:97
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:69
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:108
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:85
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:246
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:115
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:320
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:107
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:3229
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:3163
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:130
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:87
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:89
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:175
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:67
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:101
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3197
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:209
static const bool DEFAULT_DNSSEED
Definition: net.h:106
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:76
@ LOCAL_NONE
Definition: net.h:160
@ LOCAL_MAPPED
Definition: net.h:166
@ LOCAL_MANUAL
Definition: net.h:168
@ LOCAL_MAX
Definition: net.h:170
@ LOCAL_BIND
Definition: net.h:164
@ LOCAL_IF
Definition: net.h:162
std::string userAgent(const Config &config)
Definition: net.cpp:3177
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:80
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition: net.cpp:2382
bool IsReachable(enum Network net)
Definition: net.cpp:328
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:338
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:37
ConnectionDirection
Definition: netbase.h:37
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:512
bool fInbound
Definition: net.h:115
CService resolvedAddress
Definition: net.h:113
bool fConnected
Definition: net.h:114
std::string strAddedNode
Definition: net.h:112
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1257
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1259
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1258
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1079
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1082
NetPermissionFlags m_permissions
Definition: net.h:1087
std::shared_ptr< Sock > sock
Definition: net.h:1078
int m_max_outbound_block_relay
Definition: net.h:835
unsigned int nReceiveFloodSize
Definition: net.h:843
int m_max_outbound_full_relay
Definition: net.h:834
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:849
uint64_t nMaxOutboundLimit
Definition: net.h:844
CClientUIInterface * uiInterface
Definition: net.h:839
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:847
int m_max_avalanche_outbound
Definition: net.h:836
std::vector< CService > onion_binds
Definition: net.h:851
int nMaxFeeler
Definition: net.h:838
std::vector< std::string > m_specified_outgoing
Definition: net.h:856
bool whitelist_relay
Definition: net.h:860
int nMaxConnections
Definition: net.h:833
ServiceFlags nLocalServices
Definition: net.h:832
std::vector< std::string > m_added_nodes
Definition: net.h:857
int64_t m_peer_connect_timeout
Definition: net.h:845
std::vector< CService > vBinds
Definition: net.h:850
unsigned int nSendBufferMaxSize
Definition: net.h:842
bool m_i2p_accept_incoming
Definition: net.h:858
std::vector< std::string > vSeedNodes
Definition: net.h:846
BanMan * m_banman
Definition: net.h:841
bool m_use_addrman_outgoing
Definition: net.h:855
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:840
bool whitelist_forcerelay
Definition: net.h:859
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:854
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:848
int nMaxAddnode
Definition: net.h:837
NetPermissionFlags permission_flags
Definition: net.h:382
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition: net.h:381
bool prefer_evict
Definition: net.h:383
size_t recv_flood_size
Definition: net.h:384
POD that contains various stats about a node.
Definition: net.h:216
std::string addrLocal
Definition: net.h:242
CAddress addrBind
Definition: net.h:246
uint64_t nRecvBytes
Definition: net.h:236
std::chrono::microseconds m_last_ping_time
Definition: net.h:239
uint32_t m_mapped_as
Definition: net.h:249
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:237
bool fInbound
Definition: net.h:228
uint64_t nSendBytes
Definition: net.h:234
std::chrono::seconds m_last_recv
Definition: net.h:219
std::optional< double > m_availabilityScore
Definition: net.h:251
std::chrono::seconds m_last_proof_time
Definition: net.h:221
ConnectionType m_conn_type
Definition: net.h:250
std::chrono::seconds m_last_send
Definition: net.h:218
std::chrono::seconds m_last_tx_time
Definition: net.h:220
CAddress addr
Definition: net.h:244
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:235
std::chrono::microseconds m_min_ping_time
Definition: net.h:240
int64_t nTimeOffset
Definition: net.h:224
std::chrono::seconds m_connected
Definition: net.h:223
bool m_bip152_highbandwidth_from
Definition: net.h:232
bool m_bip152_highbandwidth_to
Definition: net.h:230
std::string m_addr_name
Definition: net.h:225
int nVersion
Definition: net.h:226
std::chrono::seconds m_last_block_time
Definition: net.h:222
Network m_network
Definition: net.h:248
NodeId nodeid
Definition: net.h:217
std::string cleanSubVer
Definition: net.h:227
int m_starting_height
Definition: net.h:233
NetPermissionFlags m_permission_flags
Definition: net.h:238
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:129
std::vector< uint8_t > data
Definition: net.h:136
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:137
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:200
int nScore
Definition: net.h:199
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:306
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:33
assert(!tx.IsCoinBase())