Bitcoin Core 32.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-present 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 <bip324.h>
10#include <chainparams.h>
11#include <common/bloom.h>
12#include <compat/compat.h>
13#include <consensus/amount.h>
14#include <crypto/siphash.h>
15#include <hash.h>
16#include <i2p.h>
18#include <net_permissions.h>
19#include <netaddress.h>
20#include <netbase.h>
21#include <netgroup.h>
24#include <policy/feerate.h>
25#include <protocol.h>
26#include <random.h>
27#include <semaphore_grant.h>
28#include <span.h>
29#include <streams.h>
30#include <sync.h>
31#include <uint256.h>
32#include <util/check.h>
33#include <util/not_null.h>
34#include <util/sock.h>
35#include <util/threadinterrupt.h>
36
37#include <atomic>
38#include <condition_variable>
39#include <cstdint>
40#include <deque>
41#include <functional>
42#include <list>
43#include <map>
44#include <memory>
45#include <optional>
46#include <queue>
47#include <string_view>
48#include <thread>
49#include <unordered_set>
50#include <vector>
51
52class AddrMan;
53class BanMan;
54class CChainParams;
55class CNode;
56class CScheduler;
57struct bilingual_str;
58
60inline constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
62inline constexpr auto FEELER_INTERVAL = 2min;
64inline constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
66inline constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
68inline constexpr unsigned int MAX_SUBVERSION_LENGTH = 256;
70inline constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
72inline constexpr int MAX_ADDNODE_CONNECTIONS = 8;
74inline constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
76inline constexpr int MAX_FEELER_CONNECTIONS = 1;
78inline constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};
80inline constexpr bool DEFAULT_LISTEN = true;
82inline constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS{200};
84inline constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT{50};
86inline const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
88inline constexpr bool DEFAULT_BLOCKSONLY = false;
90inline constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
92inline constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
94inline constexpr int NUM_FDS_MESSAGE_CAPTURE = 1;
96inline constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
97
98inline constexpr bool DEFAULT_FORCEDNSSEED{false};
99inline constexpr bool DEFAULT_DNSSEED{true};
100inline constexpr bool DEFAULT_FIXEDSEEDS{true};
101inline constexpr size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
102inline constexpr size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
103
104inline constexpr bool DEFAULT_V2_TRANSPORT{true};
105
106typedef int64_t NodeId;
107
109 std::string m_added_node;
111};
112
118};
119
120class CNodeStats;
122
124 CSerializedNetMsg() = default;
127 // No implicit copying, only moves.
130
132 {
134 copy.data = data;
135 copy.m_type = m_type;
136 return copy;
137 }
138
139 std::vector<unsigned char> data;
140 std::string m_type;
141
143 size_t GetMemoryUsage() const noexcept;
144};
145
151void Discover();
152
153uint16_t GetListenPort();
154
155enum
156{
157 LOCAL_NONE, // unknown
158 LOCAL_IF, // address a local interface listens on
159 LOCAL_BIND, // address explicit bound to
160 LOCAL_MAPPED, // address reported by PCP
161 LOCAL_MANUAL, // address explicitly specified (-externalip=)
162
165
167std::optional<CService> GetLocalAddrForPeer(CNode& node);
168
169void ClearLocal();
170bool AddLocal(const CService& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
171bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
172void RemoveLocal(const CService& addr);
173bool SeenLocal(const CService& addr);
174bool IsLocal(const CService& addr);
175CService GetLocalAddress(const CNode& peer);
176
177extern bool fDiscover;
178extern bool fListen;
179
181extern std::string strSubVersion;
182
185 uint16_t nPort;
186};
187
189extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
190
191extern const std::string NET_MESSAGE_TYPE_OTHER;
192using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
193
195{
196public:
200 std::chrono::seconds m_last_tx_time;
201 std::chrono::seconds m_last_block_time;
203 std::string m_addr_name;
205 std::string cleanSubVer;
207 // We requested high bandwidth connection to peer
209 // Peer requested high bandwidth connection
211 uint64_t nSendBytes;
213 uint64_t nRecvBytes;
216 NodeClock::duration m_last_ping_time;
217 NodeClock::duration m_min_ping_time;
218 // Our address, as reported by the peer
219 std::string addrLocal;
220 // Address of this peer
222 // Bind address of our side of the connection
224 // Network the peer connected through
226 uint32_t m_mapped_as;
231 std::string m_session_id;
232};
233
234
240{
241public:
245 uint32_t m_message_size{0};
246 uint32_t m_raw_message_size{0};
247 std::string m_type;
248
249 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
250 // Only one CNetMessage object will exist for the same message on either
251 // the receive or processing queue. For performance reasons we therefore
252 // delete the copy constructor and assignment operator to avoid the
253 // possibility of copying CNetMessage objects.
255 CNetMessage(const CNetMessage&) = delete;
258
260 size_t GetMemoryUsage() const noexcept;
261};
262
265public:
266 virtual ~Transport() = default;
267
268 struct Info
269 {
271 std::optional<uint256> session_id;
272 };
273
275 virtual Info GetInfo() const noexcept = 0;
276
277 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
278 // agnostic CNetMessage (message type & payload) objects.
279
281 virtual bool ReceivedMessageComplete() const = 0;
282
289 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
290
298 virtual CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) = 0;
299
300 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
301
308 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
309
317 using BytesToSend = std::tuple<
318 std::span<const uint8_t> /*to_send*/,
319 bool /*more*/,
320 const std::string& /*m_type*/
321 >;
322
358 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
359
366 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
367
369 virtual size_t GetSendMemoryUsage() const noexcept = 0;
370
371 // 3. Miscellaneous functions.
372
374 virtual bool ShouldReconnectV1() const noexcept = 0;
375};
376
377class V1Transport final : public Transport
378{
379private:
381 const NodeId m_node_id; // Only for logging
383 mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
384 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
385 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
386 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
387 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
388 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
389 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
390 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
391
392 const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
393 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
394 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
395
396 void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
397 AssertLockHeld(m_recv_mutex);
398 vRecv.clear();
399 hdrbuf.clear();
400 hdrbuf.resize(24);
401 in_data = false;
402 nHdrPos = 0;
403 nDataPos = 0;
404 data_hash.SetNull();
405 hasher.Reset();
406 }
407
408 bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
409 {
410 AssertLockHeld(m_recv_mutex);
411 if (!in_data) return false;
412 return hdr.nMessageSize == nDataPos;
413 }
414
418 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
420 CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
422 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
424 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
425
426public:
427 explicit V1Transport(NodeId node_id) noexcept;
428
429 bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
430 {
431 AssertLockNotHeld(m_recv_mutex);
432 return WITH_LOCK(m_recv_mutex, return CompleteInternal());
433 }
434
435 Info GetInfo() const noexcept override;
436
437 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
438 {
439 AssertLockNotHeld(m_recv_mutex);
440 LOCK(m_recv_mutex);
441 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
442 if (ret < 0) {
443 Reset();
444 } else {
445 msg_bytes = msg_bytes.subspan(ret);
446 }
447 return ret >= 0;
448 }
449
450 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
451
452 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
453 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
454 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
455 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
456 bool ShouldReconnectV1() const noexcept override { return false; }
457};
458
459class V2Transport final : public Transport
460{
461private:
465 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
466
469 static constexpr size_t V1_PREFIX_LEN = 16;
470
471 // The sender side and receiver side of V2Transport are state machines that are transitioned
472 // through, based on what has been received. The receive state corresponds to the contents of,
473 // and bytes received to, the receive buffer. The send state controls what can be appended to
474 // the send buffer and what can be sent from it.
475
490 enum class RecvState : uint8_t {
496 KEY_MAYBE_V1,
497
503 KEY,
504
511 GARB_GARBTERM,
512
521 VERSION,
522
528 APP,
529
534 APP_READY,
535
539 V1,
540 };
541
555 enum class SendState : uint8_t {
562 MAYBE_V1,
563
569 AWAITING_KEY,
570
577 READY,
578
582 V1,
583 };
584
588 const bool m_initiating;
593
595 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
598 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
600 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
602 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
604 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
606 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
607
610 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
612 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
614 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
616 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
618 std::string m_send_type GUARDED_BY(m_send_mutex);
620 SendState m_send_state GUARDED_BY(m_send_mutex);
622 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
623
625 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
627 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
629 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
631 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
633 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
635 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
637 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
639 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
641 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
642
643public:
644 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
645
651 V2Transport(NodeId nodeid, bool initiating) noexcept;
652
654 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
655
656 // Receive side functions.
657 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
658 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
659 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
660
661 // Send side functions.
662 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
663 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
664 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
665 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
666
667 // Miscellaneous functions.
668 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
669 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
670};
671
673{
675 std::optional<Proxy> proxy_override = {};
676 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
677 bool prefer_evict = false;
678 size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
679 bool use_v2transport = false;
680};
681
683class CNode
684{
685public:
689
691
700 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
701
703 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
705 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
707 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
711
712 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
713
714 std::atomic<NodeClock::time_point> m_last_send{NodeClock::epoch};
715 std::atomic<NodeClock::time_point> m_last_recv{NodeClock::epoch};
718
720 const std::optional<Proxy> m_proxy_override;
721
722 // Address of this peer
724 // Bind address of our side of the connection
726 const std::string m_addr_name;
728 const std::string m_dest;
730 const bool m_inbound_onion;
731 std::atomic<int> nVersion{0};
737 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
738 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
739 bool HasPermission(NetPermissionFlags permission) const {
740 return NetPermissions::HasFlag(m_permission_flags, permission);
741 }
743 std::atomic_bool fSuccessfullyConnected{false};
744 // Setting fDisconnect to true will cause the node to be disconnected the
745 // next time DisconnectNodes() runs
746 std::atomic_bool fDisconnect{false};
748 std::atomic<int> nRefCount{0};
749
750 const uint64_t nKeyedNetGroup;
751 std::atomic_bool fPauseRecv{false};
752 std::atomic_bool fPauseSend{false};
753
756 const uint64_t m_network_key;
757
759
761 void MarkReceivedMsgsForProcessing()
762 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
763
769 std::optional<std::pair<CNetMessage, bool>> PollMessage()
770 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
771
773 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
775 {
776 mapSendBytesPerMsgType[msg_type] += sent_bytes;
777 }
778
780 switch (m_conn_type) {
783 return true;
789 return false;
790 } // no default case, so the compiler can warn about missing cases
791
792 assert(false);
793 }
794
795 bool IsFullOutboundConn() const {
796 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
797 }
798
799 bool IsManualConn() const {
800 return m_conn_type == ConnectionType::MANUAL;
801 }
802
804 {
805 switch (m_conn_type) {
811 return false;
814 return true;
815 } // no default case, so the compiler can warn about missing cases
816
817 assert(false);
818 }
819
820 bool IsBlockOnlyConn() const {
821 return m_conn_type == ConnectionType::BLOCK_RELAY;
822 }
823
824 bool IsFeelerConn() const {
825 return m_conn_type == ConnectionType::FEELER;
826 }
827
828 bool IsAddrFetchConn() const {
829 return m_conn_type == ConnectionType::ADDR_FETCH;
830 }
831
833 {
834 return m_conn_type == ConnectionType::PRIVATE_BROADCAST;
835 }
836
840 {
841 return IsPrivateBroadcastConn() ? WTXID_RELAY_VERSION : PROTOCOL_VERSION;
842 }
843
844 bool IsInboundConn() const {
845 return m_conn_type == ConnectionType::INBOUND;
846 }
847
849 switch (m_conn_type) {
853 return false;
858 return true;
859 } // no default case, so the compiler can warn about missing cases
860
861 assert(false);
862 }
863
874 Network ConnectedThroughNetwork() const;
875
877 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
878
879 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
880 std::atomic<bool> m_bip152_highbandwidth_to{false};
881 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
882 std::atomic<bool> m_bip152_highbandwidth_from{false};
883
885 std::atomic_bool m_has_all_wanted_services{false};
886
889 std::atomic_bool m_relays_txs{false};
890
893 std::atomic_bool m_bloom_filter_loaded{false};
894
900 std::atomic<std::chrono::seconds> m_last_block_time{0s};
901
906 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
907
909 std::atomic<NodeClock::duration> m_last_ping_time{0us};
910
913 std::atomic<NodeClock::duration> m_min_ping_time{NodeClock::duration::max()};
914
915 CNode(NodeId id,
916 std::shared_ptr<Sock> sock,
917 const CAddress& addrIn,
918 uint64_t nKeyedNetGroupIn,
919 uint64_t nLocalHostNonceIn,
920 const CService& addrBindIn,
921 const std::string& addrNameIn,
922 ConnectionType conn_type_in,
923 bool inbound_onion,
924 uint64_t network_key,
925 CNodeOptions&& node_opts = {});
926 CNode(const CNode&) = delete;
927 CNode& operator=(const CNode&) = delete;
928
929 NodeId GetId() const {
930 return id;
931 }
932
933 uint64_t GetLocalNonce() const {
934 return nLocalHostNonce;
935 }
936
937 int GetRefCount() const
938 {
939 assert(nRefCount >= 0);
940 return nRefCount;
941 }
942
952 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
953
954 void SetCommonVersion(int greatest_common_version)
955 {
956 Assume(m_greatest_common_version == INIT_PROTO_VERSION);
957 m_greatest_common_version = greatest_common_version;
958 }
960 {
961 return m_greatest_common_version;
962 }
963
964 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
966 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
967
968 CNode* AddRef()
969 {
970 nRefCount++;
971 return this;
972 }
973
974 void Release()
975 {
976 nRefCount--;
977 }
978
979 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
980
981 void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
982
984
990 std::string LogPeer() const;
991
997 std::string DisconnectMsg() const;
998
1000 void PongReceived(NodeClock::duration ping_time)
1001 {
1002 m_last_ping_time = ping_time;
1003 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
1004 }
1005
1006private:
1007 const NodeId id;
1008 const uint64_t nLocalHostNonce;
1009 std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1010
1011 const size_t m_recv_flood_size;
1012 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1013
1015 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1016 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1017
1018 // Our address, as reported by the peer
1019 CService m_addr_local GUARDED_BY(m_addr_local_mutex);
1021
1022 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1023 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1024
1035 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1036};
1037
1042{
1043public:
1046
1048 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1049
1051 virtual void FinalizeNode(const CNode& node) = 0;
1052
1057 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1058
1066 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1067
1074 virtual bool SendMessages(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1075
1076
1077protected:
1083};
1084
1086{
1087public:
1088
1089 struct Options
1090 {
1091 ServiceFlags m_local_services = NODE_NONE;
1092 int m_max_automatic_connections = DEFAULT_MAX_PEER_CONNECTIONS;
1093 int m_full_relay_inbound_percent = DEFAULT_FULL_RELAY_INBOUND_PCT;
1095 NetEventsInterface* m_msgproc = nullptr;
1096 BanMan* m_banman = nullptr;
1097 unsigned int nSendBufferMaxSize = 0;
1098 unsigned int nReceiveFloodSize = 0;
1099 uint64_t nMaxOutboundLimit = 0;
1100 int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1101 std::vector<std::string> vSeedNodes;
1102 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1103 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1104 std::vector<NetWhitebindPermissions> vWhiteBinds;
1105 std::vector<CService> vBinds;
1106 std::vector<CService> onion_binds;
1110 bool m_use_addrman_outgoing = true;
1111 std::vector<std::string> m_specified_outgoing;
1112 std::vector<std::string> m_added_nodes;
1114 bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1115 bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1116 bool m_capture_messages = false;
1117 };
1118
1119 void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1120 {
1121 AssertLockNotHeld(m_total_bytes_sent_mutex);
1122
1123 m_local_services = connOptions.m_local_services;
1124 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1125 m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1126 m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1127 m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1128 m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1129 m_max_inbound_full_relay = std::max(0, static_cast<int>(connOptions.m_full_relay_inbound_percent / 100.0 * m_max_inbound));
1130 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1131 m_client_interface = connOptions.uiInterface;
1132 m_banman = connOptions.m_banman;
1133 m_msgproc = connOptions.m_msgproc;
1134 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1135 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1136 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1137 {
1138 LOCK(m_total_bytes_sent_mutex);
1139 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1140 }
1141 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1142 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1143 {
1144 LOCK(m_added_nodes_mutex);
1145 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1146 // peer doesn't support it or immediately disconnects us for another reason.
1147 const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1148 for (const std::string& added_node : connOptions.m_added_nodes) {
1149 m_added_node_params.push_back({added_node, use_v2transport});
1150 }
1151 }
1152 m_onion_binds = connOptions.onion_binds;
1153 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1154 whitelist_relay = connOptions.whitelist_relay;
1155 m_capture_messages = connOptions.m_capture_messages;
1156 }
1157
1158 // test only
1159 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1160
1161 CConnman(uint64_t seed0,
1162 uint64_t seed1,
1163 AddrMan& addrman,
1164 const NetGroupManager& netgroupman,
1165 const CChainParams& params,
1166 bool network_active = true,
1167 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1168
1169 ~CConnman();
1170
1171 bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc, !m_anchors_mutex);
1172
1173 void StopThreads();
1174 void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_anchors_mutex);
1175 void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_anchors_mutex)
1176 {
1177 AssertLockNotHeld(m_nodes_mutex);
1178 AssertLockNotHeld(m_reconnections_mutex);
1181 };
1182
1183 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1184 bool GetNetworkActive() const { return fNetworkActive; };
1185 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1186 void SetNetworkActive(bool active) EXCLUSIVE_LOCKS_REQUIRED(!m_anchors_mutex, !m_nodes_mutex);
1187
1200 bool OpenNetworkConnection(const CAddress& addrConnect,
1201 bool fCountFailure,
1202 CountingSemaphoreGrant<>&& grant_outbound,
1203 const char* pszDest,
1204 ConnectionType conn_type,
1205 bool use_v2transport,
1206 const std::optional<Proxy>& proxy_override)
1207 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1208
1211 {
1212 public:
1221 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1222
1227 std::counting_semaphore<> m_sem_conn_max{MAX_PRIVATE_BROADCAST_CONNECTIONS};
1228
1238 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1239
1241 size_t NumToOpen() const;
1242
1248 void NumToOpenAdd(size_t n);
1249
1256 size_t NumToOpenSub(size_t n);
1257
1259 void NumToOpenWait() const;
1260
1261 protected:
1267 std::optional<Proxy> ProxyForIPv4or6() const;
1268
1270 std::atomic_size_t m_num_to_open{0};
1271
1272 friend struct ConnmanTestMsg;
1274
1276 void ASMapHealthCheck();
1277
1278 // alias for thread safety annotations only, not defined
1280
1281 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1282
1284
1285 using NodeFn = std::function<void(CNode*)>;
1287 {
1289 for (auto&& node : m_nodes) {
1291 func(node);
1292 }
1293 };
1294
1296 {
1298 for (auto&& node : m_nodes) {
1300 func(node);
1301 }
1302 };
1303
1304 // Addrman functions
1316 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1331 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1332
1333 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1334 // a peer that is better than all our current peers.
1335 void SetTryNewOutboundPeer(bool flag);
1336 bool GetTryNewOutboundPeer() const;
1337
1339
1340 // Count the number of full-relay peer we have.
1342 // Return the number of outbound peers we have in excess of our target (eg,
1343 // if we previously called SetTryNewOutboundPeer(true), and have since set
1344 // to false, we may have extra peers that we wish to disconnect). This may
1345 // return a value less than (num_outbound_connections - num_outbound_slots)
1346 // in cases where some outbound connections are not yet fully connected, or
1347 // not yet fully disconnected.
1349 // Count the number of block-relay-only peers we have over our limit.
1360 bool EvictTxPeerIfFull(std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1361
1365 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const
1367
1381 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)
1383
1386 uint32_t GetMappedAS(const CNetAddr& addr) const;
1387 void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1389 bool DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast = true) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1392
1400
1405
1407 std::chrono::seconds GetMaxOutboundTimeframe() const;
1408
1412 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1413
1417
1419
1420 uint64_t GetTotalBytesRecv() const;
1422
1424 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1425
1427
1429 bool ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const;
1430
1432
1433private:
1435 public:
1436 std::shared_ptr<Sock> sock;
1438 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1439 : sock{sock_}, m_permissions{permissions_}
1440 {
1441 }
1442
1443 private:
1445 };
1446
1450
1451 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1452 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1453 bool InitBinds(const Options& options);
1454
1460
1461 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1462
1466
1468 void ThreadOpenConnections(std::vector<std::string> connect, std::span<const std::string> seed_nodes)
1475
1482
1491 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1492 NetPermissionFlags permission_flags,
1493 const CService& addr_bind,
1494 const CService& addr)
1496
1500 bool InactivityCheck(const CNode& node, NodeClock::time_point now) const;
1501
1507 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1508
1513
1519 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1520 const Sock::EventsPerSock& events_per_sock)
1522
1527 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
1529
1534
1535 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1536
1544 bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1545
1554
1559
1566 bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1567
1578 CNode* ConnectNode(CAddress addrConnect,
1579 const char* pszDest,
1580 bool fCountFailure,
1581 ConnectionType conn_type,
1582 bool use_v2transport,
1583 const std::optional<Proxy>& proxy_override)
1585
1586 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1587
1588 void DeleteNode(CNode* pnode);
1589
1591
1593 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1594
1595 void DumpAddresses();
1596
1597 // Network stats
1598 void RecordBytesRecv(uint64_t bytes);
1600
1605 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1606
1611
1623
1624 // Whether the node should be passed out in ForEach* callbacks
1625 static bool NodeFullyConnected(const CNode* pnode);
1626
1627 uint16_t GetDefaultPort(Network net) const;
1628 uint16_t GetDefaultPort(const std::string& addr) const;
1629
1630 // Network usage totals
1632 std::atomic<uint64_t> nTotalBytesRecv{0};
1633 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1634
1635 // outbound limit & stats
1636 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1637 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1639
1640 // P2P timeout in seconds
1641 std::chrono::seconds m_peer_connect_timeout;
1642
1643 // Whitelisted ranges. Any node connecting from these is automatically
1644 // whitelisted (as well as those connecting to whitelisted binds).
1645 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1646 // Whitelisted ranges for outgoing connections.
1647 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1648
1649 unsigned int nSendBufferMaxSize{0};
1650 unsigned int nReceiveFloodSize{0};
1651
1652 std::vector<ListenSocket> vhListenSocket;
1653 std::atomic<bool> fNetworkActive{true};
1655 std::reference_wrapper<AddrMan> addrman;
1657 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1659
1660 // connection string and whether to use v2 p2p
1661 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1662
1664 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1665 std::list<CNode*> m_nodes_disconnected;
1667 std::atomic<NodeId> nLastNodeId{0};
1668 unsigned int nPrevNodeCount{0};
1669
1670 // Stores number of full-tx connections (outbound and manual) per network
1671 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1672
1680 std::vector<CAddress> m_addrs_response_cache;
1681 std::chrono::microseconds m_cache_entry_expiration{0};
1682 };
1683
1698 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1699
1711 std::atomic<ServiceFlags> m_local_services;
1712
1713 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1714 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1715
1722
1723 /*
1724 * Maximum number of peers by connection type. Might vary from defaults
1725 * based on -maxconnections init value.
1726 */
1727
1728 // How many full-relay (tx, block, addr) outbound peers we want
1730
1731 // How many block-relay only outbound peers we want
1732 // We do not relay tx or addr messages with these peers
1734
1735 int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1736 int m_max_feeler{MAX_FEELER_CONNECTIONS};
1740
1746
1753 std::vector<CAddress> m_anchors GUARDED_BY(m_anchors_mutex);
1754
1756 const uint64_t nSeed0, nSeed1;
1757
1759 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1760
1761 std::condition_variable condMsgProc;
1763 std::atomic<bool> flagInterruptMsgProc{false};
1764
1769 const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1770
1776 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1777
1785
1790
1795 std::atomic_bool m_start_extra_block_relay_peers{false};
1796
1801 std::vector<CService> m_onion_binds;
1802
1808
1814
1818 bool m_capture_messages{false};
1819
1824
1832 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1833
1838
1841 {
1842 std::optional<Proxy> proxy_override;
1845 std::string destination;
1848 };
1849
1853 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1854
1856 void PerformReconnections()
1857 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1858
1863 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1864
1870 {
1871 public:
1872 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1873 EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
1874 {
1875 {
1876 LOCK(connman.m_nodes_mutex);
1877 m_nodes_copy = connman.m_nodes;
1878 for (auto& node : m_nodes_copy) {
1879 node->AddRef();
1880 }
1881 }
1882 if (shuffle) {
1883 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1884 }
1885 }
1886
1888 {
1889 for (auto& node : m_nodes_copy) {
1890 node->Release();
1891 }
1892 }
1893
1894 const std::vector<CNode*>& Nodes() const
1895 {
1896 return m_nodes_copy;
1897 }
1898
1899 private:
1900 std::vector<CNode*> m_nodes_copy;
1901 };
1902
1904
1905 friend struct ConnmanTestMsg;
1906};
1907
1909extern std::function<void(const CAddress& addr,
1910 const std::string& msg_type,
1911 std::span<const unsigned char> data,
1912 bool is_incoming)>
1914
1915#endif // BITCOIN_NET_H
int ret
int flags
Definition: bitcoin-tx.cpp:531
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
Stochastic address manager.
Definition: addrman.h:110
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:22
Definition: banman.h:64
A CService with information about it as peer.
Definition: protocol.h:387
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
Signals for UI communication.
Definition: interface_ui.h:22
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1870
const std::vector< CNode * > & Nodes() const
Definition: net.h:1894
NodesSnapshot(const CConnman &connman, bool shuffle) EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
Definition: net.h:1872
std::vector< CNode * > m_nodes_copy
Definition: net.h:1900
Group of private broadcast related members.
Definition: net.h:1211
Definition: net.h:1086
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1813
void AcceptConnection(const ListenSocket &hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:1752
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loading...
Definition: net.cpp:2558
std::condition_variable condMsgProc
Definition: net.h:1761
std::thread threadMessageHandler
Definition: net.h:1782
nSendBufferMaxSize
Definition: net.h:1134
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1404
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1645
CClientUIInterface * m_client_interface
Definition: net.h:1742
bool MaybePickPreferredNetwork(std::optional< Network > &network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
Definition: net.cpp:2577
std::reference_wrapper< AddrMan > addrman
Definition: net.h:1655
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition: net.cpp:1941
void DeleteNode(CNode *pnode)
Definition: net.cpp:3810
void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3272
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2471
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
int m_max_inbound
Definition: net.h:1738
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
class CConnman::PrivateBroadcast m_private_broadcast
uint16_t GetDefaultPort(Network net) const
Definition: net.cpp:3523
int m_max_outbound_block_relay
Definition: net.h:1733
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
bool AlreadyConnectedToAddress(const CNetAddr &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address.
Definition: net.cpp:353
bool ShouldRunInactivityChecks(const CNode &node, NodeClock::time_point now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:2038
void SetCaptureMessages(bool cap)
Definition: net.h:1159
std::thread threadI2PAcceptIncoming
Definition: net.h:1783
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
Definition: net.cpp:3834
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2476
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
int m_max_automatic_outbound
Definition: net.h:1737
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition: net.cpp:3926
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2293
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2991
bool AlreadyConnectedToAddressPort(const CService &addr_port) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address:port.
Definition: net.cpp:347
NodeId GetNewNodeId()
Definition: net.cpp:3518
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
std::atomic< NodeId > nLastNodeId
Definition: net.h:1667
bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given "host:port".
Definition: net.cpp:341
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int m_max_automatic_connections
Maximum number of automatic connections permitted, excluding manual connections but including inbound...
Definition: net.h:1721
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2284
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1745
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:4055
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1636
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:2258
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4021
std::thread threadDNSAddressSeed
Definition: net.h:1778
void ForEachNode(const NodeFn &func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.h:1295
void ASMapHealthCheck()
Definition: net.cpp:4319
bool AddConnection(const std::string &address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempts to open a connection.
Definition: net.cpp:1894
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
Definition: net.cpp:2156
void StartExtraBlockRelayPeers()
Definition: net.cpp:2482
const NetGroupManager & m_netgroupman
Definition: net.h:1656
std::vector< CAddress > m_anchors GUARDED_BY(m_anchors_mutex)
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:4028
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition: net.cpp:4283
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1807
unsigned int nPrevNodeCount
Definition: net.h:1668
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:580
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:4098
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3872
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:3005
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection.
Definition: net.cpp:378
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1641
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:1789
bool InitBinds(const Options &options)
Definition: net.cpp:3553
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:133
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1652
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:4278
Mutex m_total_bytes_sent_mutex
Definition: net.h:1631
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:3067
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:3534
bool EvictTxPeerIfFull(std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
If we are at capacity for inbound tx-relay peers, attempt to evict one.
Definition: net.cpp:2541
std::thread threadOpenConnections
Definition: net.h:1781
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition: net.h:1711
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition: net.cpp:3317
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition: net.cpp:3932
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2443
Mutex m_addr_fetches_mutex
Definition: net.h:1658
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1837
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1756
m_local_services
Definition: net.h:1123
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition: net.cpp:4040
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:4086
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:1608
std::queue< std::unique_ptr< i2p::sam::Session > > m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex)
A pool of created I2P SAM transient sessions that should be used instead of creating new ones in orde...
static bool NodeFullyConnected(const CNode *pnode)
Definition: net.cpp:4187
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition: net.h:1713
nReceiveFloodSize
Definition: net.h:1135
const CChainParams & m_params
Definition: net.h:1903
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
Definition: net.cpp:2571
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3898
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
bool InactivityCheck(const CNode &node, NodeClock::time_point now) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:2043
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4033
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition: net.h:1769
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition: net.cpp:1782
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2595
bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Try to find an inbound connection to evict.
Definition: net.cpp:1695
void GetNodeStats(std::vector< CNodeStats > &vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3937
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake.
Definition: net.h:1403
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:4263
std::thread threadPrivateBroadcast
Definition: net.h:1784
Mutex mutexMsgProc
Definition: net.h:1762
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3886
bool fAddressesInitialized
Definition: net.h:1654
std::vector< CAddress > GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return randomly selected addresses.
Definition: net.cpp:3823
void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2021
int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2525
std::thread threadOpenAddedConnections
Definition: net.h:1780
bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3951
Mutex m_added_nodes_mutex
Definition: net.h:1663
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2273
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4003
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition: net.cpp:3231
Mutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
int m_max_outbound_full_relay
Definition: net.h:1729
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1823
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int m_max_inbound_full_relay
Definition: net.h:1739
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4091
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition: net.h:1714
Mutex m_anchors_mutex
Addresses that were saved during the previous clean shutdown or when the network was deactivated.
Definition: net.h:1752
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3909
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3998
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1637
int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2509
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:4076
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:2127
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1633
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4203
bool GetUseAddrmanOutgoing() const
Definition: net.h:1185
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1665
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1776
bool m_use_addrman_outgoing
Definition: net.h:1741
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1647
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:1698
bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:359
std::function< void(CNode *)> NodeFn
Definition: net.h:1285
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:2096
NetEventsInterface * m_msgproc
Definition: net.h:1743
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1632
std::atomic< bool > fNetworkActive
Definition: net.h:1653
AssertLockNotHeld(m_reconnections_mutex)
void DumpAddresses()
Definition: net.cpp:2433
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:1801
Mutex m_nodes_mutex
Definition: net.h:1666
std::thread threadSocketHandler
Definition: net.h:1779
nMaxOutboundLimit
Definition: net.h:1139
int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2489
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:3386
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:32
An encapsulated private key.
Definition: key.h:46
Message header.
Definition: protocol.h:29
Network address.
Definition: netaddress.h:113
Transport protocol agnostic message container.
Definition: net.h:240
CNetMessage(CNetMessage &&)=default
CNetMessage(DataStream &&recv_in)
Definition: net.h:249
std::string m_type
Definition: net.h:247
DataStream m_recv
received message data
Definition: net.h:242
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition: net.h:684
bool IsFeelerConn() const
Definition: net.h:824
bool ExpectServicesFromConn() const
Definition: net.h:848
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:728
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:712
bool IsInboundConn() const
Definition: net.h:844
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:739
CountingSemaphoreGrant grantOutbound
Definition: net.h:747
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:779
NodeId GetId() const
Definition: net.h:929
bool IsManualConn() const
Definition: net.h:799
const std::string m_addr_name
Definition: net.h:726
CNode & operator=(const CNode &)=delete
const CService addrBind
Definition: net.h:725
void SetCommonVersion(int greatest_common_version)
Definition: net.h:954
std::list< CNetMessage > vRecvMsg
Definition: net.h:1012
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:1016
bool IsAddrFetchConn() const
Definition: net.h:828
uint64_t GetLocalNonce() const
Definition: net.h:933
const CAddress addr
Definition: net.h:723
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
Definition: net.h:717
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:750
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
bool IsBlockOnlyConn() const
Definition: net.h:820
int GetCommonVersion() const
Definition: net.h:959
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:795
Mutex m_subver_mutex
Definition: net.h:732
Mutex cs_vSend
Definition: net.h:708
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition: net.h:756
int GetRefCount() const
Definition: net.h:937
const util::NotNullUniquePtr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:688
void PongReceived(NodeClock::duration ping_time)
A ping-pong round trip has completed successfully. Update latest and minimum ping durations.
Definition: net.h:1000
Mutex m_msg_process_queue_mutex
Definition: net.h:1014
const ConnectionType m_conn_type
Definition: net.h:758
const size_t m_recv_flood_size
Definition: net.h:1011
const uint64_t nLocalHostNonce
Definition: net.h:1008
bool IsManualOrFullOutboundConn() const
Definition: net.h:803
bool IsPrivateBroadcastConn() const
Definition: net.h:832
std::shared_ptr< Sock > m_sock GUARDED_BY(m_sock_mutex)
Socket used for communication with the node.
const NetPermissionFlags m_permission_flags
Definition: net.h:690
Mutex m_addr_local_mutex
Definition: net.h:1020
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition: net.h:703
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:730
const NodeId id
Definition: net.h:1007
Mutex cs_vRecv
Definition: net.h:710
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:705
int AdvertisedVersion() const
Protocol version advertised in our VERSION message.
Definition: net.h:839
Mutex m_sock_mutex
Definition: net.h:709
const std::optional< Proxy > m_proxy_override
Proxy to use regardless of global proxy settings if reconnecting to this node.
Definition: net.h:720
std::list< CNetMessage > m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex)
std::deque< CSerializedNetMsg > vSendMsg GUARDED_BY(cs_vSend)
Messages still to be fed to m_transport->SetMessageToSend.
void Release()
Definition: net.h:974
std::string cleanSubVer GUARDED_BY(m_subver_mutex)
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
Definition: net.h:737
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:231
std::string addrLocal
Definition: net.h:219
NodeClock::duration m_min_ping_time
Definition: net.h:217
uint64_t nRecvBytes
Definition: net.h:213
uint32_t m_mapped_as
Definition: net.h:226
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:214
bool fInbound
Definition: net.h:206
uint64_t nSendBytes
Definition: net.h:211
ConnectionType m_conn_type
Definition: net.h:227
std::chrono::seconds m_last_tx_time
Definition: net.h:200
CAddress addr
Definition: net.h:221
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:212
CService addrBind
Definition: net.h:223
NodeClock::time_point m_last_recv
Definition: net.h:199
NodeClock::time_point m_last_send
Definition: net.h:198
NodeClock::duration m_last_ping_time
Definition: net.h:216
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:229
bool m_bip152_highbandwidth_from
Definition: net.h:210
bool m_bip152_highbandwidth_to
Definition: net.h:208
std::string m_addr_name
Definition: net.h:203
NodeClock::time_point m_connected
Definition: net.h:202
int nVersion
Definition: net.h:204
std::chrono::seconds m_last_block_time
Definition: net.h:201
Network m_network
Definition: net.h:225
NodeId nodeid
Definition: net.h:197
std::string cleanSubVer
Definition: net.h:205
NetPermissionFlags m_permission_flags
Definition: net.h:215
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:39
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
General SipHash-2-4 implementation.
Definition: siphash.h:99
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:165
Fast randomness source.
Definition: random.h:386
Different type to mark Mutex at global scope.
Definition: sync.h:142
Definition: init.h:13
Interface for message handling.
Definition: net.h:1042
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1045
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual bool ProcessMessages(CNode &node, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const =0
Callback to determine whether the given set of service flags are sufficient for a peer to be "relevan...
virtual bool SendMessages(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state)
Netgroup manager.
Definition: netgroup.h:17
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
Definition: netbase.h:61
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:35
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition: net.h:264
virtual ~Transport()=default
virtual Info GetInfo() const noexcept=0
Retrieve information about this transport.
std::tuple< std::span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
Definition: net.h:321
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition: net.h:386
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition: net.h:422
const NodeId m_node_id
Definition: net.h:381
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:416
CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex)
The data of the message currently being sent.
size_t m_bytes_sent GUARDED_BY(m_send_mutex)
How many bytes have been sent so far (from m_header_to_send, or from m_message_to_send....
Definition: net.h:424
unsigned int nDataPos GUARDED_BY(m_recv_mutex)
bool in_data GUARDED_BY(m_recv_mutex)
uint256 data_hash GUARDED_BY(m_recv_mutex)
std::vector< uint8_t > m_header_to_send GUARDED_BY(m_send_mutex)
The header of the message currently being sent.
const MessageStartChars m_magic_bytes
Definition: net.h:380
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition: net.h:388
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:408
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:382
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition: net.h:429
std::vector< uint8_t > m_send_buffer GUARDED_BY(m_send_mutex)
The send buffer; meaning is determined by m_send_state.
bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex)
Whether we've sent at least 24 bytes (which would trigger disconnect for V1 peers).
Definition: net.h:622
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:590
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:586
SendState
State type that controls the sender side.
Definition: net.h:555
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:592
Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex)
Lock for sending-side fields.
SendState m_send_state GUARDED_BY(m_send_mutex)
Current sender state.
std::string m_send_type GUARDED_BY(m_send_mutex)
Type of the message being sent.
const bool m_initiating
Whether we are the initiator side.
Definition: net.h:588
std::vector< uint8_t > m_recv_buffer GUARDED_BY(m_recv_mutex)
Receive buffer; meaning is determined by m_recv_state.
std::vector< uint8_t > m_send_garbage GUARDED_BY(m_send_mutex)
The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only).
uint32_t m_recv_len GUARDED_BY(m_recv_mutex)
In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >= BIP324Cipher::LENGTH_LEN.
Definition: net.h:598
uint32_t m_send_pos GUARDED_BY(m_send_mutex)
How many bytes from the send buffer have been sent so far.
Definition: net.h:614
RecvState m_recv_state GUARDED_BY(m_recv_mutex)
Current receiver state.
Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex)
Lock for receiver-side fields.
std::vector< uint8_t > m_recv_aad GUARDED_BY(m_recv_mutex)
AAD expected in next received packet (currently used only for garbage).
std::vector< uint8_t > m_recv_decode_buffer GUARDED_BY(m_recv_mutex)
Buffer to put decrypted contents in, for converting to CNetMessage.
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition: net.h:490
256-bit opaque blob.
Definition: uint256.h:196
NotNull is intended to be used to denote that a smart pointer type can not hold a nullptr value.
Definition: not_null.h:45
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ 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.
TransportProtocolType
Transport layer version.
@ V1
Unencrypted, plaintext protocol.
CClientUIInterface uiInterface
std::thread thread
Thread variable should be after other struct members so the thread does not start until the other mem...
std::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
Definition: miniscript.h:199
Definition: messages.h:21
static const unsigned char VERSION[]
Definition: netaddress.cpp:188
const std::string KEY
Definition: walletdb.cpp:44
constexpr bool DEFAULT_LISTEN
-listen default
Definition: net.h:80
uint16_t GetListenPort()
Definition: net.cpp:139
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition: net.h:92
constexpr unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:68
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:335
constexpr int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:76
constexpr bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:88
constexpr int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:72
void RemoveLocal(const CService &addr)
Definition: net.cpp:313
constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:60
constexpr size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:102
bool fDiscover
Definition: net.cpp:117
constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:100
constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:82
constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:90
void ClearLocal()
Definition: net.cpp:271
bool fListen
Definition: net.cpp:118
constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:66
constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:64
constexpr size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:101
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:121
const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:86
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:241
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:109
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:192
constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:98
constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition: net.h:78
constexpr bool DEFAULT_DNSSEED
Definition: net.h:99
int64_t NodeId
Definition: net.h:106
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:74
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:221
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:119
constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition: net.h:96
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
constexpr int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:94
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE, bool add_even_if_unreachable=false)
Definition: net.cpp:278
constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:62
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition: net.cpp:4373
constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT
Default percentage of inbound connection slots that tx-relaying peers can use.
Definition: net.h:84
@ LOCAL_NONE
Definition: net.h:157
@ LOCAL_MAPPED
Definition: net.h:160
@ LOCAL_MANUAL
Definition: net.h:161
@ LOCAL_MAX
Definition: net.h:163
@ LOCAL_BIND
Definition: net.h:159
@ LOCAL_IF
Definition: net.h:158
constexpr bool DEFAULT_V2_TRANSPORT
Definition: net.h:104
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:70
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:3455
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:324
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:33
ConnectionDirection
Definition: netbase.h:35
ServiceFlags
nServices flags
Definition: protocol.h:321
@ NODE_NONE
Definition: protocol.h:324
@ NODE_P2P_V2
Definition: protocol.h:342
constexpr int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
constexpr int PROTOCOL_VERSION
network protocol versioning
constexpr int WTXID_RELAY_VERSION
"wtxidrelay" message type for wtxid-based relay starts with this version
bool fInbound
Definition: net.h:117
CService resolvedAddress
Definition: net.h:115
AddedNodeParams m_params
Definition: net.h:114
bool fConnected
Definition: net.h:116
std::string m_added_node
Definition: net.h:109
bool m_use_v2transport
Definition: net.h:110
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1679
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1680
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1437
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1438
NetPermissionFlags m_permissions
Definition: net.h:1444
std::shared_ptr< Sock > sock
Definition: net.h:1436
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1104
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1102
std::vector< CService > onion_binds
Definition: net.h:1106
std::vector< std::string > m_specified_outgoing
Definition: net.h:1111
std::vector< std::string > m_added_nodes
Definition: net.h:1112
std::vector< CService > vBinds
Definition: net.h:1105
bool m_i2p_accept_incoming
Definition: net.h:1113
std::vector< std::string > vSeedNodes
Definition: net.h:1101
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:1109
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1103
Struct for entries in m_reconnections.
Definition: net.h:1841
std::optional< Proxy > proxy_override
Definition: net.h:1842
ConnectionType conn_type
Definition: net.h:1846
std::string destination
Definition: net.h:1845
CountingSemaphoreGrant grant
Definition: net.h:1844
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:131
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:140
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:139
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition: net.cpp:123
uint16_t nPort
Definition: net.h:185
int nScore
Definition: net.h:184
Version of the system clock that is mockable in the context of tests (via FakeNodeClock or SetMockTim...
Definition: time.h:27
std::chrono::time_point< NodeClock > time_point
Definition: time.h:28
static constexpr time_point epoch
Definition: time.h:33
std::optional< uint256 > session_id
Definition: net.h:271
TransportProtocolType transport_type
Definition: net.h:270
Bilingual messages:
Definition: translation.h:24
#define AssertLockNotHeld(cs)
Definition: sync.h:149
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())