Bitcoin ABC 0.31.8
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Copyright (c) 2017-2019 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#ifndef BITCOIN_NET_H
8#define BITCOIN_NET_H
9
10#include <avalanche/proofid.h>
12#include <chainparams.h>
13#include <common/bloom.h>
14#include <compat.h>
15#include <consensus/amount.h>
16#include <crypto/siphash.h>
17#include <hash.h>
18#include <i2p.h>
19#include <kernel/cs_main.h>
20#include <logging.h>
21#include <net_permissions.h>
22#include <netaddress.h>
23#include <netbase.h>
25#include <node/eviction.h>
26#include <nodeid.h>
27#include <protocol.h>
28#include <pubkey.h>
29#include <radix.h>
30#include <random.h>
31#include <span.h>
32#include <streams.h>
33#include <sync.h>
34#include <threadinterrupt.h>
35#include <uint256.h>
36#include <util/check.h>
37#include <util/sock.h>
38#include <util/time.h>
39
40#include <atomic>
41#include <condition_variable>
42#include <cstdint>
43#include <deque>
44#include <functional>
45#include <list>
46#include <map>
47#include <memory>
48#include <thread>
49#include <vector>
50
51class AddrMan;
52class BanMan;
53class Config;
54class CNode;
55class CScheduler;
56struct bilingual_str;
57
62static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
64static constexpr auto FEELER_INTERVAL = 2min;
66static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
68static const unsigned int MAX_SUBVERSION_LENGTH = 256;
75static const int MAX_ADDNODE_CONNECTIONS = 8;
84static const int MAX_FEELER_CONNECTIONS = 1;
86static const bool DEFAULT_LISTEN = true;
92static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 4096;
94static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
96static const bool DEFAULT_BLOCKSONLY = false;
98static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
100static const int NUM_FDS_MESSAGE_CAPTURE = 1;
101
102static const bool DEFAULT_FORCEDNSSEED = false;
103static const bool DEFAULT_DNSSEED = true;
104static const bool DEFAULT_FIXEDSEEDS = true;
105static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
106static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
107
109 std::string strAddedNode;
113};
114
115struct CNodeStats;
117
119 CSerializedNetMsg() = default;
122 // No copying, only moves.
125
128 copy.data = data;
129 copy.m_type = m_type;
130 return copy;
131 }
132
133 std::vector<uint8_t> data;
134 std::string m_type;
135};
136
137const std::vector<std::string> CONNECTION_TYPE_DOC{
138 "outbound-full-relay (default automatic connections)",
139 "block-relay-only (does not relay transactions or addresses)",
140 "inbound (initiated by the peer)",
141 "manual (added via addnode RPC or -addnode/-connect configuration options)",
142 "addr-fetch (short-lived automatic connection for soliciting addresses)",
143 "feeler (short-lived automatic connection for testing addresses)"};
144
151void Discover();
152
153uint16_t GetListenPort();
154
155enum {
156 // unknown
158 // address a local interface listens on
160 // address explicit bound to
162 // address reported by UPnP or NAT-PMP
164 // address explicitly specified (-externalip=)
166
169
170bool IsPeerAddrLocalGood(CNode *pnode);
172std::optional<CService> GetLocalAddrForPeer(CNode &node);
173
178void SetReachable(enum Network net, bool reachable);
180bool IsReachable(enum Network net);
182bool IsReachable(const CNetAddr &addr);
183
184bool AddLocal(const CService &addr, int nScore = LOCAL_NONE);
185bool AddLocal(const CNetAddr &addr, int nScore = LOCAL_NONE);
186void RemoveLocal(const CService &addr);
187bool SeenLocal(const CService &addr);
188bool IsLocal(const CService &addr);
189bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
190CService GetLocalAddress(const CNetAddr &addrPeer);
191
192extern bool fDiscover;
193extern bool fListen;
194
197 uint16_t nPort;
198};
199
201extern std::map<CNetAddr, LocalServiceInfo>
203
204extern const std::string NET_MESSAGE_TYPE_OTHER;
205typedef std::map</* message type */ std::string, /* total bytes */ uint64_t>
207
215 std::chrono::seconds m_last_send;
216 std::chrono::seconds m_last_recv;
217 std::chrono::seconds m_last_tx_time;
218 std::chrono::seconds m_last_proof_time;
219 std::chrono::seconds m_last_block_time;
220 std::chrono::seconds m_connected;
221 int64_t nTimeOffset;
222 std::string m_addr_name;
224 std::string cleanSubVer;
226 // We requested high bandwidth connection to peer
228 // Peer requested high bandwidth connection
231 uint64_t nSendBytes;
233 uint64_t nRecvBytes;
236 std::chrono::microseconds m_last_ping_time;
237 std::chrono::microseconds m_min_ping_time;
238 // Our address, as reported by the peer
239 std::string addrLocal;
240 // Address of this peer
242 // Bind address of our side of the connection
244 // Network the peer connected through
246 uint32_t m_mapped_as;
248 std::optional<double> m_availabilityScore;
249};
250
257public:
261 std::chrono::microseconds m_time{0};
262 bool m_valid_netmagic = false;
263 bool m_valid_header = false;
264 bool m_valid_checksum = false;
266 uint32_t m_message_size{0};
269 std::string m_type;
270
271 CNetMessage(CDataStream &&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 void SetVersion(int nVersionIn) { m_recv.SetVersion(nVersionIn); }
282};
283
290public:
291 // returns true if the current deserialization is complete
292 virtual bool Complete() const = 0;
293 // set the serialization context version
294 virtual void SetVersion(int version) = 0;
296 virtual int Read(const Config &config, Span<const uint8_t> &msg_bytes) = 0;
297 // decomposes a message from the context
298 virtual CNetMessage GetMessage(const Config &config,
299 std::chrono::microseconds time) = 0;
301};
302
304private:
307
308 // Parsing header (false) or data (true)
310 // Partially received header.
312 // Complete header.
314 // Received message data.
316 uint32_t nHdrPos;
317 uint32_t nDataPos;
318
319 const uint256 &GetMessageHash() const;
320 int readHeader(const Config &config, Span<const uint8_t> msg_bytes);
321 int readData(Span<const uint8_t> msg_bytes);
322
323 void Reset() {
324 vRecv.clear();
325 hdrbuf.clear();
326 hdrbuf.resize(24);
327 in_data = false;
328 nHdrPos = 0;
329 nDataPos = 0;
331 hasher.Reset();
332 }
333
334public:
336 const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn,
337 int nVersionIn)
338 : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn),
339 vRecv(nTypeIn, nVersionIn) {
340 Reset();
341 }
342
343 bool Complete() const override {
344 if (!in_data) {
345 return false;
346 }
347
348 return (hdr.nMessageSize == nDataPos);
349 }
350
351 void SetVersion(int nVersionIn) override {
352 hdrbuf.SetVersion(nVersionIn);
353 vRecv.SetVersion(nVersionIn);
354 }
355 int Read(const Config &config, Span<const uint8_t> &msg_bytes) override {
356 int ret = in_data ? readData(msg_bytes) : readHeader(config, msg_bytes);
357 if (ret < 0) {
358 Reset();
359 } else {
360 msg_bytes = msg_bytes.subspan(ret);
361 }
362 return ret;
363 }
364
365 CNetMessage GetMessage(const Config &config,
366 std::chrono::microseconds time) override;
367};
368
373public:
374 // prepare message for transport (header construction, error-correction
375 // computation, payload encryption, etc.)
376 virtual void prepareForTransport(const Config &config,
378 std::vector<uint8_t> &header) const = 0;
380};
381
383public:
384 void prepareForTransport(const Config &config, CSerializedNetMsg &msg,
385 std::vector<uint8_t> &header) const override;
386};
387
390 bool prefer_evict = false;
392};
393
395class CNode {
396public:
397 // Used only by SocketHandler thread
398 const std::unique_ptr<TransportDeserializer> m_deserializer;
399 const std::unique_ptr<const TransportSerializer> m_serializer;
400
402
412 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
413
415 size_t nSendSize GUARDED_BY(cs_vSend){0};
417 size_t nSendOffset GUARDED_BY(cs_vSend){0};
418 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
419 std::deque<std::vector<uint8_t>> vSendMsg GUARDED_BY(cs_vSend);
423
424 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
425
426 std::atomic<std::chrono::seconds> m_last_send{0s};
427 std::atomic<std::chrono::seconds> m_last_recv{0s};
429 const std::chrono::seconds m_connected;
430 std::atomic<int64_t> nTimeOffset{0};
431 // Address of this peer
433 // Bind address of our side of the connection
435 const std::string m_addr_name;
438 const bool m_inbound_onion;
439 std::atomic<int> nVersion{0};
440 // The nonce provided by the remote host.
441 uint64_t nRemoteHostNonce{0};
442 // The extra entropy provided by the remote host.
449 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
450 // This peer is preferred for eviction.
451 const bool m_prefer_evict{false};
452 bool HasPermission(NetPermissionFlags permission) const {
454 }
455 std::atomic_bool fSuccessfullyConnected{false};
456 // Setting fDisconnect to true will cause the node to be disconnected the
457 // next time DisconnectNodes() runs
458 std::atomic_bool fDisconnect{false};
460 std::atomic<int> nRefCount{0};
461
462 const uint64_t nKeyedNetGroup;
463 std::atomic_bool fPauseRecv{false};
464 std::atomic_bool fPauseSend{false};
465
467
471
479 std::optional<std::pair<CNetMessage, bool>> PollMessage()
481
486 void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes)
488 mapSendBytesPerMsgType[msg_type] += sent_bytes;
489 }
490
492 switch (m_conn_type) {
496 return true;
501 return false;
502 } // no default case, so the compiler can warn about missing cases
503
504 assert(false);
505 }
506
507 bool IsFullOutboundConn() const {
510 }
511
513
514 bool IsBlockOnlyConn() const {
516 }
517
519
520 bool IsAddrFetchConn() const {
522 }
523
524 bool IsInboundConn() const {
526 }
527
530 }
531
533 switch (m_conn_type) {
537 return false;
542 return true;
543 } // no default case, so the compiler can warn about missing cases
544
545 assert(false);
546 }
547
560
561 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
562 std::atomic<bool> m_bip152_highbandwidth_to{false};
563 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
564 std::atomic<bool> m_bip152_highbandwidth_from{false};
565
570 std::atomic_bool m_has_all_wanted_services{false};
571
576 std::atomic_bool m_relays_txs{false};
577
582 std::atomic_bool m_bloom_filter_loaded{false};
583
584 // True if we know this peer is using Avalanche (at least polling)
585 std::atomic<bool> m_avalanche_enabled{false};
586
588 // Pubkey used to verify signatures on Avalanche messages from this peer
589 std::optional<CPubKey> m_avalanche_pubkey GUARDED_BY(cs_avalanche_pubkey);
590
592 void invsPolled(uint32_t count);
593
595 void invsVoted(uint32_t count);
596
613 void updateAvailabilityScore(double decayFactor);
614 double getAvailabilityScore() const;
615
616 // Store the next time we will consider a getavaaddr message from this peer
617 std::chrono::seconds m_nextGetAvaAddr{0};
618
619 // The last time the node sent us a faulty message
620 std::atomic<std::chrono::seconds> m_avalanche_last_message_fault{0s};
632
634
642 std::atomic<std::chrono::seconds> m_last_block_time{0s};
643
650 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
651
658 std::atomic<std::chrono::seconds> m_last_proof_time{0s};
659
661 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
662
667 std::atomic<std::chrono::microseconds> m_min_ping_time{
668 std::chrono::microseconds::max()};
669
670 CNode(NodeId id, std::shared_ptr<Sock> sock, const CAddress &addrIn,
671 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
672 uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn,
673 const std::string &addrNameIn, ConnectionType conn_type_in,
674 bool inbound_onion, CNodeOptions &&node_opts = {});
675 CNode(const CNode &) = delete;
676 CNode &operator=(const CNode &) = delete;
677
682 void PongReceived(std::chrono::microseconds ping_time) {
683 m_last_ping_time = ping_time;
684 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
685 }
686
687 NodeId GetId() const { return id; }
688
689 uint64_t GetLocalNonce() const { return nLocalHostNonce; }
690 uint64_t GetLocalExtraEntropy() const { return nLocalExtraEntropy; }
691
692 int GetRefCount() const {
693 assert(nRefCount >= 0);
694 return nRefCount;
695 }
696
706 bool ReceiveMsgBytes(const Config &config, Span<const uint8_t> msg_bytes,
707 bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
708
709 void SetCommonVersion(int greatest_common_version) {
711 m_greatest_common_version = greatest_common_version;
712 }
714
717 void SetAddrLocal(const CService &addrLocalIn)
719
721 nRefCount++;
722 return this;
723 }
724
725 void Release() { nRefCount--; }
726
728
729 void copyStats(CNodeStats &stats)
732
733 std::string ConnectionTypeAsString() const {
735 }
736
737private:
738 const NodeId id;
739 const uint64_t nLocalHostNonce;
740 const uint64_t nLocalExtraEntropy;
742
743 const size_t m_recv_flood_size;
744 // Used only by SocketHandler thread
745 std::list<CNetMessage> vRecvMsg;
746
748 std::list<CNetMessage>
750 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
751
752 // Our address, as reported by the peer
755
761 std::atomic<uint64_t> invCounters{0};
762
764 std::atomic<double> availabilityScore{0.};
765
766 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
767 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
768};
769
774public:
779
781 virtual void InitializeNode(const Config &config, CNode &node,
782 ServiceFlags our_services) = 0;
783
785 virtual void FinalizeNode(const Config &config, const CNode &node) = 0;
786
796 virtual bool ProcessMessages(const Config &config, CNode *pnode,
797 std::atomic<bool> &interrupt)
799
807 virtual bool SendMessages(const Config &config, CNode *pnode)
809
810protected:
817};
818
819namespace {
820struct CConnmanTest;
821}
822
824class CConnman {
825public:
826 struct Options {
832 int nMaxAddnode = 0;
833 int nMaxFeeler = 0;
835 std::vector<NetEventsInterface *> m_msgproc;
836 BanMan *m_banman = nullptr;
837 unsigned int nSendBufferMaxSize = 0;
838 unsigned int nReceiveFloodSize = 0;
839 uint64_t nMaxOutboundLimit = 0;
841 std::vector<std::string> vSeedNodes;
842 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
843 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
844 std::vector<NetWhitebindPermissions> vWhiteBinds;
845 std::vector<CService> vBinds;
846 std::vector<CService> onion_binds;
851 std::vector<std::string> m_specified_outgoing;
852 std::vector<std::string> m_added_nodes;
856 };
857
858 void Init(const Options &connOptions)
860 nLocalServices = connOptions.nLocalServices;
861 nMaxConnections = connOptions.nMaxConnections;
862 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
863 nMaxAddnode = connOptions.nMaxAddnode;
864 nMaxFeeler = connOptions.nMaxFeeler;
865 {
866 // Lock cs_main to prevent a potential race with the peer validation
867 // logic thread.
870 std::min(connOptions.m_max_outbound_full_relay,
871 connOptions.nMaxConnections);
872 m_max_avalanche_outbound = connOptions.m_max_avalanche_outbound;
873 m_max_outbound_block_relay = connOptions.m_max_outbound_block_relay;
877 }
878 m_client_interface = connOptions.uiInterface;
879 m_banman = connOptions.m_banman;
880 m_msgproc = connOptions.m_msgproc;
881 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
882 nReceiveFloodSize = connOptions.nReceiveFloodSize;
884 std::chrono::seconds{connOptions.m_peer_connect_timeout};
885 {
887 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
888 }
889 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
890 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
891 {
893 m_added_nodes = connOptions.m_added_nodes;
894 }
895 m_onion_binds = connOptions.onion_binds;
896 whitelist_forcerelay = connOptions.whitelist_forcerelay;
897 whitelist_relay = connOptions.whitelist_relay;
898 }
899
900 CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1,
901 AddrMan &addrmanIn, bool network_active = true);
902 ~CConnman();
903
904 bool Start(CScheduler &scheduler, const Options &options)
907
908 void StopThreads();
909 void StopNodes();
910 void Stop() {
911 StopThreads();
912 StopNodes();
913 };
914
916 bool GetNetworkActive() const { return fNetworkActive; };
918 void SetNetworkActive(bool active);
919 void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure,
920 CSemaphoreGrant *grantOutbound,
921 const char *strDest, ConnectionType conn_type);
922 bool CheckIncomingNonce(uint64_t nonce);
923
924 bool ForNode(NodeId id, std::function<bool(CNode *pnode)> func);
925
926 void PushMessage(CNode *pnode, CSerializedNetMsg &&msg);
927
928 using NodeFn = std::function<void(CNode *)>;
929 void ForEachNode(const NodeFn &func) {
931 for (auto &&node : m_nodes) {
933 func(node);
934 }
935 }
936 };
937
938 void ForEachNode(const NodeFn &func) const {
940 for (auto &&node : m_nodes) {
942 func(node);
943 }
944 }
945 };
946
947 // Addrman functions
958 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct,
959 std::optional<Network> network) const;
966 std::vector<CAddress> GetAddresses(CNode &requestor, size_t max_addresses,
967 size_t max_pct);
968
969 // This allows temporarily exceeding m_max_outbound_full_relay, with the
970 // goal of finding a peer that is better than all our current peers.
971 void SetTryNewOutboundPeer(bool flag);
972 bool GetTryNewOutboundPeer() const;
973
975 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
977 }
978
979 // Return the number of outbound peers we have in excess of our target (eg,
980 // if we previously called SetTryNewOutboundPeer(true), and have since set
981 // to false, we may have extra peers that we wish to disconnect). This may
982 // return a value less than (num_outbound_connections - num_outbound_slots)
983 // in cases where some outbound connections are not yet fully connected, or
984 // not yet fully disconnected.
985 int GetExtraFullOutboundCount() const;
986 // Count the number of block-relay-only peers we have over our limit.
987 int GetExtraBlockRelayCount() const;
988
989 bool AddNode(const std::string &node)
991 bool RemoveAddedNode(const std::string &node)
993 std::vector<AddedNodeInfo> GetAddedNodeInfo() const
995
1010 bool AddConnection(const std::string &address, ConnectionType conn_type);
1011
1012 size_t GetNodeCount(ConnectionDirection) const;
1013 void GetNodeStats(std::vector<CNodeStats> &vstats) const;
1014 bool GetNodeStats(NodeId id, CNodeStats &stats) const;
1015 bool DisconnectNode(const std::string &node);
1016 bool DisconnectNode(const CSubNet &subnet);
1017 bool DisconnectNode(const CNetAddr &addr);
1018 bool DisconnectNode(NodeId id);
1019
1027
1032 };
1035 }
1036
1037 uint64_t GetMaxOutboundTarget() const;
1038 std::chrono::seconds GetMaxOutboundTimeframe() const;
1039
1043 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
1044
1047 uint64_t GetOutboundTargetBytesLeft() const;
1048
1051 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
1052
1053 uint64_t GetTotalBytesRecv() const;
1054 uint64_t GetTotalBytesSent() const;
1055
1057 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1058
1060
1066 std::chrono::seconds now) const;
1067
1068private:
1070 public:
1071 std::shared_ptr<Sock> sock;
1073 NetPermissions::AddFlag(flags, m_permissions);
1074 }
1075 ListenSocket(std::shared_ptr<Sock> sock_,
1076 NetPermissionFlags permissions_)
1077 : sock(sock_), m_permissions(permissions_) {}
1078
1079 private:
1081 };
1082
1083 bool BindListenPort(const CService &bindAddr, bilingual_str &strError,
1084 NetPermissionFlags permissions);
1085 bool Bind(const CService &addr, unsigned int flags,
1086 NetPermissionFlags permissions);
1087 bool InitBinds(const Options &options);
1088
1091 void AddAddrFetch(const std::string &strDest)
1094 void
1095 ThreadOpenConnections(std::vector<std::string> connect,
1096 std::function<void(const CAddress &, ConnectionType)>
1097 mockOpenConnection)
1102 void AcceptConnection(const ListenSocket &hListenSocket);
1103
1112 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock> &&sock,
1113 NetPermissionFlags permission_flags,
1114 const CAddress &addr_bind,
1115 const CAddress &addr);
1116
1117 void DisconnectNodes();
1120 bool InactivityCheck(const CNode &node) const;
1121
1127 Sock::EventsPerSock GenerateWaitSockets(Span<CNode *const> nodes);
1128
1134
1141 void SocketHandlerConnected(const std::vector<CNode *> &nodes,
1142 const Sock::EventsPerSock &events_per_sock)
1144
1149 void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock);
1150
1154
1155 uint64_t CalculateKeyedNetGroup(const CAddress &ad) const;
1156
1157 CNode *FindNode(const CNetAddr &ip);
1158 CNode *FindNode(const CSubNet &subNet);
1159 CNode *FindNode(const std::string &addrName);
1160 CNode *FindNode(const CService &addr);
1161
1166 bool AlreadyConnectedToAddress(const CAddress &addr);
1167
1169 CNode *ConnectNode(CAddress addrConnect, const char *pszDest,
1170 bool fCountFailure, ConnectionType conn_type);
1172 NetPermissionFlags &flags, const CNetAddr &addr,
1173 const std::vector<NetWhitelistPermissions> &ranges) const;
1174
1175 void DeleteNode(CNode *pnode);
1176
1178
1183 std::pair<size_t, bool> SocketSendData(CNode &node) const
1185
1186 void DumpAddresses();
1187
1188 // Network stats
1189 void RecordBytesRecv(uint64_t bytes);
1190 void RecordBytesSent(uint64_t bytes);
1191
1196
1197 // Whether the node should be passed out in ForEach* callbacks
1198 static bool NodeFullyConnected(const CNode *pnode);
1199
1201
1202 // Network usage totals
1204 std::atomic<uint64_t> nTotalBytesRecv{0};
1205 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent){0};
1206
1207 // outbound limit & stats
1208 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent){0};
1209 std::chrono::seconds
1210 nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent){0};
1211 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1212
1213 // P2P timeout in seconds
1214 std::chrono::seconds m_peer_connect_timeout;
1215
1216 // Whitelisted ranges. Any node connecting from these is automatically
1217 // whitelisted (as well as those connecting to whitelisted binds).
1218 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1219 // Whitelisted ranges for outgoing connections.
1220 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1221
1222 unsigned int nSendBufferMaxSize{0};
1223 unsigned int nReceiveFloodSize{0};
1224
1225 std::vector<ListenSocket> vhListenSocket;
1226 std::atomic<bool> fNetworkActive{true};
1229 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1231 std::vector<std::string> m_added_nodes GUARDED_BY(m_added_nodes_mutex);
1233 std::vector<CNode *> m_nodes GUARDED_BY(m_nodes_mutex);
1234 std::list<CNode *> m_nodes_disconnected;
1236 std::atomic<NodeId> nLastNodeId{0};
1237 unsigned int nPrevNodeCount{0};
1238
1246 std::vector<CAddress> m_addrs_response_cache;
1247 std::chrono::microseconds m_cache_entry_expiration{0};
1248 };
1249
1264 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1265
1277 std::atomic<ServiceFlags> nLocalServices;
1278
1279 std::unique_ptr<CSemaphore> semOutbound;
1280 std::unique_ptr<CSemaphore> semAddnode;
1282
1283 // How many full-relay (tx, block, addr) outbound peers we want
1285
1286 // How many block-relay only outbound peers we want
1287 // We do not relay tx or addr messages with these peers
1289
1290 // How many avalanche enabled outbound peers we want
1292
1298 // FIXME m_msgproc is a terrible name
1299 std::vector<NetEventsInterface *> m_msgproc;
1305
1310 std::vector<CAddress> m_anchors;
1311
1313 const uint64_t nSeed0, nSeed1;
1314
1316 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1317
1318 std::condition_variable condMsgProc;
1320 std::atomic<bool> flagInterruptMsgProc{false};
1321
1329
1334 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1335
1342
1348
1354 std::atomic_bool m_start_extra_block_relay_peers{false};
1355
1360 std::vector<CService> m_onion_binds;
1361
1367
1373
1380 public:
1381 explicit NodesSnapshot(const CConnman &connman, bool shuffle) {
1382 {
1383 LOCK(connman.m_nodes_mutex);
1384 m_nodes_copy = connman.m_nodes;
1385 for (auto &node : m_nodes_copy) {
1386 node->AddRef();
1387 }
1388 }
1389 if (shuffle) {
1390 Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(),
1392 }
1393 }
1394
1396 for (auto &node : m_nodes_copy) {
1397 node->Release();
1398 }
1399 }
1400
1401 const std::vector<CNode *> &Nodes() const { return m_nodes_copy; }
1402
1403 private:
1404 std::vector<CNode *> m_nodes_copy;
1405 };
1406
1407 friend struct ::CConnmanTest;
1408 friend struct ConnmanTestMsg;
1409};
1410
1411std::string getSubVersionEB(uint64_t MaxBlockSize);
1412std::string userAgent(const Config &config);
1413
1415void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type,
1416 Span<const uint8_t> data, bool is_incoming);
1417
1421extern std::function<void(const CAddress &addr, const std::string &msg_type,
1422 Span<const uint8_t> data, bool is_incoming)>
1424
1425#endif // BITCOIN_NET_H
int flags
Definition: bitcoin-tx.cpp:542
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Stochastic address manager.
Definition: addrman.h:68
Definition: banman.h:58
A CService with information about it as peer.
Definition: protocol.h:443
Signals for UI communication.
Definition: ui_interface.h:25
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1379
const std::vector< CNode * > & Nodes() const
Definition: net.h:1401
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1381
std::vector< CNode * > m_nodes_copy
Definition: net.h:1404
Definition: net.h:824
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1372
std::condition_variable condMsgProc
Definition: net.h:1318
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1205
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1210
std::thread threadMessageHandler
Definition: net.h:1340
void ForEachNode(const NodeFn &func)
Definition: net.h:929
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:2873
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1033
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
Definition: net.cpp:2889
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1218
CClientUIInterface * m_client_interface
Definition: net.h:1297
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2128
void ForEachNode(const NodeFn &func) const
Definition: net.h:938
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3084
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1088
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:425
void DeleteNode(CNode *pnode)
Definition: net.cpp:2653
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2745
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:907
bool GetNetworkActive() const
Definition: net.h:916
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:392
int m_max_outbound
Definition: net.h:1295
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1590
void Stop()
Definition: net.h:910
int m_max_outbound_block_relay
Definition: net.h:1288
std::thread threadI2PAcceptIncoming
Definition: net.h:1341
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1594
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1320
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2047
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2574
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1428
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:1246
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:1300
NodeId GetNewNodeId()
Definition: net.cpp:2375
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1328
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1280
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2438
std::atomic< NodeId > nLastNodeId
Definition: net.h:1236
void RecordBytesSent(uint64_t bytes)
Definition: net.cpp:2849
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int GetExtraBlockRelayCount() const
Definition: net.cpp:1622
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1420
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1304
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:2912
std::thread threadDNSAddressSeed
Definition: net.h:1336
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition: net.h:1277
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2179
const uint64_t nSeed1
Definition: net.h:1313
void StartExtraBlockRelayPeers()
Definition: net.h:974
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1310
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2869
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1366
friend struct ConnmanTestMsg
Definition: net.h:1408
unsigned int nPrevNodeCount
Definition: net.h:1237
void NotifyNumConnectionsChanged()
Definition: net.cpp:1187
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:2932
bool DisconnectNode(const std::string &node)
Definition: net.cpp:2800
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1214
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:1347
bool InitBinds(const Options &options)
Definition: net.cpp:2401
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:133
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1208
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1225
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:1978
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3096
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2864
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1279
RecursiveMutex cs_totalBytesSent
Definition: net.h:1203
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2379
std::thread threadOpenConnections
Definition: net.h:1339
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2757
Mutex m_addr_fetches_mutex
Definition: net.h:1230
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1206
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:352
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2775
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:1990
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1313
unsigned int nReceiveFloodSize
Definition: net.h:1223
int GetExtraFullOutboundCount() const
Definition: net.cpp:1606
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2923
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:830
RecursiveMutex m_nodes_mutex
Definition: net.h:1235
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3034
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:1572
int nMaxConnections
Definition: net.h:1281
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
Definition: net.cpp:2364
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:2667
std::function< void(CNode *)> NodeFn
Definition: net.h:928
void SetNetworkActive(bool active)
Definition: net.cpp:2350
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1234
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2079
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:1030
AddrMan & addrman
Definition: net.h:1228
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:1272
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3100
Mutex mutexMsgProc
Definition: net.h:1319
bool fAddressesInitialized
Definition: net.h:1227
~CConnman()
Definition: net.cpp:2661
void StopThreads()
Definition: net.cpp:2597
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2733
std::thread threadOpenAddedConnections
Definition: net.h:1338
Mutex m_added_nodes_mutex
Definition: net.h:1232
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:582
const Config * config
Definition: net.h:1200
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.h:858
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:397
int m_max_outbound_full_relay
Definition: net.h:1284
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int nMaxAddnode
Definition: net.h:1293
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2845
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:1201
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:1412
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:987
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3038
void StopNodes()
Definition: net.cpp:2618
bool GetUseAddrmanOutgoing() const
Definition: net.h:917
unsigned int nSendBufferMaxSize
Definition: net.h:1222
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1334
bool m_use_addrman_outgoing
Definition: net.h:1296
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1220
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:1264
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1204
std::atomic< bool > fNetworkActive
Definition: net.h:1226
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1354
void DisconnectNodes()
Definition: net.cpp:1137
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:1399
void DumpAddresses()
Definition: net.cpp:1563
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:1360
int nMaxFeeler
Definition: net.h:1294
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:1299
std::thread threadSocketHandler
Definition: net.h:1337
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2927
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:1636
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:958
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2217
int m_max_avalanche_outbound
Definition: net.h:1291
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:72
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:47
Network address.
Definition: netaddress.h:121
Transport protocol agnostic message container.
Definition: net.h:256
CNetMessage(CDataStream &&recv_in)
Definition: net.h:271
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:261
CDataStream m_recv
received message data
Definition: net.h:259
void SetVersion(int nVersionIn)
Definition: net.h:281
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
bool m_valid_checksum
Definition: net.h:264
bool m_valid_header
Definition: net.h:263
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
bool m_valid_netmagic
Definition: net.h:262
Information about a peer.
Definition: net.h:395
Mutex cs_avalanche_pubkey
Definition: net.h:587
const CAddress addrBind
Definition: net.h:434
bool IsFeelerConn() const
Definition: net.h:518
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:429
bool ExpectServicesFromConn() const
Definition: net.h:532
std::atomic< int > nVersion
Definition: net.h:439
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition: net.h:570
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:424
std::atomic< double > availabilityScore
The last computed score.
Definition: net.h:764
bool IsInboundConn() const
Definition: net.h:524
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:452
std::atomic_bool fPauseRecv
Definition: net.h:463
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:491
NodeId GetId() const
Definition: net.h:687
bool IsManualConn() const
Definition: net.h:512
std::atomic< int64_t > nTimeOffset
Definition: net.h:430
const std::string m_addr_name
Definition: net.h:435
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition: net.h:733
void SetCommonVersion(int greatest_common_version)
Definition: net.h:709
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:562
std::list< CNetMessage > vRecvMsg
Definition: net.h:745
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition: net.h:576
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:564
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:682
std::atomic_bool fSuccessfullyConnected
Definition: net.h:455
const bool m_prefer_evict
Definition: net.h:451
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:750
bool IsAddrFetchConn() const
Definition: net.h:520
uint64_t GetLocalNonce() const
Definition: net.h:689
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:2965
const CAddress addr
Definition: net.h:432
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
Definition: net.cpp:609
CSemaphoreGrant grantOutbound
Definition: net.h:459
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:462
std::atomic< int > nRefCount
Definition: net.h:460
std::atomic< int > m_greatest_common_version
Definition: net.h:741
bool IsBlockOnlyConn() const
Definition: net.h:514
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition: net.cpp:3001
int GetCommonVersion() const
Definition: net.h:713
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:507
uint64_t nRemoteHostNonce
Definition: net.h:441
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:448
const std::unique_ptr< const TransportSerializer > m_serializer
Definition: net.h:399
Mutex cs_vSend
Definition: net.h:420
CNode * AddRef()
Definition: net.h:720
std::atomic_bool fPauseSend
Definition: net.h:464
std::chrono::seconds m_nextGetAvaAddr
Definition: net.h:617
uint64_t nRemoteExtraEntropy
Definition: net.h:443
int GetRefCount() const
Definition: net.h:692
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:3018
uint64_t GetLocalExtraEntropy() const
Definition: net.h:690
SteadyMilliseconds m_last_poll
Definition: net.h:633
double getAvailabilityScore() const
Definition: net.cpp:2959
Mutex m_msg_process_queue_mutex
Definition: net.h:747
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:417
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition: net.h:582
CService addrLocal GUARDED_BY(m_addr_local_mutex)
const ConnectionType m_conn_type
Definition: net.h:466
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:621
const size_t m_recv_flood_size
Definition: net.h:743
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition: net.cpp:625
const uint64_t nLocalHostNonce
Definition: net.h:739
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:661
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
Definition: net.cpp:2944
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:415
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
std::atomic< std::chrono::seconds > m_avalanche_last_message_fault
Definition: net.h:620
const uint64_t nLocalExtraEntropy
Definition: net.h:740
const NetPermissionFlags m_permission_flags
Definition: net.h:401
bool ReceiveMsgBytes(const Config &config, Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:673
void invsPolled(uint32_t count)
The node was polled for count invs.
Definition: net.cpp:2936
Mutex m_addr_local_mutex
Definition: net.h:753
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
Definition: net.h:438
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:667
const NodeId id
Definition: net.h:738
std::atomic< int > m_avalanche_message_fault_counter
How much faulty messages did this node accumulate.
Definition: net.h:625
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:486
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:658
Mutex cs_vRecv
Definition: net.h:422
std::atomic< bool > m_avalanche_enabled
Definition: net.h:585
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:642
const std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:398
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:418
std::atomic< uint64_t > invCounters
The inventories polled and voted counters since last score computation, stored as a pair of uint32_t ...
Definition: net.h:761
std::deque< std::vector< uint8_t > > vSendMsg GUARDED_BY(cs_vSend)
Mutex m_sock_mutex
Definition: net.h:421
std::atomic_bool fDisconnect
Definition: net.h:458
std::atomic< std::chrono::seconds > m_last_recv
Definition: net.h:427
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:631
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:650
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
Definition: net.cpp:603
void invsVoted(uint32_t count)
The node voted for count invs.
Definition: net.cpp:2940
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
Definition: net.cpp:573
std::atomic< std::chrono::seconds > m_last_send
Definition: net.h:426
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
bool IsAvalancheOutboundConnection() const
Definition: net.h:528
void Release()
Definition: net.h:725
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
Definition: net.h:449
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:773
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:778
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:289
virtual ~TransportDeserializer()
Definition: net.h:300
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:372
virtual ~TransportSerializer()
Definition: net.h:379
virtual void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const =0
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
Definition: net.cpp:771
CDataStream vRecv
Definition: net.h:315
CMessageHeader hdr
Definition: net.h:313
const uint256 & GetMessageHash() const
Definition: net.cpp:762
uint32_t nDataPos
Definition: net.h:317
uint32_t nHdrPos
Definition: net.h:316
int Read(const Config &config, Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:355
void SetVersion(int nVersionIn) override
Definition: net.h:351
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:745
bool Complete() const override
Definition: net.h:343
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
Definition: net.cpp:712
CHash256 hasher
Definition: net.h:305
V1TransportDeserializer(const CMessageHeader::MessageMagic &pchMessageStartIn, int nTypeIn, int nVersionIn)
Definition: net.h:335
CDataStream hdrbuf
Definition: net.h:311
uint256 data_hash
Definition: net.h:306
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) const override
Definition: net.cpp:814
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:291
@ NET
Definition: logging.h:43
Definition: init.h:31
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:238
const std::vector< std::string > CONNECTION_TYPE_DOC
Definition: net.h:137
uint16_t GetListenPort()
Definition: net.cpp:138
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:92
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:347
CService GetLocalAddress(const CNetAddr &addrPeer)
Definition: net.cpp:222
void RemoveLocal(const CService &addr)
Definition: net.cpp:312
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:68
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:62
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:75
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:279
bool fDiscover
Definition: net.cpp:126
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:106
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:100
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:96
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:102
bool fListen
Definition: net.cpp:127
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:94
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:66
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:105
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:82
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:244
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:113
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:318
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:104
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:3188
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:3122
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:128
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:84
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:86
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:174
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:64
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:98
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:3156
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:206
static const bool DEFAULT_DNSSEED
Definition: net.h:103
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:73
@ LOCAL_NONE
Definition: net.h:157
@ LOCAL_MAPPED
Definition: net.h:163
@ LOCAL_MANUAL
Definition: net.h:165
@ LOCAL_MAX
Definition: net.h:167
@ LOCAL_BIND
Definition: net.h:161
@ LOCAL_IF
Definition: net.h:159
std::string userAgent(const Config &config)
Definition: net.cpp:3136
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:77
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:2297
bool IsReachable(enum Network net)
Definition: net.cpp:326
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:336
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
ServiceFlags
nServices flags.
Definition: protocol.h:336
@ NODE_NONE
Definition: protocol.h:339
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:112
CService resolvedAddress
Definition: net.h:110
bool fConnected
Definition: net.h:111
std::string strAddedNode
Definition: net.h:109
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1245
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1247
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1246
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1072
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1075
NetPermissionFlags m_permissions
Definition: net.h:1080
std::shared_ptr< Sock > sock
Definition: net.h:1071
int m_max_outbound_block_relay
Definition: net.h:830
unsigned int nReceiveFloodSize
Definition: net.h:838
int m_max_outbound_full_relay
Definition: net.h:829
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:844
uint64_t nMaxOutboundLimit
Definition: net.h:839
CClientUIInterface * uiInterface
Definition: net.h:834
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:842
int m_max_avalanche_outbound
Definition: net.h:831
std::vector< CService > onion_binds
Definition: net.h:846
int nMaxFeeler
Definition: net.h:833
std::vector< std::string > m_specified_outgoing
Definition: net.h:851
bool whitelist_relay
Definition: net.h:855
int nMaxConnections
Definition: net.h:828
ServiceFlags nLocalServices
Definition: net.h:827
std::vector< std::string > m_added_nodes
Definition: net.h:852
int64_t m_peer_connect_timeout
Definition: net.h:840
std::vector< CService > vBinds
Definition: net.h:845
unsigned int nSendBufferMaxSize
Definition: net.h:837
bool m_i2p_accept_incoming
Definition: net.h:853
std::vector< std::string > vSeedNodes
Definition: net.h:841
BanMan * m_banman
Definition: net.h:836
bool m_use_addrman_outgoing
Definition: net.h:850
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:835
bool whitelist_forcerelay
Definition: net.h:854
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:849
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:843
int nMaxAddnode
Definition: net.h:832
NetPermissionFlags permission_flags
Definition: net.h:389
bool prefer_evict
Definition: net.h:390
size_t recv_flood_size
Definition: net.h:391
POD that contains various stats about a node.
Definition: net.h:213
std::string addrLocal
Definition: net.h:239
CAddress addrBind
Definition: net.h:243
uint64_t nRecvBytes
Definition: net.h:233
std::chrono::microseconds m_last_ping_time
Definition: net.h:236
uint32_t m_mapped_as
Definition: net.h:246
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:234
bool fInbound
Definition: net.h:225
uint64_t nSendBytes
Definition: net.h:231
std::chrono::seconds m_last_recv
Definition: net.h:216
std::optional< double > m_availabilityScore
Definition: net.h:248
std::chrono::seconds m_last_proof_time
Definition: net.h:218
ConnectionType m_conn_type
Definition: net.h:247
std::chrono::seconds m_last_send
Definition: net.h:215
std::chrono::seconds m_last_tx_time
Definition: net.h:217
CAddress addr
Definition: net.h:241
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:232
std::chrono::microseconds m_min_ping_time
Definition: net.h:237
int64_t nTimeOffset
Definition: net.h:221
std::chrono::seconds m_connected
Definition: net.h:220
bool m_bip152_highbandwidth_from
Definition: net.h:229
bool m_bip152_highbandwidth_to
Definition: net.h:227
std::string m_addr_name
Definition: net.h:222
int nVersion
Definition: net.h:223
std::chrono::seconds m_last_block_time
Definition: net.h:219
Network m_network
Definition: net.h:245
NodeId nodeid
Definition: net.h:214
std::string cleanSubVer
Definition: net.h:224
int m_starting_height
Definition: net.h:230
NetPermissionFlags m_permission_flags
Definition: net.h:235
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:126
std::vector< uint8_t > data
Definition: net.h:133
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:134
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
uint16_t nPort
Definition: net.h:197
int nScore
Definition: net.h:196
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