Bitcoin Core 31.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
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/sock.h>
35
36#include <atomic>
37#include <condition_variable>
38#include <cstdint>
39#include <deque>
40#include <functional>
41#include <list>
42#include <map>
43#include <memory>
44#include <optional>
45#include <queue>
46#include <string_view>
47#include <thread>
48#include <unordered_set>
49#include <vector>
50
51class AddrMan;
52class BanMan;
53class CChainParams;
54class CNode;
55class CScheduler;
56struct bilingual_str;
57
59static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
61static constexpr auto FEELER_INTERVAL = 2min;
63static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
65static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
67static const unsigned int MAX_SUBVERSION_LENGTH = 256;
71static const int MAX_ADDNODE_CONNECTIONS = 8;
75static const int MAX_FEELER_CONNECTIONS = 1;
77static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};
79static const bool DEFAULT_LISTEN = true;
81static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
83static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
85static const bool DEFAULT_BLOCKSONLY = false;
87static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
89static constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
91static const int NUM_FDS_MESSAGE_CAPTURE = 1;
93static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
94
95static constexpr bool DEFAULT_FORCEDNSSEED{false};
96static constexpr bool DEFAULT_DNSSEED{true};
97static constexpr bool DEFAULT_FIXEDSEEDS{true};
98static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
99static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
100
101static constexpr bool DEFAULT_V2_TRANSPORT{true};
102
103typedef int64_t NodeId;
104
109
116
117class CNodeStats;
119
121 CSerializedNetMsg() = default;
124 // No implicit copying, only moves.
127
129 {
131 copy.data = data;
132 copy.m_type = m_type;
133 return copy;
134 }
135
136 std::vector<unsigned char> data;
137 std::string m_type;
138
140 size_t GetMemoryUsage() const noexcept;
141};
142
148void Discover();
149
150uint16_t GetListenPort();
151
152enum
153{
154 LOCAL_NONE, // unknown
155 LOCAL_IF, // address a local interface listens on
156 LOCAL_BIND, // address explicit bound to
157 LOCAL_MAPPED, // address reported by PCP
158 LOCAL_MANUAL, // address explicitly specified (-externalip=)
159
161};
162
164std::optional<CService> GetLocalAddrForPeer(CNode& node);
165
166void ClearLocal();
167bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
168bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
169void RemoveLocal(const CService& addr);
170bool SeenLocal(const CService& addr);
171bool IsLocal(const CService& addr);
172CService GetLocalAddress(const CNode& peer);
173
174extern bool fDiscover;
175extern bool fListen;
176
178extern std::string strSubVersion;
179
182 uint16_t nPort;
183};
184
186extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
187
188extern const std::string NET_MESSAGE_TYPE_OTHER;
189using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
190
192{
193public:
195 std::chrono::seconds m_last_send;
196 std::chrono::seconds m_last_recv;
197 std::chrono::seconds m_last_tx_time;
198 std::chrono::seconds m_last_block_time;
199 std::chrono::seconds m_connected;
200 std::string m_addr_name;
202 std::string cleanSubVer;
204 // We requested high bandwidth connection to peer
206 // Peer requested high bandwidth connection
209 uint64_t nSendBytes;
211 uint64_t nRecvBytes;
214 std::chrono::microseconds m_last_ping_time;
215 std::chrono::microseconds m_min_ping_time;
216 // Our address, as reported by the peer
217 std::string addrLocal;
218 // Address of this peer
220 // Bind address of our side of the connection
222 // Network the peer connected through
224 uint32_t m_mapped_as;
229 std::string m_session_id;
230};
231
232
238{
239public:
241 std::chrono::microseconds m_time{0};
242 uint32_t m_message_size{0};
243 uint32_t m_raw_message_size{0};
244 std::string m_type;
245
246 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
247 // Only one CNetMessage object will exist for the same message on either
248 // the receive or processing queue. For performance reasons we therefore
249 // delete the copy constructor and assignment operator to avoid the
250 // possibility of copying CNetMessage objects.
252 CNetMessage(const CNetMessage&) = delete;
255
257 size_t GetMemoryUsage() const noexcept;
258};
259
262public:
263 virtual ~Transport() = default;
264
265 struct Info
266 {
268 std::optional<uint256> session_id;
269 };
270
272 virtual Info GetInfo() const noexcept = 0;
273
274 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
275 // agnostic CNetMessage (message type & payload) objects.
276
278 virtual bool ReceivedMessageComplete() const = 0;
279
286 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
287
295 virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
296
297 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
298
305 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
306
314 using BytesToSend = std::tuple<
315 std::span<const uint8_t> /*to_send*/,
316 bool /*more*/,
317 const std::string& /*m_type*/
318 >;
319
355 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
356
363 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
364
366 virtual size_t GetSendMemoryUsage() const noexcept = 0;
367
368 // 3. Miscellaneous functions.
369
371 virtual bool ShouldReconnectV1() const noexcept = 0;
372};
373
374class V1Transport final : public Transport
375{
376private:
378 const NodeId m_node_id; // Only for logging
381 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
382 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
383 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
384 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
385 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
386 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
387 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
388
390 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
391 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
392
395 vRecv.clear();
396 hdrbuf.clear();
397 hdrbuf.resize(24);
398 in_data = false;
399 nHdrPos = 0;
400 nDataPos = 0;
401 data_hash.SetNull();
402 hasher.Reset();
403 }
404
406 {
408 if (!in_data) return false;
409 return hdr.nMessageSize == nDataPos;
410 }
411
415 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
419 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
421 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
422
423public:
424 explicit V1Transport(NodeId node_id) noexcept;
425
431
432 Info GetInfo() const noexcept override;
433
434 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
435 {
438 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
439 if (ret < 0) {
440 Reset();
441 } else {
442 msg_bytes = msg_bytes.subspan(ret);
443 }
444 return ret >= 0;
445 }
446
447 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
448
449 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
450 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
451 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
452 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
453 bool ShouldReconnectV1() const noexcept override { return false; }
454};
455
456class V2Transport final : public Transport
457{
458private:
462 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
463
466 static constexpr size_t V1_PREFIX_LEN = 16;
467
468 // The sender side and receiver side of V2Transport are state machines that are transitioned
469 // through, based on what has been received. The receive state corresponds to the contents of,
470 // and bytes received to, the receive buffer. The send state controls what can be appended to
471 // the send buffer and what can be sent from it.
472
487 enum class RecvState : uint8_t {
493 KEY_MAYBE_V1,
494
500 KEY,
501
508 GARB_GARBTERM,
509
518 VERSION,
519
525 APP,
526
531 APP_READY,
532
537 };
538
552 enum class SendState : uint8_t {
559 MAYBE_V1,
560
566 AWAITING_KEY,
567
574 READY,
575
580 };
581
585 const bool m_initiating;
590
592 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
595 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
597 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
599 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
601 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
603 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
604
607 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
609 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
611 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
613 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
615 std::string m_send_type GUARDED_BY(m_send_mutex);
617 SendState m_send_state GUARDED_BY(m_send_mutex);
619 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
620
622 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
624 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
626 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
628 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
630 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
632 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
634 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
636 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
638 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
639
640public:
641 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
642
648 V2Transport(NodeId nodeid, bool initiating) noexcept;
649
651 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
652
653 // Receive side functions.
654 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
655 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
656 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
657
658 // Send side functions.
659 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
660 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
661 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
662 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
663
664 // Miscellaneous functions.
665 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
666 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
667};
668
670{
672 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
673 bool prefer_evict = false;
675 bool use_v2transport = false;
676};
677
679class CNode
680{
681public:
684 const std::unique_ptr<Transport> m_transport;
685
687
696 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
697
699 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
701 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
703 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
707
708 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
709
710 std::atomic<std::chrono::seconds> m_last_send{0s};
711 std::atomic<std::chrono::seconds> m_last_recv{0s};
713 const std::chrono::seconds m_connected;
714 // Address of this peer
716 // Bind address of our side of the connection
718 const std::string m_addr_name;
720 const std::string m_dest;
722 const bool m_inbound_onion;
723 std::atomic<int> nVersion{0};
729 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
730 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
731 bool HasPermission(NetPermissionFlags permission) const {
733 }
734
735 std::atomic_bool fSuccessfullyConnected{false};
736 // Setting fDisconnect to true will cause the node to be disconnected the
737 // next time DisconnectNodes() runs
738 std::atomic_bool fDisconnect{false};
740 std::atomic<int> nRefCount{0};
741
742 const uint64_t nKeyedNetGroup;
743 std::atomic_bool fPauseRecv{false};
744 std::atomic_bool fPauseSend{false};
745
748 const uint64_t m_network_key;
749
751
755
761 std::optional<std::pair<CNetMessage, bool>> PollMessage()
763
765 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
767 {
768 mapSendBytesPerMsgType[msg_type] += sent_bytes;
769 }
770
772 switch (m_conn_type) {
775 return true;
781 return false;
782 } // no default case, so the compiler can warn about missing cases
783
784 assert(false);
785 }
786
790
791 bool IsManualConn() const {
793 }
794
796 {
797 switch (m_conn_type) {
803 return false;
806 return true;
807 } // no default case, so the compiler can warn about missing cases
808
809 assert(false);
810 }
811
812 bool IsBlockOnlyConn() const {
814 }
815
816 bool IsFeelerConn() const {
818 }
819
820 bool IsAddrFetchConn() const {
822 }
823
828
829 bool IsInboundConn() const {
831 }
832
834 switch (m_conn_type) {
838 return false;
843 return true;
844 } // no default case, so the compiler can warn about missing cases
845
846 assert(false);
847 }
848
859 Network ConnectedThroughNetwork() const;
860
862 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
863
864 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
865 std::atomic<bool> m_bip152_highbandwidth_to{false};
866 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
867 std::atomic<bool> m_bip152_highbandwidth_from{false};
868
870 std::atomic_bool m_has_all_wanted_services{false};
871
874 std::atomic_bool m_relays_txs{false};
875
878 std::atomic_bool m_bloom_filter_loaded{false};
879
885 std::atomic<std::chrono::seconds> m_last_block_time{0s};
886
891 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
892
894 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
895
898 std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
899
900 CNode(NodeId id,
901 std::shared_ptr<Sock> sock,
902 const CAddress& addrIn,
903 uint64_t nKeyedNetGroupIn,
904 uint64_t nLocalHostNonceIn,
905 const CService& addrBindIn,
906 const std::string& addrNameIn,
907 ConnectionType conn_type_in,
908 bool inbound_onion,
909 uint64_t network_key,
910 CNodeOptions&& node_opts = {});
911 CNode(const CNode&) = delete;
912 CNode& operator=(const CNode&) = delete;
913
914 NodeId GetId() const {
915 return id;
916 }
917
918 uint64_t GetLocalNonce() const {
919 return nLocalHostNonce;
920 }
921
922 int GetRefCount() const
923 {
924 assert(nRefCount >= 0);
925 return nRefCount;
926 }
927
937 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
938
939 void SetCommonVersion(int greatest_common_version)
940 {
942 m_greatest_common_version = greatest_common_version;
943 }
945 {
947 }
948
949 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
951 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
952
954 {
955 nRefCount++;
956 return this;
957 }
958
959 void Release()
960 {
961 nRefCount--;
962 }
963
964 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
965
967
968 std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
969
976 std::string LogIP(bool log_ip) const;
977
984 std::string DisconnectMsg(bool log_ip) const;
985
987 void PongReceived(std::chrono::microseconds ping_time) {
988 m_last_ping_time = ping_time;
989 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
990 }
991
992private:
993 const NodeId id;
994 const uint64_t nLocalHostNonce;
996
997 const size_t m_recv_flood_size;
998 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
999
1001 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1002 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1003
1004 // Our address, as reported by the peer
1007
1008 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1009 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1010
1021 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1022};
1023
1028{
1029public:
1032
1034 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1035
1037 virtual void FinalizeNode(const CNode& node) = 0;
1038
1043 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1044
1052 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1053
1061
1062
1063protected:
1069};
1070
1072{
1073public:
1074
1075 struct Options
1076 {
1081 BanMan* m_banman = nullptr;
1082 unsigned int nSendBufferMaxSize = 0;
1083 unsigned int nReceiveFloodSize = 0;
1084 uint64_t nMaxOutboundLimit = 0;
1086 std::vector<std::string> vSeedNodes;
1087 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1088 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1089 std::vector<NetWhitebindPermissions> vWhiteBinds;
1090 std::vector<CService> vBinds;
1091 std::vector<CService> onion_binds;
1096 std::vector<std::string> m_specified_outgoing;
1097 std::vector<std::string> m_added_nodes;
1102 };
1103
1105 {
1107
1108 m_local_services = connOptions.m_local_services;
1109 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1114 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1115 m_client_interface = connOptions.uiInterface;
1116 m_banman = connOptions.m_banman;
1117 m_msgproc = connOptions.m_msgproc;
1118 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1119 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1120 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1121 {
1122 LOCK(m_total_bytes_sent_mutex);
1123 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1124 }
1125 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1126 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1127 {
1129 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1130 // peer doesn't support it or immediately disconnects us for another reason.
1132 for (const std::string& added_node : connOptions.m_added_nodes) {
1133 m_added_node_params.push_back({added_node, use_v2transport});
1134 }
1135 }
1136 m_onion_binds = connOptions.onion_binds;
1137 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1138 whitelist_relay = connOptions.whitelist_relay;
1139 m_capture_messages = connOptions.m_capture_messages;
1140 }
1141
1142 // test only
1143 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1144
1145 CConnman(uint64_t seed0,
1146 uint64_t seed1,
1147 AddrMan& addrman,
1148 const NetGroupManager& netgroupman,
1149 const CChainParams& params,
1150 bool network_active = true,
1151 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1152
1153 ~CConnman();
1154
1156
1157 void StopThreads();
1165
1166 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1167 bool GetNetworkActive() const { return fNetworkActive; };
1169 void SetNetworkActive(bool active);
1170
1183 bool OpenNetworkConnection(const CAddress& addrConnect,
1184 bool fCountFailure,
1185 CountingSemaphoreGrant<>&& grant_outbound,
1186 const char* pszDest,
1187 ConnectionType conn_type,
1188 bool use_v2transport,
1189 const std::optional<Proxy>& proxy_override = std::nullopt)
1190 EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1191
1194 {
1195 public:
1204 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1205
1211
1221 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1222
1224 size_t NumToOpen() const;
1225
1231 void NumToOpenAdd(size_t n);
1232
1239 size_t NumToOpenSub(size_t n);
1240
1242 void NumToOpenWait() const;
1243
1244 protected:
1250 std::optional<Proxy> ProxyForIPv4or6() const;
1251
1253 std::atomic_size_t m_num_to_open{0};
1254
1255 friend struct ConnmanTestMsg;
1256 } m_private_broadcast;
1257
1258 bool CheckIncomingNonce(uint64_t nonce);
1259 void ASMapHealthCheck();
1260
1261 // alias for thread safety annotations only, not defined
1263
1264 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1265
1267
1268 using NodeFn = std::function<void(CNode*)>;
1269 void ForEachNode(const NodeFn& func)
1270 {
1272 for (auto&& node : m_nodes) {
1274 func(node);
1275 }
1276 };
1277
1278 void ForEachNode(const NodeFn& func) const
1279 {
1281 for (auto&& node : m_nodes) {
1283 func(node);
1284 }
1285 };
1286
1287 // Addrman functions
1299 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1314 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1315
1316 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1317 // a peer that is better than all our current peers.
1318 void SetTryNewOutboundPeer(bool flag);
1319 bool GetTryNewOutboundPeer() const;
1320
1321 void StartExtraBlockRelayPeers();
1322
1323 // Count the number of full-relay peer we have.
1324 int GetFullOutboundConnCount() const;
1325 // Return the number of outbound peers we have in excess of our target (eg,
1326 // if we previously called SetTryNewOutboundPeer(true), and have since set
1327 // to false, we may have extra peers that we wish to disconnect). This may
1328 // return a value less than (num_outbound_connections - num_outbound_slots)
1329 // in cases where some outbound connections are not yet fully connected, or
1330 // not yet fully disconnected.
1331 int GetExtraFullOutboundCount() const;
1332 // Count the number of block-relay-only peers we have over our limit.
1333 int GetExtraBlockRelayCount() const;
1334
1335 bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1336 bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1337 bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1338 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1339
1353 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1354
1355 size_t GetNodeCount(ConnectionDirection) const;
1356 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1357 uint32_t GetMappedAS(const CNetAddr& addr) const;
1358 void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1359 bool DisconnectNode(std::string_view node);
1360 bool DisconnectNode(const CSubNet& subnet);
1361 bool DisconnectNode(const CNetAddr& addr);
1362 bool DisconnectNode(NodeId id);
1363
1370 ServiceFlags GetLocalServices() const;
1371
1376
1377 uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1378 std::chrono::seconds GetMaxOutboundTimeframe() const;
1379
1383 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1384
1387 uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1388
1389 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1390
1391 uint64_t GetTotalBytesRecv() const;
1392 uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1393
1395 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1396
1397 void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1398
1400 bool ShouldRunInactivityChecks(const CNode& node, std::chrono::microseconds now) const;
1401
1402 bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1403
1404private:
1406 public:
1407 std::shared_ptr<Sock> sock;
1409 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1410 : sock{sock_}, m_permissions{permissions_}
1411 {
1412 }
1413
1414 private:
1416 };
1417
1421
1422 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1423 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1424 bool InitBinds(const Options& options);
1425
1427 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1433 void AcceptConnection(const ListenSocket& hListenSocket);
1434
1443 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1444 NetPermissionFlags permission_flags,
1445 const CService& addr_bind,
1446 const CService& addr);
1447
1451 bool InactivityCheck(const CNode& node, std::chrono::microseconds now) const;
1452
1458 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1459
1464
1470 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1471 const Sock::EventsPerSock& events_per_sock)
1473
1478 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1479
1482
1483 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1484
1492 bool AlreadyConnectedToHost(std::string_view host) const;
1493
1501 bool AlreadyConnectedToAddressPort(const CService& addr_port) const;
1502
1506 bool AlreadyConnectedToAddress(const CNetAddr& addr) const;
1507
1509
1520 CNode* ConnectNode(CAddress addrConnect,
1521 const char* pszDest,
1522 bool fCountFailure,
1523 ConnectionType conn_type,
1524 bool use_v2transport,
1525 const std::optional<Proxy>& proxy_override)
1527
1528 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1529
1530 void DeleteNode(CNode* pnode);
1531
1533
1535 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1536
1537 void DumpAddresses();
1538
1539 // Network stats
1540 void RecordBytesRecv(uint64_t bytes);
1542
1547 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1548
1553
1564 bool MaybePickPreferredNetwork(std::optional<Network>& network);
1565
1566 // Whether the node should be passed out in ForEach* callbacks
1567 static bool NodeFullyConnected(const CNode* pnode);
1568
1569 uint16_t GetDefaultPort(Network net) const;
1570 uint16_t GetDefaultPort(const std::string& addr) const;
1571
1572 // Network usage totals
1574 std::atomic<uint64_t> nTotalBytesRecv{0};
1575 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1576
1577 // outbound limit & stats
1578 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1579 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1581
1582 // P2P timeout in seconds
1583 std::chrono::seconds m_peer_connect_timeout;
1584
1585 // Whitelisted ranges. Any node connecting from these is automatically
1586 // whitelisted (as well as those connecting to whitelisted binds).
1587 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1588 // Whitelisted ranges for outgoing connections.
1589 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1590
1591 unsigned int nSendBufferMaxSize{0};
1592 unsigned int nReceiveFloodSize{0};
1593
1594 std::vector<ListenSocket> vhListenSocket;
1595 std::atomic<bool> fNetworkActive{true};
1597 std::reference_wrapper<AddrMan> addrman;
1599 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1601
1602 // connection string and whether to use v2 p2p
1603 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1604
1606 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1607 std::list<CNode*> m_nodes_disconnected;
1609 std::atomic<NodeId> nLastNodeId{0};
1610 unsigned int nPrevNodeCount{0};
1611
1612 // Stores number of full-tx connections (outbound and manual) per network
1613 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1614
1622 std::vector<CAddress> m_addrs_response_cache;
1623 std::chrono::microseconds m_cache_entry_expiration{0};
1624 };
1625
1640 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1641
1653 std::atomic<ServiceFlags> m_local_services;
1654
1655 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1656 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1657
1664
1665 /*
1666 * Maximum number of peers by connection type. Might vary from defaults
1667 * based on -maxconnections init value.
1668 */
1669
1670 // How many full-relay (tx, block, addr) outbound peers we want
1672
1673 // How many block-relay only outbound peers we want
1674 // We do not relay tx or addr messages with these peers
1676
1681
1687
1692 std::vector<CAddress> m_anchors;
1693
1695 const uint64_t nSeed0, nSeed1;
1696
1698 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1699
1700 std::condition_variable condMsgProc;
1702 std::atomic<bool> flagInterruptMsgProc{false};
1703
1708 const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1709
1715 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1716
1724
1729
1734 std::atomic_bool m_start_extra_block_relay_peers{false};
1735
1740 std::vector<CService> m_onion_binds;
1741
1747
1753
1758
1763
1771 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1772
1777
1787
1791 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1792
1795
1800 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1801
1807 {
1808 public:
1809 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1810 {
1811 {
1812 LOCK(connman.m_nodes_mutex);
1813 m_nodes_copy = connman.m_nodes;
1814 for (auto& node : m_nodes_copy) {
1815 node->AddRef();
1816 }
1817 }
1818 if (shuffle) {
1819 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1820 }
1821 }
1822
1824 {
1825 for (auto& node : m_nodes_copy) {
1826 node->Release();
1827 }
1828 }
1829
1830 const std::vector<CNode*>& Nodes() const
1831 {
1832 return m_nodes_copy;
1833 }
1834
1835 private:
1836 std::vector<CNode*> m_nodes_copy;
1837 };
1838
1840
1841 friend struct ConnmanTestMsg;
1842};
1843
1845extern std::function<void(const CAddress& addr,
1846 const std::string& msg_type,
1847 std::span<const unsigned char> data,
1848 bool is_incoming)>
1850
1851#endif // BITCOIN_NET_H
int ret
int flags
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition check.h:125
Stochastic address manager.
Definition addrman.h:89
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition bip324.h:20
A CService with information about it as peer.
Definition protocol.h:367
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:77
Signals for UI communication.
const std::vector< CNode * > & Nodes() const
Definition net.h:1830
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition net.h:1809
std::vector< CNode * > m_nodes_copy
Definition net.h:1836
Group of private broadcast related members.
Definition net.h:1194
std::atomic_bool m_outbound_tor_ok_at_least_once
Remember if we ever established at least one outbound connection to a Tor peer, including sending and...
Definition net.h:1204
std::atomic_size_t m_num_to_open
Number of ConnectionType::PRIVATE_BROADCAST connections to open.
Definition net.h:1253
friend struct ConnmanTestMsg
Definition net.h:1255
std::counting_semaphore m_sem_conn_max
Semaphore used to guard against opening too many connections.
Definition net.h:1210
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:2490
std::condition_variable condMsgProc
Definition net.h:1700
std::thread threadMessageHandler
Definition net.h:1721
void ForEachNode(const NodeFn &func)
Definition net.h:1269
nSendBufferMaxSize
Definition net.h:1118
void RemoveLocalServices(ServiceFlags services)
Definition net.h:1375
bool AlreadyConnectedToHost(std::string_view host) const
Determine whether we're already connected to a given "host:port".
Definition net.cpp:335
std::reference_wrapper< AddrMan > addrman
Definition net.h:1597
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition net.cpp:3124
void ForEachNode(const NodeFn &func) const
Definition net.h:1278
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition net.cpp:4118
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition net.cpp:1909
m_max_outbound_full_relay
Definition net.h:1110
void DeleteNode(CNode *pnode)
Definition net.cpp:3670
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition net.cpp:1684
bool GetNetworkActive() const
Definition net.h:1167
whitelist_relay
Definition net.h:1138
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
Definition net.h:1800
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
uint16_t GetDefaultPort(Network net) const
Definition net.cpp:3395
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Attempt reconnections, if m_reconnections non-empty.
Definition net.cpp:4143
void SetCaptureMessages(bool cap)
Definition net.h:1143
std::thread threadI2PAcceptIncoming
Definition net.h:1722
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_unused_i2p_sessions_mutex)
Open a new P2P connection.
Definition net.cpp:372
std::atomic< bool > flagInterruptMsgProc
Definition net.h:1702
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition net.cpp:1761
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2255
m_onion_binds
Definition net.h:1136
NodeId GetNewNodeId()
Definition net.cpp:3390
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
m_capture_messages
Definition net.h:1139
std::atomic< NodeId > nLastNodeId
Definition net.h:1609
m_max_automatic_outbound
Definition net.h:1112
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1578
std::thread threadDNSAddressSeed
Definition net.h:1717
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:2120
void ThreadI2PAcceptIncoming()
Definition net.cpp:3163
const uint64_t nSeed1
Definition net.h:1695
const NetGroupManager & m_netgroupman
Definition net.h:1598
m_banman
Definition net.h:1116
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition net.h:1692
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition net.cpp:4136
friend struct ConnmanTestMsg
Definition net.h:1841
unsigned int nPrevNodeCount
Definition net.h:1610
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition net.cpp:572
void NotifyNumConnectionsChanged()
Definition net.cpp:1988
ServiceFlags GetLocalServices() const
Definition net.cpp:3954
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:1728
bool InitBinds(const Options &options)
Definition net.cpp:3425
vWhitelistedRangeOutgoing
Definition net.h:1126
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition net.cpp:132
std::vector< ListenSocket > vhListenSocket
Definition net.h:1594
bool AlreadyConnectedToAddress(const CNetAddr &addr) const
Determine whether we're already connected to a given address.
Definition net.cpp:347
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition net.cpp:2896
Mutex m_total_bytes_sent_mutex
Definition net.h:1573
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:2969
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition net.cpp:3406
std::thread threadOpenConnections
Definition net.h:1720
int m_max_feeler
Definition net.h:1678
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
Definition net.h:1159
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2405
Mutex m_addr_fetches_mutex
Definition net.h:1600
m_peer_connect_timeout
Definition net.h:1120
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition net.h:1776
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:3459
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1695
m_local_services
Definition net.h:1108
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition net.cpp:2092
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
Definition net.cpp:3896
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:1597
RecursiveMutex m_nodes_mutex
Definition net.h:1608
m_max_outbound_block_relay
Definition net.h:1111
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:4042
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition net.h:1655
m_client_interface
Definition net.h:1115
nReceiveFloodSize
Definition net.h:1119
const CChainParams & m_params
Definition net.h:1839
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
whitelist_forcerelay
Definition net.h:1137
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition net.h:1708
void AddLocalServices(ServiceFlags services)
Definition net.h:1374
m_max_automatic_connections
Definition net.h:1109
std::thread threadPrivateBroadcast
Definition net.h:1723
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2525
m_msgproc
Definition net.h:1117
Mutex mutexMsgProc
Definition net.h:1701
m_max_inbound
Definition net.h:1113
bool fAddressesInitialized
Definition net.h:1596
void StopThreads()
Definition net.cpp:3613
std::thread threadOpenAddedConnections
Definition net.h:1719
Mutex m_added_nodes_mutex
Definition net.h:1605
vWhitelistedRangeIncoming
Definition net.h:1125
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:2235
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:3859
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition net.h:1762
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition net.h:1656
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition net.cpp:3206
bool MaybePickPreferredNetwork(std::optional< Network > &network)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
Definition net.cpp:2509
void RecordBytesRecv(uint64_t bytes)
Definition net.cpp:3854
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1579
void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
Definition net.cpp:3633
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1575
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4058
bool GetUseAddrmanOutgoing() const
Definition net.h:1168
int m_max_addnode
Definition net.h:1677
std::list< CNode * > m_nodes_disconnected
Definition net.h:1607
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1715
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:1640
std::function< void(CNode *)> NodeFn
Definition net.h:1268
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition net.cpp:2061
std::atomic< uint64_t > nTotalBytesRecv
Definition net.h:1574
std::atomic< bool > fNetworkActive
Definition net.h:1595
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition net.h:1734
m_use_addrman_outgoing
Definition net.h:1114
bool InactivityCheck(const CNode &node, std::chrono::microseconds now) const
Return true if the peer is inactive and should be disconnected.
Definition net.cpp:2008
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition net.cpp:2222
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams &params, bool network_active=true, std::shared_ptr< CThreadInterrupt > interrupt_net=std::make_shared< CThreadInterrupt >())
Definition net.cpp:3369
void DumpAddresses()
Definition net.cpp:2395
bool AlreadyConnectedToAddressPort(const CService &addr_port) const
Determine whether we're already connected to a given address:port.
Definition net.cpp:341
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
std::thread threadSocketHandler
Definition net.h:1718
nMaxOutboundLimit
Definition net.h:1123
void AcceptConnection(const ListenSocket &hListenSocket)
Definition net.cpp:1733
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition net.cpp:3274
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:24
An encapsulated private key.
Definition key.h:36
Message header.
Definition protocol.h:29
Network address.
Definition netaddress.h:113
Transport protocol agnostic message container.
Definition net.h:238
CNetMessage(CNetMessage &&)=default
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:127
uint32_t m_message_size
size of the payload
Definition net.h:242
std::chrono::microseconds m_time
time of message receipt
Definition net.h:241
CNetMessage(DataStream &&recv_in)
Definition net.h:246
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition net.h:243
std::string m_type
Definition net.h:244
DataStream m_recv
received message data
Definition net.h:240
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition net.h:680
bool IsFeelerConn() const
Definition net.h:816
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition net.h:713
bool ExpectServicesFromConn() const
Definition net.h:833
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition net.h:720
std::atomic< int > nVersion
Definition net.h:723
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
std::atomic_bool m_has_all_wanted_services
Whether this peer provides all services that we want.
Definition net.h:870
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition net.h:708
bool IsInboundConn() const
Definition net.h:829
bool HasPermission(NetPermissionFlags permission) const
Definition net.h:731
CountingSemaphoreGrant grantOutbound
Definition net.h:739
std::atomic_bool fPauseRecv
Definition net.h:743
bool IsOutboundOrBlockRelayConn() const
Definition net.h:771
NodeId GetId() const
Definition net.h:914
bool IsManualConn() const
Definition net.h:791
const std::string m_addr_name
Definition net.h:718
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition net.cpp:614
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition net.h:968
const CService addrBind
Definition net.h:717
void SetCommonVersion(int greatest_common_version)
Definition net.h:939
std::atomic< bool > m_bip152_highbandwidth_to
Definition net.h:865
std::list< CNetMessage > vRecvMsg
Definition net.h:998
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition net.h:874
std::atomic< bool > m_bip152_highbandwidth_from
Definition net.h:867
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition net.h:987
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition net.h:735
const bool m_prefer_evict
Definition net.h:730
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition net.h:1002
bool IsAddrFetchConn() const
Definition net.h:820
uint64_t GetLocalNonce() const
Definition net.h:918
const CAddress addr
Definition net.h:715
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition net.h:742
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
std::atomic< int > nRefCount
Definition net.h:740
std::atomic< int > m_greatest_common_version
Definition net.h:995
bool IsBlockOnlyConn() const
Definition net.h:812
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CService &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, uint64_t network_key, CNodeOptions &&node_opts={})
Definition net.cpp:3968
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition net.cpp:4011
int GetCommonVersion() const
Definition net.h:944
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition net.h:787
Mutex m_subver_mutex
Definition net.h:724
Mutex cs_vSend
Definition net.h:704
CNode * AddRef()
Definition net.h:953
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition net.h:748
std::atomic_bool fPauseSend
Definition net.h:744
int GetRefCount() const
Definition net.h:922
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
Definition net.cpp:4028
Mutex m_msg_process_queue_mutex
Definition net.h:1000
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition net.h:878
const ConnectionType m_conn_type
Definition net.h:750
const size_t m_recv_flood_size
Definition net.h:997
const uint64_t nLocalHostNonce
Definition net.h:994
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
Definition net.h:894
bool IsManualOrFullOutboundConn() const
Definition net.h:795
bool IsPrivateBroadcastConn() const
Definition net.h:824
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition net.h:684
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:686
Mutex m_addr_local_mutex
Definition net.h:1006
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition net.h:699
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition net.h:722
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
Definition net.h:898
const NodeId id
Definition net.h:993
void AccountForSentBytes(const std::string &msg_type, size_t sent_bytes) EXCLUSIVE_LOCKS_REQUIRED(cs_vSend)
Account for the total size of a sent message in the per msg type connection stats.
Definition net.h:765
Mutex cs_vRecv
Definition net.h:706
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
Definition net.h:885
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition net.h:701
Mutex m_sock_mutex
Definition net.h:705
std::atomic_bool fDisconnect
Definition net.h:738
std::atomic< std::chrono::seconds > m_last_recv
Definition net.h:711
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
Definition net.h:891
std::atomic< std::chrono::seconds > m_last_send
Definition net.h:710
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:959
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:729
std::string m_session_id
BIP324 session id string in hex, if any.
Definition net.h:229
std::string addrLocal
Definition net.h:217
uint64_t nRecvBytes
Definition net.h:211
std::chrono::microseconds m_last_ping_time
Definition net.h:214
uint32_t m_mapped_as
Definition net.h:224
mapMsgTypeSize mapRecvBytesPerMsgType
Definition net.h:212
bool fInbound
Definition net.h:203
uint64_t nSendBytes
Definition net.h:209
std::chrono::seconds m_last_recv
Definition net.h:196
ConnectionType m_conn_type
Definition net.h:225
std::chrono::seconds m_last_send
Definition net.h:195
std::chrono::seconds m_last_tx_time
Definition net.h:197
CAddress addr
Definition net.h:219
mapMsgTypeSize mapSendBytesPerMsgType
Definition net.h:210
std::chrono::microseconds m_min_ping_time
Definition net.h:215
CService addrBind
Definition net.h:221
TransportProtocolType m_transport_type
Transport protocol type.
Definition net.h:227
std::chrono::seconds m_connected
Definition net.h:199
bool m_bip152_highbandwidth_from
Definition net.h:207
bool m_bip152_highbandwidth_to
Definition net.h:205
std::string m_addr_name
Definition net.h:200
int nVersion
Definition net.h:201
std::chrono::seconds m_last_block_time
Definition net.h:198
Network m_network
Definition net.h:223
NodeId nodeid
Definition net.h:194
std::string cleanSubVer
Definition net.h:202
int m_starting_height
Definition net.h:208
NetPermissionFlags m_permission_flags
Definition net.h:213
Simple class for background tasks that should be run periodically or once "after a while".
Definition scheduler.h:40
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:530
General SipHash-2-4 implementation.
Definition siphash.h:27
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:133
Fast randomness source.
Definition random.h:386
Different type to mark Mutex at global scope.
Definition sync.h:134
Interface for message handling.
Definition net.h:1028
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:1031
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)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition sock.h:28
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition net.h:261
virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept=0
Get bytes to send on the wire, if any, along with other information about it.
virtual size_t GetSendMemoryUsage() const noexcept=0
Return the memory usage of this transport attributable to buffered data to send.
virtual bool ReceivedBytes(std::span< const uint8_t > &msg_bytes)=0
Feed wire bytes to the transport.
virtual void MarkBytesSent(size_t bytes_sent) noexcept=0
Report how many bytes returned by the last GetBytesToSend() have been sent.
virtual bool ShouldReconnectV1() const noexcept=0
Whether upon disconnections, a reconnect with V1 is warranted.
virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool &reject_message)=0
Retrieve a completed message from transport.
virtual bool ReceivedMessageComplete() const =0
Returns true if the current message is complete (so GetReceivedMessage can be called).
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:314
virtual bool SetMessageToSend(CSerializedNetMsg &msg) noexcept=0
Set the next message to send.
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition net.h:383
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition net.h:419
int readData(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:771
const NodeId m_node_id
Definition net.h:378
Mutex m_send_mutex
Lock for sending state.
Definition net.h:413
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:421
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:377
const uint256 & GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:789
int readHeader(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:728
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition net.h:385
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:405
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Feed wire bytes to the transport.
Definition net.h:434
V1Transport(NodeId node_id) noexcept
Definition net.cpp:716
void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:393
bool ShouldReconnectV1() const noexcept override
Whether upon disconnections, a reconnect with V1 is warranted.
Definition net.h:453
Mutex m_recv_mutex
Lock for receive state.
Definition net.h:379
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:426
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:619
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
Definition net.cpp:1528
static constexpr uint32_t MAX_GARBAGE_LEN
Definition net.h:641
const NodeId m_nodeid
NodeId (for debug logging).
Definition net.h:587
BIP324Cipher m_cipher
Cipher state.
Definition net.h:583
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
Definition net.cpp:1567
void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state.
Definition net.cpp:1077
SendState
State type that controls the sender side.
Definition net.h:552
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition net.h:589
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.
static constexpr size_t V1_PREFIX_LEN
The length of the V1 prefix to match bytes initially received by responders with to determine if thei...
Definition net.h:466
std::string m_send_type GUARDED_BY(m_send_mutex)
Type of the message being sent.
bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in VERSION/APP state.
Definition net.cpp:1202
bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY state.
Definition net.cpp:1115
const bool m_initiating
Whether we are the initiator side.
Definition net.h:585
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
Definition net.cpp:1576
std::vector< uint8_t > m_recv_buffer GUARDED_BY(m_recv_mutex)
Receive buffer; meaning is determined by m_recv_state.
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
Definition net.cpp:1511
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).
bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in GARB_GARBTERM state.
Definition net.cpp:1175
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:595
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:611
RecvState m_recv_state GUARDED_BY(m_recv_mutex)
Current receiver state.
bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
Definition net.cpp:1068
CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Definition net.cpp:1450
Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex)
Lock for receiver-side fields.
static constexpr std::array< std::byte, 0 > VERSION_CONTENTS
Contents of the version packet to send.
Definition net.h:462
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Feed wire bytes to the transport.
Definition net.cpp:1320
bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Whether upon disconnections, a reconnect with V1 is warranted.
Definition net.cpp:1550
std::vector< uint8_t > m_recv_aad GUARDED_BY(m_recv_mutex)
AAD expected in next received packet (currently used only for garbage).
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition net.cpp:1479
V2Transport(NodeId nodeid, bool initiating) noexcept
Construct a V2 transport with securely generated random keys.
Definition net.cpp:1013
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:487
256-bit opaque blob.
Definition uint256.h:195
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.
std::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
Definition common.h:29
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:108
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:118
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:4224
uint16_t GetListenPort()
Definition net.cpp:138
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:81
static constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition net.h:89
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:329
void RemoveLocal(const CService &addr)
Definition net.cpp:310
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:67
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition net.h:59
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:71
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition net.cpp:277
bool fDiscover
Definition net.cpp:116
static const size_t DEFAULT_MAXSENDBUFFER
Definition net.h:99
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:91
static constexpr bool DEFAULT_FIXEDSEEDS
Definition net.h:97
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:85
void ClearLocal()
Definition net.cpp:270
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:65
bool fListen
Definition net.cpp:117
@ LOCAL_NONE
Definition net.h:154
@ LOCAL_MAPPED
Definition net.h:157
@ LOCAL_MANUAL
Definition net.h:158
@ LOCAL_MAX
Definition net.h:160
@ LOCAL_BIND
Definition net.h:156
@ LOCAL_IF
Definition net.h:155
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:63
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:98
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition net.cpp:120
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition net.h:83
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:240
std::map< std::string, uint64_t > mapMsgTypeSize
Definition net.h:189
static constexpr bool DEFAULT_FORCEDNSSEED
Definition net.h:95
static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition net.h:77
static constexpr bool DEFAULT_DNSSEED
Definition net.h:96
int64_t NodeId
Definition net.h:103
CService GetLocalAddress(const CNode &peer)
Definition net.cpp:220
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition net.h:75
static const bool DEFAULT_LISTEN
-listen default
Definition net.h:79
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition net.h:93
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition net.h:61
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition net.h:87
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:69
static constexpr bool DEFAULT_V2_TRANSPORT
Definition net.h:101
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:73
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:3343
bool SeenLocal(const CService &addr)
vote for a local address
Definition net.cpp:318
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:33
ServiceFlags
nServices flags
Definition protocol.h:309
@ NODE_NONE
Definition protocol.h:312
@ NODE_P2P_V2
Definition protocol.h:330
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
bool fInbound
Definition net.h:114
CService resolvedAddress
Definition net.h:112
AddedNodeParams m_params
Definition net.h:111
bool fConnected
Definition net.h:113
std::string m_added_node
Definition net.h:106
bool m_use_v2transport
Definition net.h:107
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1621
std::chrono::microseconds m_cache_entry_expiration
Definition net.h:1623
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1622
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition net.h:1408
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition net.h:1409
NetPermissionFlags m_permissions
Definition net.h:1415
std::shared_ptr< Sock > sock
Definition net.h:1407
unsigned int nReceiveFloodSize
Definition net.h:1083
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:1089
uint64_t nMaxOutboundLimit
Definition net.h:1084
CClientUIInterface * uiInterface
Definition net.h:1079
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1087
std::vector< CService > onion_binds
Definition net.h:1091
std::vector< std::string > m_specified_outgoing
Definition net.h:1096
bool whitelist_relay
Definition net.h:1100
NetEventsInterface * m_msgproc
Definition net.h:1080
std::vector< std::string > m_added_nodes
Definition net.h:1097
int64_t m_peer_connect_timeout
Definition net.h:1085
std::vector< CService > vBinds
Definition net.h:1090
bool m_capture_messages
Definition net.h:1101
unsigned int nSendBufferMaxSize
Definition net.h:1082
int m_max_automatic_connections
Definition net.h:1078
ServiceFlags m_local_services
Definition net.h:1077
bool m_i2p_accept_incoming
Definition net.h:1098
std::vector< std::string > vSeedNodes
Definition net.h:1086
BanMan * m_banman
Definition net.h:1081
bool m_use_addrman_outgoing
Definition net.h:1095
bool whitelist_forcerelay
Definition net.h:1099
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:1094
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1088
Struct for entries in m_reconnections.
Definition net.h:1780
ConnectionType conn_type
Definition net.h:1784
std::string destination
Definition net.h:1783
CountingSemaphoreGrant grant
Definition net.h:1782
NetPermissionFlags permission_flags
Definition net.h:671
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition net.h:672
bool prefer_evict
Definition net.h:673
bool use_v2transport
Definition net.h:675
size_t recv_flood_size
Definition net.h:674
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition net.h:128
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition net.h:137
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition net.h:136
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:122
uint16_t nPort
Definition net.h:182
std::optional< uint256 > session_id
Definition net.h:268
TransportProtocolType transport_type
Definition net.h:267
Bilingual messages:
Definition translation.h:24
#define AssertLockNotHeld(cs)
Definition sync.h:141
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
Definition sync.h:123
AnnotatedMixin< std::recursive_mutex > RecursiveMutex
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition sync.h:120
#define LOCK(cs)
Definition sync.h:258
#define WITH_LOCK(cs, code)
Definition sync.h:289
#define AssertLockHeld(cs)
Definition sync.h:136
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define LOCK_RETURNED(x)
assert(!tx.IsCoinBase())