Bitcoin Core 22.99.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_NET_H
7#define BITCOIN_NET_H
8
9#include <addrman.h>
10#include <chainparams.h>
11#include <common/bloom.h>
12#include <compat.h>
13#include <consensus/amount.h>
14#include <crypto/siphash.h>
15#include <hash.h>
16#include <i2p.h>
17#include <net_permissions.h>
18#include <netaddress.h>
19#include <netbase.h>
20#include <policy/feerate.h>
21#include <protocol.h>
22#include <random.h>
23#include <span.h>
24#include <streams.h>
25#include <sync.h>
26#include <threadinterrupt.h>
27#include <uint256.h>
28#include <util/check.h>
29
30#include <atomic>
31#include <condition_variable>
32#include <cstdint>
33#include <deque>
34#include <map>
35#include <memory>
36#include <optional>
37#include <thread>
38#include <vector>
39
40class CScheduler;
41class CNode;
42class BanMan;
43struct bilingual_str;
44
46static const bool DEFAULT_WHITELISTRELAY = true;
48static const bool DEFAULT_WHITELISTFORCERELAY = false;
49
51static const int TIMEOUT_INTERVAL = 20 * 60;
53static constexpr auto FEELER_INTERVAL = 2min;
55static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
57static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
59static const unsigned int MAX_SUBVERSION_LENGTH = 256;
63static const int MAX_ADDNODE_CONNECTIONS = 8;
67static const int MAX_FEELER_CONNECTIONS = 1;
69static const bool DEFAULT_LISTEN = true;
71static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
73static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
75static const bool DEFAULT_BLOCKSONLY = false;
77static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
79static const int NUM_FDS_MESSAGE_CAPTURE = 1;
80
81static constexpr bool DEFAULT_FORCEDNSSEED{false};
82static constexpr bool DEFAULT_DNSSEED{true};
83static constexpr bool DEFAULT_FIXEDSEEDS{true};
84static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
85static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
86
87typedef int64_t NodeId;
88
90{
91 std::string strAddedNode;
95};
96
97class CNodeStats;
99
101{
102 CSerializedNetMsg() = default;
105 // No copying, only moves.
108
109 std::vector<unsigned char> data;
110 std::string m_type;
111};
112
120enum class ConnectionType {
126 INBOUND,
127
135
136
143 MANUAL,
144
160 FEELER,
161
172
180};
181
183std::string ConnectionTypeAsString(ConnectionType conn_type);
184void Discover();
185uint16_t GetListenPort();
186
187enum
188{
189 LOCAL_NONE, // unknown
190 LOCAL_IF, // address a local interface listens on
191 LOCAL_BIND, // address explicit bound to
192 LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
193 LOCAL_MANUAL, // address explicitly specified (-externalip=)
194
197
198bool IsPeerAddrLocalGood(CNode *pnode);
200std::optional<CAddress> GetLocalAddrForPeer(CNode *pnode);
201
206void SetReachable(enum Network net, bool reachable);
208bool IsReachable(enum Network net);
210bool IsReachable(const CNetAddr& addr);
211
212bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
213bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
214void RemoveLocal(const CService& addr);
215bool SeenLocal(const CService& addr);
216bool IsLocal(const CService& addr);
217bool GetLocal(CService &addr, const CNetAddr *paddrPeer = nullptr);
218CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
219
220
221extern bool fDiscover;
222extern bool fListen;
223
225extern std::string strSubVersion;
226
229 uint16_t nPort;
230};
231
233extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(cs_mapLocalHost);
234
235extern const std::string NET_MESSAGE_COMMAND_OTHER;
236typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
237
239{
240public:
244 int64_t nLastSend;
245 int64_t nLastRecv;
246 int64_t nLastTXTime;
249 int64_t nTimeOffset;
250 std::string m_addr_name;
252 std::string cleanSubVer;
257 uint64_t nSendBytes;
259 uint64_t nRecvBytes;
262 std::chrono::microseconds m_last_ping_time;
263 std::chrono::microseconds m_min_ping_time;
265 // Our address, as reported by the peer
266 std::string addrLocal;
267 // Address of this peer
269 // Bind address of our side of the connection
271 // Network the peer connected through
273 uint32_t m_mapped_as;
275};
276
277
283public:
285 std::chrono::microseconds m_time{0};
286 uint32_t m_message_size{0};
287 uint32_t m_raw_message_size{0};
288 std::string m_command;
289
290 CNetMessage(CDataStream&& recv_in) : m_recv(std::move(recv_in)) {}
291
292 void SetVersion(int nVersionIn)
293 {
294 m_recv.SetVersion(nVersionIn);
295 }
296};
297
303public:
304 // returns true if the current deserialization is complete
305 virtual bool Complete() const = 0;
306 // set the serialization context version
307 virtual void SetVersion(int version) = 0;
309 virtual int Read(Span<const uint8_t>& msg_bytes) = 0;
310 // decomposes a message from the context
311 virtual CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) = 0;
313};
314
316{
317private:
319 const NodeId m_node_id; // Only for logging
322 bool in_data; // parsing header (false) or data (true)
323 CDataStream hdrbuf; // partially received header
324 CMessageHeader hdr; // complete header
325 CDataStream vRecv; // received message data
326 unsigned int nHdrPos;
327 unsigned int nDataPos;
328
329 const uint256& GetMessageHash() const;
330 int readHeader(Span<const uint8_t> msg_bytes);
331 int readData(Span<const uint8_t> msg_bytes);
332
333 void Reset() {
334 vRecv.clear();
335 hdrbuf.clear();
336 hdrbuf.resize(24);
337 in_data = false;
338 nHdrPos = 0;
339 nDataPos = 0;
341 hasher.Reset();
342 }
343
344public:
345 V1TransportDeserializer(const CChainParams& chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
346 : m_chain_params(chain_params),
347 m_node_id(node_id),
348 hdrbuf(nTypeIn, nVersionIn),
349 vRecv(nTypeIn, nVersionIn)
350 {
351 Reset();
352 }
353
354 bool Complete() const override
355 {
356 if (!in_data)
357 return false;
358 return (hdr.nMessageSize == nDataPos);
359 }
360 void SetVersion(int nVersionIn) override
361 {
362 hdrbuf.SetVersion(nVersionIn);
363 vRecv.SetVersion(nVersionIn);
364 }
365 int Read(Span<const uint8_t>& msg_bytes) override
366 {
367 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
368 if (ret < 0) {
369 Reset();
370 } else {
371 msg_bytes = msg_bytes.subspan(ret);
372 }
373 return ret;
374 }
375 CNetMessage GetMessage(std::chrono::microseconds time, bool& reject_message) override;
376};
377
381public:
382 // prepare message for transport (header construction, error-correction computation, payload encryption, etc.)
383 virtual void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) = 0;
385};
386
388public:
389 void prepareForTransport(CSerializedNetMsg& msg, std::vector<unsigned char>& header) override;
390};
391
393class CNode
394{
395 friend class CConnman;
396 friend struct ConnmanTestMsg;
397
398public:
399 std::unique_ptr<TransportDeserializer> m_deserializer;
400 std::unique_ptr<TransportSerializer> m_serializer;
401
403 std::atomic<ServiceFlags> nServices{NODE_NONE};
406 size_t nSendSize GUARDED_BY(cs_vSend){0};
408 size_t nSendOffset GUARDED_BY(cs_vSend){0};
409 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
410 std::deque<std::vector<unsigned char>> vSendMsg GUARDED_BY(cs_vSend);
414
416 std::list<CNetMessage> vProcessMsg GUARDED_BY(cs_vProcessMsg);
418
420
421 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
422
423 std::atomic<int64_t> nLastSend{0};
424 std::atomic<int64_t> nLastRecv{0};
426 const int64_t nTimeConnected;
427 std::atomic<int64_t> nTimeOffset{0};
428 // Address of this peer
430 // Bind address of our side of the connection
432 const std::string m_addr_name;
434 const bool m_inbound_onion;
435 std::atomic<int> nVersion{0};
441 std::string cleanSubVer GUARDED_BY(cs_SubVer){};
442 bool m_prefer_evict{false}; // This peer is preferred for eviction.
443 bool HasPermission(NetPermissionFlags permission) const {
444 return NetPermissions::HasFlag(m_permissionFlags, permission);
445 }
446 bool fClient{false}; // set by version message
447 bool m_limited_node{false}; //after BIP159, set by version message
449 std::atomic_bool fSuccessfullyConnected{false};
450 // Setting fDisconnect to true will cause the node to be disconnected the
451 // next time DisconnectNodes() runs
452 std::atomic_bool fDisconnect{false};
454 std::atomic<int> nRefCount{0};
455
456 const uint64_t nKeyedNetGroup;
457 std::atomic_bool fPauseRecv{false};
458 std::atomic_bool fPauseSend{false};
459
461 switch (m_conn_type) {
464 return true;
469 return false;
470 } // no default case, so the compiler can warn about missing cases
471
472 assert(false);
473 }
474
475 bool IsFullOutboundConn() const {
477 }
478
479 bool IsManualConn() const {
481 }
482
483 bool IsBlockOnlyConn() const {
485 }
486
487 bool IsFeelerConn() const {
489 }
490
491 bool IsAddrFetchConn() const {
493 }
494
495 bool IsInboundConn() const {
497 }
498
500 switch (m_conn_type) {
504 return false;
508 return true;
509 } // no default case, so the compiler can warn about missing cases
510
511 assert(false);
512 }
513
525
526 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
527 std::atomic<bool> m_bip152_highbandwidth_to{false};
528 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
529 std::atomic<bool> m_bip152_highbandwidth_from{false};
530
531 struct TxRelay {
533 // We use fRelayTxes for two purposes -
534 // a) it allows us to not relay tx invs before receiving the peer's version message
535 // b) the peer may tell us in its version message that we should not relay tx invs
536 // unless it loads a bloom filter.
537 bool fRelayTxes GUARDED_BY(cs_filter){false};
538 std::unique_ptr<CBloomFilter> pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter){nullptr};
539
541 CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory){50000, 0.000001};
542 // Set of transaction ids we still have to announce.
543 // They are sorted by the mempool before relay, so the order is not important.
544 std::set<uint256> setInventoryTxToSend;
545 // Used for BIP35 mempool sending
546 bool fSendMempool GUARDED_BY(cs_tx_inventory){false};
547 // Last time a "MEMPOOL" request was serviced.
548 std::atomic<std::chrono::seconds> m_last_mempool_req{0s};
549 std::chrono::microseconds nNextInvSend{0};
550
552 std::atomic<CAmount> minFeeFilter{0};
554 std::chrono::microseconds m_next_send_feefilter{0};
555 };
556
557 // m_tx_relay == nullptr if we're not relaying transactions with this peer
558 std::unique_ptr<TxRelay> m_tx_relay;
559
565 std::atomic<int64_t> nLastBlockTime{0};
566
571 std::atomic<int64_t> nLastTXTime{0};
572
574 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
575
578 std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
579
580 CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress& addrBindIn, const std::string& addrNameIn, ConnectionType conn_type_in, bool inbound_onion);
581 ~CNode();
582 CNode(const CNode&) = delete;
583 CNode& operator=(const CNode&) = delete;
584
585 NodeId GetId() const {
586 return id;
587 }
588
589 uint64_t GetLocalNonce() const {
590 return nLocalHostNonce;
591 }
592
593 int GetRefCount() const
594 {
595 assert(nRefCount >= 0);
596 return nRefCount;
597 }
598
608 bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete);
609
610 void SetCommonVersion(int greatest_common_version)
611 {
613 m_greatest_common_version = greatest_common_version;
614 }
616 {
618 }
619
620 CService GetAddrLocal() const;
622 void SetAddrLocal(const CService& addrLocalIn);
623
625 {
626 nRefCount++;
627 return this;
628 }
629
630 void Release()
631 {
632 nRefCount--;
633 }
634
635 void AddKnownTx(const uint256& hash)
636 {
637 if (m_tx_relay != nullptr) {
638 LOCK(m_tx_relay->cs_tx_inventory);
639 m_tx_relay->filterInventoryKnown.insert(hash);
640 }
641 }
642
643 void PushTxInventory(const uint256& hash)
644 {
645 if (m_tx_relay == nullptr) return;
646 LOCK(m_tx_relay->cs_tx_inventory);
647 if (!m_tx_relay->filterInventoryKnown.contains(hash)) {
648 m_tx_relay->setInventoryTxToSend.insert(hash);
649 }
650 }
651
653
654 void CopyStats(CNodeStats& stats);
655
657 {
658 return nLocalServices;
659 }
660
662
664 void PongReceived(std::chrono::microseconds ping_time) {
665 m_last_ping_time = ping_time;
666 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
667 }
668
669private:
670 const NodeId id;
671 const uint64_t nLocalHostNonce;
674
691
692 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
693
694 // Our address, as reported by the peer
697
698 mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend);
699 mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv);
700};
701
706{
707public:
709 virtual void InitializeNode(CNode* pnode) = 0;
710
712 virtual void FinalizeNode(const CNode& node) = 0;
713
721 virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) = 0;
722
729 virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode->cs_sendProcessing) = 0;
730
731
732protected:
738};
739
741{
742public:
743
744 struct Options
745 {
750 int nMaxAddnode = 0;
751 int nMaxFeeler = 0;
754 BanMan* m_banman = nullptr;
755 unsigned int nSendBufferMaxSize = 0;
756 unsigned int nReceiveFloodSize = 0;
757 uint64_t nMaxOutboundLimit = 0;
759 std::vector<std::string> vSeedNodes;
760 std::vector<NetWhitelistPermissions> vWhitelistedRange;
761 std::vector<NetWhitebindPermissions> vWhiteBinds;
762 std::vector<CService> vBinds;
763 std::vector<CService> onion_binds;
768 std::vector<std::string> m_specified_outgoing;
769 std::vector<std::string> m_added_nodes;
771 };
772
773 void Init(const Options& connOptions) {
774 nLocalServices = connOptions.nLocalServices;
775 nMaxConnections = connOptions.nMaxConnections;
776 m_max_outbound_full_relay = std::min(connOptions.m_max_outbound_full_relay, connOptions.nMaxConnections);
779 nMaxAddnode = connOptions.nMaxAddnode;
780 nMaxFeeler = connOptions.nMaxFeeler;
782 m_client_interface = connOptions.uiInterface;
783 m_banman = connOptions.m_banman;
784 m_msgproc = connOptions.m_msgproc;
788 {
790 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
791 }
793 {
795 vAddedNodes = connOptions.m_added_nodes;
796 }
797 m_onion_binds = connOptions.onion_binds;
798 }
799
800 CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, bool network_active = true);
801 ~CConnman();
802 bool Start(CScheduler& scheduler, const Options& options);
803
804 void StopThreads();
805 void StopNodes();
806 void Stop()
807 {
808 StopThreads();
809 StopNodes();
810 };
811
812 void Interrupt();
813 bool GetNetworkActive() const { return fNetworkActive; };
815 void SetNetworkActive(bool active);
816 void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound, const char* strDest, ConnectionType conn_type);
817 bool CheckIncomingNonce(uint64_t nonce);
818
819 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
820
821 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
822
823 using NodeFn = std::function<void(CNode*)>;
824 void ForEachNode(const NodeFn& func)
825 {
827 for (auto&& node : vNodes) {
829 func(node);
830 }
831 };
832
833 void ForEachNode(const NodeFn& func) const
834 {
836 for (auto&& node : vNodes) {
838 func(node);
839 }
840 };
841
842 // Addrman functions
850 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network) const;
857 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
858
859 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
860 // a peer that is better than all our current peers.
861 void SetTryNewOutboundPeer(bool flag);
862 bool GetTryNewOutboundPeer() const;
863
865 LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
867 }
868
869 // Return the number of outbound peers we have in excess of our target (eg,
870 // if we previously called SetTryNewOutboundPeer(true), and have since set
871 // to false, we may have extra peers that we wish to disconnect). This may
872 // return a value less than (num_outbound_connections - num_outbound_slots)
873 // in cases where some outbound connections are not yet fully connected, or
874 // not yet fully disconnected.
875 int GetExtraFullOutboundCount() const;
876 // Count the number of block-relay-only peers we have over our limit.
877 int GetExtraBlockRelayCount() const;
878
879 bool AddNode(const std::string& node);
880 bool RemoveAddedNode(const std::string& node);
881 std::vector<AddedNodeInfo> GetAddedNodeInfo() const;
882
895 bool AddConnection(const std::string& address, ConnectionType conn_type);
896
897 size_t GetNodeCount(ConnectionDirection) const;
898 void GetNodeStats(std::vector<CNodeStats>& vstats) const;
899 bool DisconnectNode(const std::string& node);
900 bool DisconnectNode(const CSubNet& subnet);
901 bool DisconnectNode(const CNetAddr& addr);
902 bool DisconnectNode(NodeId id);
903
911
912 uint64_t GetMaxOutboundTarget() const;
913 std::chrono::seconds GetMaxOutboundTimeframe() const;
914
918 bool OutboundTargetReached(bool historicalBlockServingLimit) const;
919
922 uint64_t GetOutboundTargetBytesLeft() const;
923
926 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const;
927
928 uint64_t GetTotalBytesRecv() const;
929 uint64_t GetTotalBytesSent() const;
930
932 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
933
934 unsigned int GetReceiveFloodSize() const;
935
936 void WakeMessageHandler();
937
942 std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval);
943
945 bool ShouldRunInactivityChecks(const CNode& node, int64_t secs_now) const;
946
947private:
949 public:
952 ListenSocket(SOCKET socket_, NetPermissionFlags permissions_) : socket(socket_), m_permissions(permissions_) {}
953 private:
955 };
956
957 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
958 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
959 bool InitBinds(const Options& options);
960
962 void AddAddrFetch(const std::string& strDest);
963 void ProcessAddrFetch();
964 void ThreadOpenConnections(std::vector<std::string> connect);
967 void AcceptConnection(const ListenSocket& hListenSocket);
968
978 NetPermissionFlags permissionFlags,
979 const CAddress& addr_bind,
980 const CAddress& addr);
981
982 void DisconnectNodes();
985 bool InactivityCheck(const CNode& node) const;
986 bool GenerateSelectSet(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
987 void SocketEvents(std::set<SOCKET> &recv_set, std::set<SOCKET> &send_set, std::set<SOCKET> &error_set);
988 void SocketHandler();
989 void ThreadSocketHandler();
991
992 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
993
994 CNode* FindNode(const CNetAddr& ip);
995 CNode* FindNode(const CSubNet& subNet);
996 CNode* FindNode(const std::string& addrName);
997 CNode* FindNode(const CService& addr);
998
1003 bool AlreadyConnectedToAddress(const CAddress& addr);
1004
1006 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type);
1008
1009 void DeleteNode(CNode* pnode);
1010
1012
1013 size_t SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1014 void DumpAddresses();
1015
1016 // Network stats
1017 void RecordBytesRecv(uint64_t bytes);
1018 void RecordBytesSent(uint64_t bytes);
1019
1023 std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1024
1025 // Whether the node should be passed out in ForEach* callbacks
1026 static bool NodeFullyConnected(const CNode* pnode);
1027
1028 // Network usage totals
1031 uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv) {0};
1032 uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent) {0};
1033
1034 // outbound limit & stats
1035 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent) {0};
1036 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent) {0};
1037 uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent);
1038
1039 // P2P timeout in seconds
1041
1042 // Whitelisted ranges. Any node connecting from these is automatically
1043 // whitelisted (as well as those connecting to whitelisted binds).
1044 std::vector<NetWhitelistPermissions> vWhitelistedRange;
1045
1046 unsigned int nSendBufferMaxSize{0};
1047 unsigned int nReceiveFloodSize{0};
1048
1049 std::vector<ListenSocket> vhListenSocket;
1050 std::atomic<bool> fNetworkActive{true};
1053 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1055 std::vector<std::string> vAddedNodes GUARDED_BY(cs_vAddedNodes);
1057 std::vector<CNode*> vNodes GUARDED_BY(cs_vNodes);
1058 std::list<CNode*> vNodesDisconnected;
1060 std::atomic<NodeId> nLastNodeId{0};
1061 unsigned int nPrevNodeCount{0};
1062
1070 std::vector<CAddress> m_addrs_response_cache;
1071 std::chrono::microseconds m_cache_entry_expiration{0};
1072 };
1073
1088 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1089
1103
1104 std::unique_ptr<CSemaphore> semOutbound;
1105 std::unique_ptr<CSemaphore> semAddnode;
1107
1108 // How many full-relay (tx, block, addr) outbound peers we want
1110
1111 // How many block-relay only outbound peers we want
1112 // We do not relay tx or addr messages with these peers
1114
1123
1128 std::vector<CAddress> m_anchors;
1129
1131 const uint64_t nSeed0, nSeed1;
1132
1134 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1135
1136 std::condition_variable condMsgProc;
1138 std::atomic<bool> flagInterruptMsgProc{false};
1139
1147
1152 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1153
1160
1165
1170 std::atomic_bool m_start_extra_block_relay_peers{false};
1171
1172 std::atomic<std::chrono::microseconds> m_next_send_inv_to_incoming{0us};
1173
1178 std::vector<CService> m_onion_binds;
1179
1180 friend struct CConnmanTest;
1181 friend struct ConnmanTestMsg;
1182};
1183
1185std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval);
1186
1188void CaptureMessage(const CAddress& addr, const std::string& msg_type, const Span<const unsigned char>& data, bool is_incoming);
1189
1191{
1194 std::chrono::microseconds m_min_ping_time;
1204};
1205
1213[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1214
1236void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
1237
1238#endif // BITCOIN_NET_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int flags
Definition: bitcoin-tx.cpp:525
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
Stochastic address manager.
Definition: addrman.h:55
Definition: banman.h:59
A CService with information about it as peer.
Definition: protocol.h:359
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
Signals for UI communication.
Definition: ui_interface.h:25
Definition: net.h:741
void CreateNodeFromAcceptedSocket(SOCKET hSocket, NetPermissionFlags permissionFlags, 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 vNodes member...
Definition: net.cpp:1126
std::condition_variable condMsgProc
Definition: net.h:1136
uint64_t nTotalBytesSent GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1032
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1036
std::thread threadMessageHandler
Definition: net.h:1158
void ForEachNode(const NodeFn &func)
Definition: net.h:824
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition: net.cpp:2918
void ThreadOpenAddedConnections()
Definition: net.cpp:2182
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:2932
CClientUIInterface * m_client_interface
Definition: net.h:1119
size_t SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
Definition: net.cpp:791
void SocketHandler()
Definition: net.cpp:1520
void ForEachNode(const NodeFn &func) const
Definition: net.h:833
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:3063
std::vector< AddedNodeInfo > GetAddedNodeInfo() const
Definition: net.cpp:2128
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
Definition: net.cpp:1221
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
Definition: net.cpp:402
void DeleteNode(CNode *pnode)
Definition: net.cpp:2725
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1054
bool GetNetworkActive() const
Definition: net.h:813
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:371
int m_max_outbound
Definition: net.h:1117
void AddAddrFetch(const std::string &strDest)
Definition: net.cpp:119
RecursiveMutex cs_vNodes
Definition: net.h:1059
ServiceFlags nLocalServices
Services this instance offers.
Definition: net.h:1102
bool GetTryNewOutboundPeer() const
Definition: net.cpp:1796
void Stop()
Definition: net.h:806
int m_max_outbound_block_relay
Definition: net.h:1113
void ProcessAddrFetch()
Definition: net.cpp:1779
std::thread threadI2PAcceptIncoming
Definition: net.h:1159
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1801
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1138
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2978
std::list< CNode * > vNodesDisconnected
Definition: net.h:1058
void SocketEvents(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1445
NodeId GetNewNodeId()
Definition: net.cpp:2478
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition: net.h:1146
std::unique_ptr< CSemaphore > semAddnode
Definition: net.h:1105
std::atomic< NodeId > nLastNodeId
Definition: net.h:1060
std::atomic< std::chrono::microseconds > m_next_send_inv_to_incoming
Definition: net.h:1172
bool ShouldRunInactivityChecks(const CNode &node, int64_t secs_now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:1320
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:1827
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1122
void Interrupt()
Definition: net.cpp:2642
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:2952
std::thread threadDNSAddressSeed
Definition: net.h:1154
std::vector< std::string > vAddedNodes GUARDED_BY(cs_vAddedNodes)
void ThreadOpenConnections(std::vector< std::string > connect)
Definition: net.cpp:1841
void ThreadI2PAcceptIncoming()
Definition: net.cpp:2302
const uint64_t nSeed1
Definition: net.h:1131
void StartExtraBlockRelayPeers()
Definition: net.h:864
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1128
RecursiveMutex m_addr_fetches_mutex
Definition: net.h:1054
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:2913
unsigned int nPrevNodeCount
Definition: net.h:1061
void NotifyNumConnectionsChanged()
Definition: net.cpp:1305
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::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 This t...
Definition: net.h:1164
bool InitBinds(const Options &options)
Definition: net.cpp:2506
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(cs_totalBytesSent)
Definition: net.h:1035
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1049
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2115
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:3093
uint64_t GetMaxOutboundTarget() const
Definition: net.cpp:2907
std::unique_ptr< CSemaphore > semOutbound
Definition: net.h:1104
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:1044
void ThreadSocketHandler()
Definition: net.cpp:1638
RecursiveMutex cs_totalBytesSent
Definition: net.h:1030
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:2484
std::thread threadOpenConnections
Definition: net.h:1157
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2813
int64_t m_peer_connect_timeout
Definition: net.h:1040
std::vector< CNode * > vNodes GUARDED_BY(cs_vNodes)
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:1325
CNode * FindNode(const CNetAddr &ip)
Definition: net.cpp:327
void Init(const Options &connOptions)
Definition: net.h:773
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2829
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1131
unsigned int nReceiveFloodSize
Definition: net.h:1047
int GetExtraFullOutboundCount() const
Definition: net.cpp:1813
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:2961
RecursiveMutex cs_totalBytesRecv
Definition: net.h:1029
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:3017
int nMaxConnections
Definition: net.h:1106
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:2738
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
Definition: net.h:1031
void WakeMessageHandler()
Definition: net.cpp:1649
void SetNetworkActive(bool active)
Definition: net.cpp:2453
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
Definition: net.cpp:2211
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr) const
Definition: net.cpp:527
bool Start(CScheduler &scheduler, const Options &options)
Definition: net.cpp:2528
bool GenerateSelectSet(std::set< SOCKET > &recv_set, std::set< SOCKET > &send_set, std::set< SOCKET > &error_set)
Definition: net.cpp:1356
void ThreadDNSAddressSeed()
Definition: net.cpp:1658
AddrMan & addrman
Definition: net.h:1052
void ThreadMessageHandler()
Definition: net.cpp:2246
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
Definition: net.cpp:3098
Mutex mutexMsgProc
Definition: net.h:1137
bool fAddressesInitialized
Definition: net.h:1051
std::chrono::microseconds PoissonNextSendInbound(std::chrono::microseconds now, std::chrono::seconds average_interval)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:3076
~CConnman()
Definition: net.cpp:2732
void StopThreads()
Definition: net.cpp:2666
RecursiveMutex cs_vAddedNodes
Definition: net.h:1056
std::thread threadOpenAddedConnections
Definition: net.h:1156
friend struct CConnmanTest
Definition: net.h:1180
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:376
int m_max_outbound_full_relay
Definition: net.h:1109
int nMaxAddnode
Definition: net.h:1115
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:2884
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:3022
void StopNodes()
Definition: net.cpp:2683
bool GetUseAddrmanOutgoing() const
Definition: net.h:814
unsigned int nSendBufferMaxSize
Definition: net.h:1046
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1152
bool m_use_addrman_outgoing
Definition: net.h:1118
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:1088
std::function< void(CNode *)> NodeFn
Definition: net.h:823
NetEventsInterface * m_msgproc
Definition: net.h:1120
uint64_t nMaxOutboundLimit GUARDED_BY(cs_totalBytesSent)
std::atomic< bool > fNetworkActive
Definition: net.h:1050
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition: net.h:1170
void DisconnectNodes()
Definition: net.cpp:1255
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, bool network_active=true)
Definition: net.cpp:2468
void DumpAddresses()
Definition: net.cpp:1769
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:1178
bool AddNode(const std::string &node)
Definition: net.cpp:2790
int nMaxFeeler
Definition: net.h:1116
std::thread threadSocketHandler
Definition: net.h:1155
uint64_t GetTotalBytesSent() const
Definition: net.cpp:2967
bool RemoveAddedNode(const std::string &node)
Definition: net.cpp:2801
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1098
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:2341
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:205
void SetVersion(int n)
Definition: streams.h:362
void resize(size_type n, value_type c=0)
Definition: streams.h:257
void clear()
Definition: streams.h:261
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
CHash256 & Reset()
Definition: hash.h:42
Message header.
Definition: protocol.h:31
uint32_t nMessageSize
Definition: protocol.h:56
Network address.
Definition: netaddress.h:119
Transport protocol agnostic message container.
Definition: net.h:282
CNetMessage(CDataStream &&recv_in)
Definition: net.h:290
uint32_t m_message_size
size of the payload
Definition: net.h:286
std::chrono::microseconds m_time
time of message receipt
Definition: net.h:285
CDataStream m_recv
received message data
Definition: net.h:284
void SetVersion(int nVersionIn)
Definition: net.h:292
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition: net.h:287
std::string m_command
Definition: net.h:288
Information about a peer.
Definition: net.h:394
RecursiveMutex cs_vProcessMsg
Definition: net.h:415
std::atomic< int64_t > nLastSend
Definition: net.h:423
const CAddress addrBind
Definition: net.h:431
bool IsFeelerConn() const
Definition: net.h:487
mapMsgCmdSize mapSendBytesPerMsgCmd GUARDED_BY(cs_vSend)
bool ExpectServicesFromConn() const
Definition: net.h:499
bool m_prefer_evict
Definition: net.h:442
std::atomic< int > nVersion
Definition: net.h:435
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:421
bool IsInboundConn() const
Definition: net.h:495
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:443
std::atomic_bool fPauseRecv
Definition: net.h:457
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:460
NodeId GetId() const
Definition: net.h:585
bool IsManualConn() const
Definition: net.h:479
void PushTxInventory(const uint256 &hash)
Definition: net.h:643
std::atomic< int64_t > nTimeOffset
Definition: net.h:427
RecursiveMutex cs_sendProcessing
Definition: net.h:419
const std::string m_addr_name
Definition: net.h:432
mapMsgCmdSize mapRecvBytesPerMsgCmd GUARDED_BY(cs_vRecv)
CNode & operator=(const CNode &)=delete
std::deque< std::vector< unsigned char > > vSendMsg GUARDED_BY(cs_vSend)
std::string ConnectionTypeAsString() const
Definition: net.h:661
void SetCommonVersion(int greatest_common_version)
Definition: net.h:610
std::atomic< bool > m_bip152_highbandwidth_to
Definition: net.h:527
std::list< CNetMessage > vRecvMsg
Definition: net.h:692
size_t nProcessQueueSize
Definition: net.h:417
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:559
std::atomic< bool > m_bip152_highbandwidth_from
Definition: net.h:529
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:664
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition: net.h:449
bool IsAddrFetchConn() const
Definition: net.h:491
uint64_t GetLocalNonce() const
Definition: net.h:589
std::atomic< ServiceFlags > nServices
Definition: net.h:403
bool ReceiveMsgBytes(Span< const uint8_t > msg_bytes, bool &complete)
Receive bytes from the buffer and deserialize them into messages.
Definition: net.cpp:631
RecursiveMutex cs_SubVer
Definition: net.h:436
const CAddress addr
Definition: net.h:429
RecursiveMutex cs_addrLocal
Definition: net.h:696
CSemaphoreGrant grantOutbound
Definition: net.h:453
const int64_t nTimeConnected
Unix epoch time at peer connection, in seconds.
Definition: net.h:426
Mutex cs_hSocket
Definition: net.h:412
const uint64_t nKeyedNetGroup
Definition: net.h:456
void CopyStats(CNodeStats &stats)
Definition: net.cpp:575
std::atomic< int > nRefCount
Definition: net.h:454
std::atomic< int > m_greatest_common_version
Definition: net.h:673
bool IsBlockOnlyConn() const
Definition: net.h:483
void CloseSocketDisconnect()
Definition: net.cpp:516
int GetCommonVersion() const
Definition: net.h:615
bool IsFullOutboundConn() const
Definition: net.h:475
std::unique_ptr< TransportSerializer > m_serializer
Definition: net.h:400
bool fClient
Definition: net.h:446
Mutex cs_vSend
Definition: net.h:411
CNode * AddRef()
Definition: net.h:624
std::atomic_bool fPauseSend
Definition: net.h:458
SOCKET hSocket GUARDED_BY(cs_hSocket)
int GetRefCount() const
Definition: net.h:593
const ServiceFlags nLocalServices
Services offered to this peer.
Definition: net.h:690
std::unique_ptr< TxRelay > m_tx_relay
Definition: net.h:558
std::unique_ptr< TransportDeserializer > m_deserializer
Definition: net.h:399
size_t nSendOffset GUARDED_BY(cs_vSend)
Offset inside the first vSendMsg already sent.
Definition: net.h:408
NetPermissionFlags m_permissionFlags
Definition: net.h:402
std::atomic< int64_t > nLastRecv
Definition: net.h:424
std::atomic< int64_t > nLastTXTime
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition: net.h:571
const ConnectionType m_conn_type
Definition: net.h:672
Network ConnectedThroughNetwork() const
Get network the peer connected through.
Definition: net.cpp:568
CService addrLocal GUARDED_BY(cs_addrLocal)
const uint64_t nLocalHostNonce
Definition: net.h:671
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition: net.h:574
CNode(NodeId id, ServiceFlags nLocalServicesIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion)
Definition: net.cpp:2980
size_t nSendSize GUARDED_BY(cs_vSend)
Total size of all vSendMsg entries.
Definition: net.h:406
ServiceFlags GetLocalServices() const
Definition: net.h:656
std::string cleanSubVer GUARDED_BY(cs_SubVer)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:441
CNode(const CNode &)=delete
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:434
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition: net.h:578
const NodeId id
Definition: net.h:670
void AddKnownTx(const uint256 &hash)
Definition: net.h:635
Mutex cs_vRecv
Definition: net.h:413
~CNode()
Definition: net.cpp:3012
bool m_limited_node
Definition: net.h:447
std::atomic< int64_t > nLastBlockTime
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition: net.h:565
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Definition: net.h:409
std::atomic_bool fDisconnect
Definition: net.h:452
CService GetAddrLocal() const
Definition: net.cpp:553
std::list< CNetMessage > vProcessMsg GUARDED_BY(cs_vProcessMsg)
void Release()
Definition: net.h:630
std::string addrLocal
Definition: net.h:266
CAddress addrBind
Definition: net.h:270
int64_t nLastBlockTime
Definition: net.h:247
uint64_t nRecvBytes
Definition: net.h:259
mapMsgCmdSize mapSendBytesPerMsgCmd
Definition: net.h:258
bool fRelayTxes
Definition: net.h:243
std::chrono::microseconds m_last_ping_time
Definition: net.h:262
uint32_t m_mapped_as
Definition: net.h:273
bool fInbound
Definition: net.h:253
uint64_t nSendBytes
Definition: net.h:257
int64_t nTimeConnected
Definition: net.h:248
ConnectionType m_conn_type
Definition: net.h:274
CAddress addr
Definition: net.h:268
CAmount minFeeFilter
Definition: net.h:264
int64_t nLastRecv
Definition: net.h:245
std::chrono::microseconds m_min_ping_time
Definition: net.h:263
ServiceFlags nServices
Definition: net.h:242
int64_t nTimeOffset
Definition: net.h:249
bool m_bip152_highbandwidth_from
Definition: net.h:255
bool m_bip152_highbandwidth_to
Definition: net.h:254
int64_t nLastTXTime
Definition: net.h:246
std::string m_addr_name
Definition: net.h:250
mapMsgCmdSize mapRecvBytesPerMsgCmd
Definition: net.h:260
int nVersion
Definition: net.h:251
Network m_network
Definition: net.h:272
NodeId nodeid
Definition: net.h:241
NetPermissionFlags m_permissionFlags
Definition: net.h:261
std::string cleanSubVer
Definition: net.h:252
int m_starting_height
Definition: net.h:256
int64_t nLastSend
Definition: net.h:244
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:109
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:34
RAII-style semaphore lock.
Definition: sync.h:310
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
SipHash-2-4.
Definition: siphash.h:14
Interface for message handling.
Definition: net.h:706
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual void InitializeNode(CNode *pnode)=0
Initialize a peer (setup state, queue any initial messages)
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(pnode -> cs_sendProcessing)=0
Send queued protocol messages to a given node.
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
Process protocol messages received from a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:189
The TransportDeserializer takes care of holding and deserializing the network receive buffer.
Definition: net.h:302
virtual ~TransportDeserializer()
Definition: net.h:312
virtual bool Complete() const =0
virtual CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message)=0
virtual int Read(Span< const uint8_t > &msg_bytes)=0
read and deserialize data, advances msg_bytes data pointer
virtual void SetVersion(int version)=0
The TransportSerializer prepares messages for the network transport.
Definition: net.h:380
virtual void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header)=0
virtual ~TransportSerializer()
Definition: net.h:384
const CChainParams & m_chain_params
Definition: net.h:318
CDataStream vRecv
Definition: net.h:325
CMessageHeader hdr
Definition: net.h:324
CNetMessage GetMessage(std::chrono::microseconds time, bool &reject_message) override
Definition: net.cpp:741
const uint256 & GetMessageHash() const
Definition: net.cpp:733
const NodeId m_node_id
Definition: net.h:319
int Read(Span< const uint8_t > &msg_bytes) override
read and deserialize data, advances msg_bytes data pointer
Definition: net.h:365
V1TransportDeserializer(const CChainParams &chain_params, const NodeId node_id, int nTypeIn, int nVersionIn)
Definition: net.h:345
void SetVersion(int nVersionIn) override
Definition: net.h:360
int readData(Span< const uint8_t > msg_bytes)
Definition: net.cpp:716
int readHeader(Span< const uint8_t > msg_bytes)
Definition: net.cpp:676
unsigned int nHdrPos
Definition: net.h:326
bool Complete() const override
Definition: net.h:354
CHash256 hasher
Definition: net.h:320
CDataStream hdrbuf
Definition: net.h:323
uint256 data_hash
Definition: net.h:321
unsigned int nDataPos
Definition: net.h:327
void prepareForTransport(CSerializedNetMsg &msg, std::vector< unsigned char > &header) override
Definition: net.cpp:778
void SetNull()
Definition: uint256.h:39
256-bit opaque blob.
Definition: uint256.h:124
unsigned int SOCKET
Definition: compat.h:41
static CService ip(uint32_t i)
#define LogPrint(category,...)
Definition: logging.h:191
unsigned int nonce
Definition: miner_tests.cpp:54
@ NET
Definition: logging.h:38
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:181
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:201
uint16_t GetListenPort()
Definition: net.cpp:125
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:71
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:321
void RemoveLocal(const CService &addr)
Definition: net.cpp:283
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:59
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:63
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:250
bool fDiscover
Definition: net.cpp:112
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:85
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:79
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:83
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:75
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:48
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:57
bool fListen
Definition: net.cpp:113
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:46
RecursiveMutex cs_mapLocalHost
Definition: net.cpp:114
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:73
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:55
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:84
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:117
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(cs_mapLocalHost)
const std::string NET_MESSAGE_COMMAND_OTHER
Definition: net.cpp:104
static const int TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:51
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition: net.cpp:986
void CaptureMessage(const CAddress &addr, const std::string &msg_type, const Span< const unsigned char > &data, bool is_incoming)
Dump binary message to file, with timestamp.
Definition: net.cpp:3105
std::optional< CAddress > GetLocalAddrForPeer(CNode *pnode)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:208
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:290
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:81
ConnectionType
Different types of connections to a peer.
Definition: net.h:120
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ 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.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:82
int64_t NodeId
Definition: net.h:87
std::map< std::string, uint64_t > mapMsgCmdSize
Definition: net.h:236
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:67
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:69
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
Definition: net.cpp:131
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:53
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:77
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &vEvictionCandidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition: net.cpp:913
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:61
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
Definition: net.cpp:533
@ LOCAL_NONE
Definition: net.h:189
@ LOCAL_MAPPED
Definition: net.h:192
@ LOCAL_MANUAL
Definition: net.h:193
@ LOCAL_MAX
Definition: net.h:195
@ LOCAL_BIND
Definition: net.h:191
@ LOCAL_IF
Definition: net.h:190
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:65
void Discover()
Definition: net.cpp:2402
bool IsReachable(enum Network net)
Definition: net.cpp:298
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:310
std::chrono::microseconds PoissonNextSend(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:3087
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:45
ConnectionDirection
Definition: netbase.h:32
ServiceFlags
nServices flags
Definition: protocol.h:271
@ NODE_NONE
Definition: protocol.h:274
bool fInbound
Definition: net.h:94
CService resolvedAddress
Definition: net.h:92
bool fConnected
Definition: net.h:93
std::string strAddedNode
Definition: net.h:91
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1069
std::chrono::microseconds m_cache_entry_expiration
Definition: net.h:1071
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1070
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:951
ListenSocket(SOCKET socket_, NetPermissionFlags permissions_)
Definition: net.h:952
NetPermissionFlags m_permissions
Definition: net.h:954
int m_max_outbound_block_relay
Definition: net.h:749
unsigned int nReceiveFloodSize
Definition: net.h:756
int m_max_outbound_full_relay
Definition: net.h:748
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:761
uint64_t nMaxOutboundLimit
Definition: net.h:757
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:760
CClientUIInterface * uiInterface
Definition: net.h:752
std::vector< CService > onion_binds
Definition: net.h:763
int nMaxFeeler
Definition: net.h:751
std::vector< std::string > m_specified_outgoing
Definition: net.h:768
NetEventsInterface * m_msgproc
Definition: net.h:753
int nMaxConnections
Definition: net.h:747
ServiceFlags nLocalServices
Definition: net.h:746
std::vector< std::string > m_added_nodes
Definition: net.h:769
int64_t m_peer_connect_timeout
Definition: net.h:758
std::vector< CService > vBinds
Definition: net.h:762
unsigned int nSendBufferMaxSize
Definition: net.h:755
bool m_i2p_accept_incoming
Definition: net.h:770
std::vector< std::string > vSeedNodes
Definition: net.h:759
BanMan * m_banman
Definition: net.h:754
bool m_use_addrman_outgoing
Definition: net.h:767
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:766
int nMaxAddnode
Definition: net.h:750
CRollingBloomFilter filterInventoryKnown GUARDED_BY(cs_tx_inventory)
Definition: net.h:541
std::set< uint256 > setInventoryTxToSend
Definition: net.h:541
CAmount lastSentFeeFilter
Definition: net.h:553
std::chrono::microseconds m_next_send_feefilter
Definition: net.h:554
std::unique_ptr< CBloomFilter > pfilter PT_GUARDED_BY(cs_filter) GUARDED_BY(cs_filter)
Definition: net.h:538
std::chrono::microseconds nNextInvSend
Definition: net.h:549
bool fSendMempool GUARDED_BY(cs_tx_inventory)
Definition: net.h:546
std::atomic< CAmount > minFeeFilter
Minimum fee rate with which to filter inv's to this node.
Definition: net.h:552
std::atomic< std::chrono::seconds > m_last_mempool_req
Definition: net.h:548
bool fRelayTxes GUARDED_BY(cs_filter)
Definition: net.h:537
RecursiveMutex cs_filter
Definition: net.h:532
RecursiveMutex cs_tx_inventory
Definition: net.h:538
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:110
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:109
uint16_t nPort
Definition: net.h:229
int nScore
Definition: net.h:228
int64_t nLastBlockTime
Definition: net.h:1195
Network m_network
Definition: net.h:1203
int64_t nTimeConnected
Definition: net.h:1193
bool fRelevantServices
Definition: net.h:1197
int64_t nLastTXTime
Definition: net.h:1196
std::chrono::microseconds m_min_ping_time
Definition: net.h:1194
uint64_t nKeyedNetGroup
Definition: net.h:1200
Bilingual messages:
Definition: translation.h:16
#define LOCK(cs)
Definition: sync.h:226
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
assert(!tx.IsCoinBase())
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15