Bitcoin Core 32.1.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
59inline constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
61inline constexpr auto FEELER_INTERVAL = 2min;
63inline constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
65inline constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
67inline constexpr unsigned int MAX_SUBVERSION_LENGTH = 256;
69inline constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;
71inline constexpr int MAX_ADDNODE_CONNECTIONS = 8;
73inline constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;
75inline constexpr int MAX_FEELER_CONNECTIONS = 1;
77inline constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};
79inline constexpr bool DEFAULT_LISTEN = true;
81inline constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS{200};
83inline constexpr int MAX_PEER_CONNECTIONS{2'000};
85inline constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT{50};
87inline const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
89inline constexpr bool DEFAULT_BLOCKSONLY = false;
91inline constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
93inline constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
95inline constexpr int NUM_FDS_MESSAGE_CAPTURE = 1;
97inline constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
98
99inline constexpr bool DEFAULT_FORCEDNSSEED{false};
100inline constexpr bool DEFAULT_DNSSEED{true};
101inline constexpr bool DEFAULT_FIXEDSEEDS{true};
102inline constexpr size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
103inline constexpr size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
104
105inline constexpr bool DEFAULT_V2_TRANSPORT{true};
106
107typedef int64_t NodeId;
108
113
120
121class CNodeStats;
123
125 CSerializedNetMsg() = default;
128 // No implicit copying, only moves.
131
133 {
135 copy.data = data;
136 copy.m_type = m_type;
137 return copy;
138 }
139
140 std::vector<unsigned char> data;
141 std::string m_type;
142
144 size_t GetMemoryUsage() const noexcept;
145};
146
152void Discover();
153
154uint16_t GetListenPort();
155
156enum
157{
158 LOCAL_NONE, // unknown
159 LOCAL_IF, // address a local interface listens on
160 LOCAL_BIND, // address explicit bound to
161 LOCAL_MAPPED, // address reported by PCP
162 LOCAL_MANUAL, // address explicitly specified (-externalip=)
163
165};
166
168std::optional<CService> GetLocalAddrForPeer(CNode& node);
169
170void ClearLocal();
171bool AddLocal(const CService& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
172bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
173void RemoveLocal(const CService& addr);
174bool SeenLocal(const CService& addr);
175bool IsLocal(const CService& addr);
176CService GetLocalAddress(const CNode& peer);
177
178extern bool fDiscover;
179extern bool fListen;
180
182extern std::string strSubVersion;
183
186 uint16_t nPort;
187};
188
190extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
191
192extern const std::string NET_MESSAGE_TYPE_OTHER;
193using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
194
196{
197public:
201 std::chrono::seconds m_last_tx_time;
202 std::chrono::seconds m_last_block_time;
204 std::string m_addr_name;
206 std::string cleanSubVer;
208 // We requested high bandwidth connection to peer
210 // Peer requested high bandwidth connection
212 uint64_t nSendBytes;
214 uint64_t nRecvBytes;
217 NodeClock::duration m_last_ping_time;
218 NodeClock::duration m_min_ping_time;
219 // Our address, as reported by the peer
220 std::string addrLocal;
221 // Address of this peer
223 // Bind address of our side of the connection
225 // Network the peer connected through
227 uint32_t m_mapped_as;
232 std::string m_session_id;
233};
234
235
241{
242public:
246 uint32_t m_message_size{0};
247 uint32_t m_raw_message_size{0};
248 std::string m_type;
249
250 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
251 // Only one CNetMessage object will exist for the same message on either
252 // the receive or processing queue. For performance reasons we therefore
253 // delete the copy constructor and assignment operator to avoid the
254 // possibility of copying CNetMessage objects.
256 CNetMessage(const CNetMessage&) = delete;
259
261 size_t GetMemoryUsage() const noexcept;
262};
263
266public:
267 virtual ~Transport() = default;
268
269 struct Info
270 {
272 std::optional<uint256> session_id;
273 };
274
276 virtual Info GetInfo() const noexcept = 0;
277
278 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
279 // agnostic CNetMessage (message type & payload) objects.
280
282 virtual bool ReceivedMessageComplete() const = 0;
283
290 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
291
299 virtual CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) = 0;
300
301 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
302
309 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
310
318 using BytesToSend = std::tuple<
319 std::span<const uint8_t> /*to_send*/,
320 bool /*more*/,
321 const std::string& /*m_type*/
322 >;
323
359 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
360
367 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
368
370 virtual size_t GetSendMemoryUsage() const noexcept = 0;
371
372 // 3. Miscellaneous functions.
373
375 virtual bool ShouldReconnectV1() const noexcept = 0;
376};
377
378class V1Transport final : public Transport
379{
380private:
382 const NodeId m_node_id; // Only for logging
385 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
386 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
387 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
388 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
389 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
390 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
391 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
392
394 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
395 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
396
399 vRecv.clear();
400 hdrbuf.clear();
401 hdrbuf.resize(24);
402 in_data = false;
403 nHdrPos = 0;
404 nDataPos = 0;
405 data_hash.SetNull();
406 hasher.Reset();
407 }
408
410 {
412 if (!in_data) return false;
413 return hdr.nMessageSize == nDataPos;
414 }
415
419 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
423 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
425 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
426
427public:
428 explicit V1Transport(NodeId node_id) noexcept;
429
435
436 Info GetInfo() const noexcept override;
437
438 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
439 {
442 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
443 if (ret < 0) {
444 Reset();
445 } else {
446 msg_bytes = msg_bytes.subspan(ret);
447 }
448 return ret >= 0;
449 }
450
451 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
452
453 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
454 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
455 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
456 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
457 bool ShouldReconnectV1() const noexcept override { return false; }
458};
459
460class V2Transport final : public Transport
461{
462private:
466 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
467
470 static constexpr size_t V1_PREFIX_LEN = 16;
471
472 // The sender side and receiver side of V2Transport are state machines that are transitioned
473 // through, based on what has been received. The receive state corresponds to the contents of,
474 // and bytes received to, the receive buffer. The send state controls what can be appended to
475 // the send buffer and what can be sent from it.
476
491 enum class RecvState : uint8_t {
497 KEY_MAYBE_V1,
498
504 KEY,
505
512 GARB_GARBTERM,
513
522 VERSION,
523
529 APP,
530
535 APP_READY,
536
541 };
542
556 enum class SendState : uint8_t {
563 MAYBE_V1,
564
570 AWAITING_KEY,
571
578 READY,
579
584 };
585
589 const bool m_initiating;
594
596 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
599 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
601 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
603 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
605 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
607 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
608
611 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
613 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
615 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
617 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
619 std::string m_send_type GUARDED_BY(m_send_mutex);
621 SendState m_send_state GUARDED_BY(m_send_mutex);
623 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
624
626 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
628 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
630 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
632 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
634 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
636 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
638 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
640 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
642 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
643
644public:
645 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
646
652 V2Transport(NodeId nodeid, bool initiating) noexcept;
653
655 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
656
657 // Receive side functions.
658 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
659 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
660 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
661
662 // Send side functions.
663 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
664 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
665 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
666 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
667
668 // Miscellaneous functions.
669 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
670 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
671};
672
674{
676 std::optional<Proxy> proxy_override = {};
677 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
678 bool prefer_evict = false;
680 bool use_v2transport = false;
681};
682
684class CNode
685{
686public:
689 const std::unique_ptr<Transport> m_transport;
690
692
701 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
702
704 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
706 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
708 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
712
713 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
714
715 std::atomic<NodeClock::time_point> m_last_send{NodeClock::epoch};
716 std::atomic<NodeClock::time_point> m_last_recv{NodeClock::epoch};
719
721 const std::optional<Proxy> m_proxy_override;
722
723 // Address of this peer
725 // Bind address of our side of the connection
727 const std::string m_addr_name;
729 const std::string m_dest;
731 const bool m_inbound_onion;
732 std::atomic<int> nVersion{0};
738 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
739 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
740 bool HasPermission(NetPermissionFlags permission) const {
742 }
743
744 std::atomic_bool fSuccessfullyConnected{false};
745 // Setting fDisconnect to true will cause the node to be disconnected the
746 // next time DisconnectNodes() runs
747 std::atomic_bool fDisconnect{false};
749 std::atomic<int> nRefCount{0};
750
751 const uint64_t nKeyedNetGroup;
752 std::atomic_bool fPauseRecv{false};
753 std::atomic_bool fPauseSend{false};
755 std::atomic<NodeClock::time_point> m_pause_send_since{NodeClock::epoch};
756
759 const uint64_t m_network_key;
760
762
766
772 std::optional<std::pair<CNetMessage, bool>> PollMessage()
774
776 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
778 {
779 mapSendBytesPerMsgType[msg_type] += sent_bytes;
780 }
781
783 switch (m_conn_type) {
786 return true;
792 return false;
793 } // no default case, so the compiler can warn about missing cases
794
795 assert(false);
796 }
797
801
802 bool IsManualConn() const {
804 }
805
807 {
808 switch (m_conn_type) {
814 return false;
817 return true;
818 } // no default case, so the compiler can warn about missing cases
819
820 assert(false);
821 }
822
823 bool IsBlockOnlyConn() const {
825 }
826
827 bool IsFeelerConn() const {
829 }
830
831 bool IsAddrFetchConn() const {
833 }
834
839
846
847 bool IsInboundConn() const {
849 }
850
852 switch (m_conn_type) {
856 return false;
861 return true;
862 } // no default case, so the compiler can warn about missing cases
863
864 assert(false);
865 }
866
877 Network ConnectedThroughNetwork() const;
878
880 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
881
882 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
883 std::atomic<bool> m_bip152_highbandwidth_to{false};
884 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
885 std::atomic<bool> m_bip152_highbandwidth_from{false};
886
888 std::atomic_bool m_has_all_wanted_services{false};
889
892 std::atomic_bool m_relays_txs{false};
893
896 std::atomic_bool m_bloom_filter_loaded{false};
897
903 std::atomic<std::chrono::seconds> m_last_block_time{0s};
904
909 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
910
912 std::atomic<NodeClock::duration> m_last_ping_time{0us};
913
916 std::atomic<NodeClock::duration> m_min_ping_time{NodeClock::duration::max()};
917
918 CNode(NodeId id,
919 std::shared_ptr<Sock> sock,
920 const CAddress& addrIn,
921 uint64_t nKeyedNetGroupIn,
922 uint64_t nLocalHostNonceIn,
923 const CService& addrBindIn,
924 const std::string& addrNameIn,
925 ConnectionType conn_type_in,
926 bool inbound_onion,
927 uint64_t network_key,
928 CNodeOptions&& node_opts = {});
929 CNode(const CNode&) = delete;
930 CNode& operator=(const CNode&) = delete;
931
932 NodeId GetId() const {
933 return id;
934 }
935
936 uint64_t GetLocalNonce() const {
937 return nLocalHostNonce;
938 }
939
940 int GetRefCount() const
941 {
942 assert(nRefCount >= 0);
943 return nRefCount;
944 }
945
955 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
956
957 void SetCommonVersion(int greatest_common_version)
958 {
960 m_greatest_common_version = greatest_common_version;
961 }
963 {
965 }
966
967 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
969 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
970
972 {
973 nRefCount++;
974 return this;
975 }
976
977 void Release()
978 {
979 nRefCount--;
980 }
981
982 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
983
985
986 std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
987
993 std::string LogPeer() const;
994
1000 std::string DisconnectMsg() const;
1001
1003 void PongReceived(NodeClock::duration ping_time)
1004 {
1005 m_last_ping_time = ping_time;
1006 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
1007 }
1008
1009private:
1010 const NodeId id;
1011 const uint64_t nLocalHostNonce;
1013
1014 const size_t m_recv_flood_size;
1015 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1016
1018 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1019 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1020
1021 // Our address, as reported by the peer
1024
1025 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1026 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1027
1038 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1039};
1040
1045{
1046public:
1049
1051 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1052
1054 virtual void FinalizeNode(const CNode& node) = 0;
1055
1060 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1061
1069 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1070
1078
1079
1080protected:
1086};
1087
1089{
1090public:
1091
1121
1123 {
1125
1126 m_local_services = connOptions.m_local_services;
1127 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1132 m_max_inbound_full_relay = std::max(0, static_cast<int>(connOptions.m_full_relay_inbound_percent / 100.0 * m_max_inbound));
1133 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1134 m_client_interface = connOptions.uiInterface;
1135 m_banman = connOptions.m_banman;
1136 m_msgproc = connOptions.m_msgproc;
1137 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1138 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1139 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1140 {
1141 LOCK(m_total_bytes_sent_mutex);
1142 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1143 }
1144 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1145 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1146 {
1148 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1149 // peer doesn't support it or immediately disconnects us for another reason.
1151 for (const std::string& added_node : connOptions.m_added_nodes) {
1152 m_added_node_params.push_back({added_node, use_v2transport});
1153 }
1154 }
1155 m_onion_binds = connOptions.onion_binds;
1156 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1157 whitelist_relay = connOptions.whitelist_relay;
1158 m_capture_messages = connOptions.m_capture_messages;
1159 }
1160
1161 // test only
1162 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1163
1164 CConnman(uint64_t seed0,
1165 uint64_t seed1,
1166 AddrMan& addrman,
1167 const NetGroupManager& netgroupman,
1168 const CChainParams& params,
1169 bool network_active = true,
1170 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1171
1172 ~CConnman();
1173
1175
1176 void StopThreads();
1179 {
1184 };
1185
1186 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1187 bool GetNetworkActive() const { return fNetworkActive; };
1189 void SetNetworkActive(bool active);
1190
1203 bool OpenNetworkConnection(const CAddress& addrConnect,
1204 bool fCountFailure,
1205 CountingSemaphoreGrant<>&& grant_outbound,
1206 const char* pszDest,
1207 ConnectionType conn_type,
1208 bool use_v2transport,
1209 const std::optional<Proxy>& proxy_override)
1211
1214 {
1215 public:
1224 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1225
1231
1241 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1242
1244 size_t NumToOpen() const;
1245
1251 void NumToOpenAdd(size_t n);
1252
1259 size_t NumToOpenSub(size_t n);
1260
1262 void NumToOpenWait() const;
1263
1264 protected:
1270 std::optional<Proxy> ProxyForIPv4or6() const;
1271
1273 std::atomic_size_t m_num_to_open{0};
1274
1275 friend struct ConnmanTestMsg;
1276 } m_private_broadcast;
1277
1278 bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1279 void ASMapHealthCheck();
1280
1281 // alias for thread safety annotations only, not defined
1283
1284 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1285
1287
1288 using NodeFn = std::function<void(CNode*)>;
1290 {
1292 for (auto&& node : m_nodes) {
1294 func(node);
1295 }
1296 };
1297
1299 {
1301 for (auto&& node : m_nodes) {
1303 func(node);
1304 }
1305 };
1306
1307 // Addrman functions
1319 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1334 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1335
1336 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1337 // a peer that is better than all our current peers.
1338 void SetTryNewOutboundPeer(bool flag);
1339 bool GetTryNewOutboundPeer() const;
1340
1341 void StartExtraBlockRelayPeers();
1342
1343 // Count the number of full-relay peer we have.
1344 int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1345 // Return the number of outbound peers we have in excess of our target (eg,
1346 // if we previously called SetTryNewOutboundPeer(true), and have since set
1347 // to false, we may have extra peers that we wish to disconnect). This may
1348 // return a value less than (num_outbound_connections - num_outbound_slots)
1349 // in cases where some outbound connections are not yet fully connected, or
1350 // not yet fully disconnected.
1351 int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1352 // Count the number of block-relay-only peers we have over our limit.
1353 int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1363 bool EvictTxPeerIfFull(std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1364
1365 bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1366 bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1367 bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1368 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const
1370
1384 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)
1386
1389 uint32_t GetMappedAS(const CNetAddr& addr) const;
1390 void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1392 bool DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast = true) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1395
1403
1408
1409 uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1410 std::chrono::seconds GetMaxOutboundTimeframe() const;
1411
1415 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1416
1419 uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1420
1421 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1422
1423 uint64_t GetTotalBytesRecv() const;
1424 uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1425
1427 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1428
1429 void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1430
1432 bool ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const;
1433
1434 bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1435
1436private:
1438 public:
1439 std::shared_ptr<Sock> sock;
1441 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1442 : sock{sock_}, m_permissions{permissions_}
1443 {
1444 }
1445
1446 private:
1448 };
1449
1453
1454 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1455 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1456 bool InitBinds(const Options& options);
1457
1463
1464 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1465
1469
1471 void ThreadOpenConnections(std::vector<std::string> connect, std::span<const std::string> seed_nodes)
1477
1484
1493 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1494 NetPermissionFlags permission_flags,
1495 const CService& addr_bind,
1496 const CService& addr)
1498
1502 bool InactivityCheck(const CNode& node, NodeClock::time_point now) const;
1503
1509 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1510
1515
1521 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1522 const Sock::EventsPerSock& events_per_sock)
1524
1529 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
1531
1536
1537 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1538
1546 bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1547
1556
1561
1568 bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1569
1580 CNode* ConnectNode(CAddress addrConnect,
1581 const char* pszDest,
1582 bool fCountFailure,
1583 ConnectionType conn_type,
1584 bool use_v2transport,
1585 const std::optional<Proxy>& proxy_override)
1587
1588 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1589
1590 void DeleteNode(CNode* pnode);
1591
1593
1595 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1596
1597 void DumpAddresses();
1598
1599 // Network stats
1600 void RecordBytesRecv(uint64_t bytes);
1602
1607 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1608
1613
1625
1626 // Whether the node should be passed out in ForEach* callbacks
1627 static bool NodeFullyConnected(const CNode* pnode);
1628
1629 uint16_t GetDefaultPort(Network net) const;
1630 uint16_t GetDefaultPort(const std::string& addr) const;
1631
1632 // Network usage totals
1634 std::atomic<uint64_t> nTotalBytesRecv{0};
1635 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1636
1637 // outbound limit & stats
1638 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1639 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1641
1642 // P2P timeout in seconds
1643 std::chrono::seconds m_peer_connect_timeout;
1644
1645 // Whitelisted ranges. Any node connecting from these is automatically
1646 // whitelisted (as well as those connecting to whitelisted binds).
1647 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1648 // Whitelisted ranges for outgoing connections.
1649 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1650
1651 unsigned int nSendBufferMaxSize{0};
1652 unsigned int nReceiveFloodSize{0};
1653
1654 std::vector<ListenSocket> vhListenSocket;
1655 std::atomic<bool> fNetworkActive{true};
1657 std::reference_wrapper<AddrMan> addrman;
1659 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1661
1662 // connection string and whether to use v2 p2p
1663 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1664
1666 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1667 std::list<CNode*> m_nodes_disconnected;
1669 std::atomic<NodeId> nLastNodeId{0};
1670 unsigned int nPrevNodeCount{0};
1671
1672 // Stores number of full-tx connections (outbound and manual) per network
1673 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1674
1682 std::vector<CAddress> m_addrs_response_cache;
1683 std::chrono::microseconds m_cache_entry_expiration{0};
1684 };
1685
1700 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1701
1713 std::atomic<ServiceFlags> m_local_services;
1714
1715 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1716 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1717
1724
1725 /*
1726 * Maximum number of peers by connection type. Might vary from defaults
1727 * based on -maxconnections init value.
1728 */
1729
1730 // How many full-relay (tx, block, addr) outbound peers we want
1732
1733 // How many block-relay only outbound peers we want
1734 // We do not relay tx or addr messages with these peers
1736
1742
1748
1753 std::vector<CAddress> m_anchors;
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
1819
1824
1832 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1833
1838
1849
1853 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1854
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
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
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.
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:1214
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:1224
std::atomic_size_t m_num_to_open
Number of ConnectionType::PRIVATE_BROADCAST connections to open.
Definition net.h:1273
friend struct ConnmanTestMsg
Definition net.h:1275
std::counting_semaphore m_sem_conn_max
Semaphore used to guard against opening too many connections.
Definition net.h:1230
void AcceptConnection(const ListenSocket &hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:1756
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:2571
std::condition_variable condMsgProc
Definition net.h:1761
std::thread threadMessageHandler
Definition net.h:1782
nSendBufferMaxSize
Definition net.h:1137
void RemoveLocalServices(ServiceFlags services)
Definition net.h:1407
void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempt reconnections, if m_reconnections non-empty.
Definition net.cpp:4269
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:2590
std::reference_wrapper< AddrMan > addrman
Definition net.h:1657
void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3748
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition net.cpp:1943
m_max_outbound_full_relay
Definition net.h:1128
void DeleteNode(CNode *pnode)
Definition net.cpp:3786
void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3273
bool GetNetworkActive() const
Definition net.h:1187
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
whitelist_relay
Definition net.h:1157
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:1863
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:3509
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
void SetCaptureMessages(bool cap)
Definition net.h:1162
std::thread threadI2PAcceptIncoming
Definition net.h:1783
std::atomic< bool > flagInterruptMsgProc
Definition net.h:1763
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition net.cpp:3902
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2306
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Return vector of current BLOCK_RELAY peers.
Definition net.cpp:2992
m_onion_binds
Definition net.h:1155
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:3504
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
m_capture_messages
Definition net.h:1158
std::atomic< NodeId > nLastNodeId
Definition net.h:1669
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
m_max_automatic_outbound
Definition net.h:1130
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1638
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:2271
std::thread threadDNSAddressSeed
Definition net.h:1778
void ForEachNode(const NodeFn &func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.h:1298
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:1898
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:2169
const uint64_t nSeed1
Definition net.h:1756
const NetGroupManager & m_netgroupman
Definition net.h:1658
m_banman
Definition net.h:1135
void ForEachNode(const NodeFn &func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.h:1289
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition net.h:1753
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition net.cpp:4262
friend struct ConnmanTestMsg
Definition net.h:1905
unsigned int nPrevNodeCount
Definition net.h:1670
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition net.cpp:580
ServiceFlags GetLocalServices() const
Definition net.cpp:4074
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::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:3539
vWhitelistedRangeOutgoing
Definition net.h:1145
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition net.cpp:133
std::vector< ListenSocket > vhListenSocket
Definition net.h:1654
Mutex m_total_bytes_sent_mutex
Definition net.h:1633
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:3068
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition net.cpp:3520
std::thread threadOpenConnections
Definition net.h:1781
int m_max_feeler
Definition net.h:1738
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3318
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition net.cpp:3908
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition net.cpp:2456
Mutex m_addr_fetches_mutex
Definition net.h:1660
m_peer_connect_timeout
Definition net.h:1139
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition net.h:1837
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:3573
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1756
m_local_services
Definition net.h:1126
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
Definition net.cpp:4016
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
m_max_outbound_block_relay
Definition net.h:1129
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:4163
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition net.h:1715
m_client_interface
Definition net.h:1134
nReceiveFloodSize
Definition net.h:1138
const CChainParams & m_params
Definition net.h:1903
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
whitelist_forcerelay
Definition net.h:1156
bool InactivityCheck(const CNode &node, NodeClock::time_point now) const
Return true if the peer is inactive and should be disconnected.
Definition net.cpp:2045
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:1786
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition net.cpp:2608
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:1699
void GetNodeStats(std::vector< CNodeStats > &vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3913
void AddLocalServices(ServiceFlags services)
Definition net.h:1406
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:4242
m_max_automatic_connections
Definition net.h:1127
std::thread threadPrivateBroadcast
Definition net.h:1784
m_msgproc
Definition net.h:1136
Mutex mutexMsgProc
Definition net.h:1762
m_max_inbound
Definition net.h:1131
bool fAddressesInitialized
Definition net.h:1656
void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:2023
void StopThreads()
Definition net.cpp:3728
std::thread threadOpenAddedConnections
Definition net.h:1780
bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3927
Mutex m_added_nodes_mutex
Definition net.h:1665
vWhitelistedRangeIncoming
Definition net.h:1144
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition net.cpp:2286
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:3979
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition net.cpp:3232
Mutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
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:1823
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition net.h:1716
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3885
void RecordBytesRecv(uint64_t bytes)
Definition net.cpp:3974
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1639
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition net.cpp:2140
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1635
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition net.cpp:4179
bool GetUseAddrmanOutgoing() const
Definition net.h:1188
int m_max_addnode
Definition net.h:1737
std::list< CNode * > m_nodes_disconnected
Definition net.h:1667
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1776
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:1700
std::function< void(CNode *)> NodeFn
Definition net.h:1288
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition net.cpp:2109
std::atomic< uint64_t > nTotalBytesRecv
Definition net.h:1634
std::atomic< bool > fNetworkActive
Definition net.h:1655
AssertLockNotHeld(m_reconnections_mutex)
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
Definition net.h:1795
m_use_addrman_outgoing
Definition net.h:1133
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:3483
void DumpAddresses()
Definition net.cpp:2446
Mutex m_nodes_mutex
Definition net.h:1668
std::thread threadSocketHandler
Definition net.h:1779
m_max_inbound_full_relay
Definition net.h:1132
nMaxOutboundLimit
Definition net.h:1142
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition net.cpp:3387
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:32
An encapsulated private key.
Definition key.h:40
Message header.
Definition protocol.h:29
Network address.
Definition netaddress.h:113
Transport protocol agnostic message container.
Definition net.h:241
NodeClock::time_point m_time
Definition net.h:245
CNetMessage(CNetMessage &&)=default
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:128
uint32_t m_message_size
size of the payload
Definition net.h:246
CNetMessage(DataStream &&recv_in)
Definition net.h:250
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Definition net.h:247
std::string m_type
Definition net.h:248
DataStream m_recv
received message data time of message receipt
Definition net.h:243
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition net.h:685
bool IsFeelerConn() const
Definition net.h:827
bool ExpectServicesFromConn() const
Definition net.h:851
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition net.h:729
std::atomic< int > nVersion
Definition net.h:732
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:888
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition net.h:713
bool IsInboundConn() const
Definition net.h:847
bool HasPermission(NetPermissionFlags permission) const
Definition net.h:740
CountingSemaphoreGrant grantOutbound
Definition net.h:748
std::atomic_bool fPauseRecv
Definition net.h:752
bool IsOutboundOrBlockRelayConn() const
Definition net.h:782
NodeId GetId() const
Definition net.h:932
bool IsManualConn() const
Definition net.h:802
std::atomic< NodeClock::duration > m_last_ping_time
Last measured round-trip duration. Used only for stats.
Definition net.h:912
const std::string m_addr_name
Definition net.h:727
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
Definition net.cpp:622
CNode & operator=(const CNode &)=delete
std::string ConnectionTypeAsString() const
Definition net.h:986
const CService addrBind
Definition net.h:726
void SetCommonVersion(int greatest_common_version)
Definition net.h:957
std::atomic< bool > m_bip152_highbandwidth_to
Definition net.h:883
std::list< CNetMessage > vRecvMsg
Definition net.h:1015
std::atomic_bool m_relays_txs
Whether we should relay transactions to this peer.
Definition net.h:892
std::atomic< bool > m_bip152_highbandwidth_from
Definition net.h:885
std::atomic_bool fSuccessfullyConnected
fSuccessfullyConnected is set to true on receiving VERACK from the peer.
Definition net.h:744
const bool m_prefer_evict
Definition net.h:739
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition net.h:1019
bool IsAddrFetchConn() const
Definition net.h:831
uint64_t GetLocalNonce() const
Definition net.h:936
const CAddress addr
Definition net.h:724
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
Definition net.h:718
std::atomic< NodeClock::time_point > m_last_recv
Definition net.h:716
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition net.h:751
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:749
std::atomic< int > m_greatest_common_version
Definition net.h:1012
bool IsBlockOnlyConn() const
Definition net.h:823
std::atomic< NodeClock::time_point > m_pause_send_since
When was fPauseSend last set from false to true.
Definition net.h:755
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:4088
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
Definition net.cpp:4132
int GetCommonVersion() const
Definition net.h:962
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition net.h:798
Mutex m_subver_mutex
Definition net.h:733
Mutex cs_vSend
Definition net.h:709
CNode * AddRef()
Definition net.h:971
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition net.h:759
std::atomic_bool fPauseSend
Definition net.h:753
int GetRefCount() const
Definition net.h:940
std::atomic< NodeClock::duration > m_min_ping_time
Lowest measured round-trip duration.
Definition net.h:916
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:4149
void PongReceived(NodeClock::duration ping_time)
A ping-pong round trip has completed successfully. Update latest and minimum ping durations.
Definition net.h:1003
Mutex m_msg_process_queue_mutex
Definition net.h:1017
std::atomic_bool m_bloom_filter_loaded
Whether this peer has loaded a bloom filter.
Definition net.h:896
std::atomic< NodeClock::time_point > m_last_send
Definition net.h:715
const ConnectionType m_conn_type
Definition net.h:761
const size_t m_recv_flood_size
Definition net.h:1014
const uint64_t nLocalHostNonce
Definition net.h:1011
bool IsManualOrFullOutboundConn() const
Definition net.h:806
bool IsPrivateBroadcastConn() const
Definition net.h:835
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition net.h:689
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:691
Mutex m_addr_local_mutex
Definition net.h:1023
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition net.h:704
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition net.h:731
const NodeId id
Definition net.h:1010
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:776
Mutex cs_vRecv
Definition net.h:711
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:903
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition net.h:706
int AdvertisedVersion() const
Protocol version advertised in our VERSION message.
Definition net.h:842
Mutex m_sock_mutex
Definition net.h:710
std::atomic_bool fDisconnect
Definition net.h:747
const std::optional< Proxy > m_proxy_override
Proxy to use regardless of global proxy settings if reconnecting to this node.
Definition net.h:721
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:909
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:977
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:738
std::string m_session_id
BIP324 session id string in hex, if any.
Definition net.h:232
std::string addrLocal
Definition net.h:220
NodeClock::duration m_min_ping_time
Definition net.h:218
uint64_t nRecvBytes
Definition net.h:214
uint32_t m_mapped_as
Definition net.h:227
mapMsgTypeSize mapRecvBytesPerMsgType
Definition net.h:215
bool fInbound
Definition net.h:207
uint64_t nSendBytes
Definition net.h:212
ConnectionType m_conn_type
Definition net.h:228
std::chrono::seconds m_last_tx_time
Definition net.h:201
CAddress addr
Definition net.h:222
mapMsgTypeSize mapSendBytesPerMsgType
Definition net.h:213
CService addrBind
Definition net.h:224
NodeClock::time_point m_last_recv
Definition net.h:200
NodeClock::time_point m_last_send
Definition net.h:199
NodeClock::duration m_last_ping_time
Definition net.h:217
TransportProtocolType m_transport_type
Transport protocol type.
Definition net.h:230
bool m_bip152_highbandwidth_from
Definition net.h:211
bool m_bip152_highbandwidth_to
Definition net.h:209
std::string m_addr_name
Definition net.h:204
NodeClock::time_point m_connected
Definition net.h:203
int nVersion
Definition net.h:205
std::chrono::seconds m_last_block_time
Definition net.h:202
Network m_network
Definition net.h:226
NodeId nodeid
Definition net.h:198
std::string cleanSubVer
Definition net.h:206
NetPermissionFlags m_permission_flags
Definition net.h:216
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
Interface for message handling.
Definition net.h:1045
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:1048
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:35
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition net.h:265
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 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message)=0
Retrieve a completed message from transport.
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 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:318
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:387
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition net.h:423
int readData(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:782
const NodeId m_node_id
Definition net.h:382
Mutex m_send_mutex
Lock for sending state.
Definition net.h:417
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:425
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:381
const uint256 & GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:800
int readHeader(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.cpp:739
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition net.h:389
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:409
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:438
V1Transport(NodeId node_id) noexcept
Definition net.cpp:727
void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:397
bool ShouldReconnectV1() const noexcept override
Whether upon disconnections, a reconnect with V1 is warranted.
Definition net.h:457
Mutex m_recv_mutex
Lock for receive state.
Definition net.h:383
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:430
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:623
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:1539
static constexpr uint32_t MAX_GARBAGE_LEN
Definition net.h:645
const NodeId m_nodeid
NodeId (for debug logging).
Definition net.h:591
BIP324Cipher m_cipher
Cipher state.
Definition net.h:587
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:1578
void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state.
Definition net.cpp:1087
SendState
State type that controls the sender side.
Definition net.h:556
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition net.h:593
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:470
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:1212
CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
Definition net.cpp:1461
bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY state.
Definition net.cpp:1125
const bool m_initiating
Whether we are the initiator side.
Definition net.h:589
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
Definition net.cpp:1587
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:1522
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:1185
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:599
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:615
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:1078
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:466
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:1330
bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Whether upon disconnections, a reconnect with V1 is warranted.
Definition net.cpp:1561
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:1490
V2Transport(NodeId nodeid, bool initiating) noexcept
Construct a V2 transport with securely generated random keys.
Definition net.cpp:1023
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:491
256-bit opaque blob.
Definition uint256.h:196
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
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:109
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:119
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:4352
constexpr bool DEFAULT_LISTEN
-listen default
Definition net.h:79
uint16_t GetListenPort()
Definition net.cpp:139
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition net.h:93
constexpr unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:67
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:75
constexpr bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:89
constexpr int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:71
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:59
constexpr size_t DEFAULT_MAXSENDBUFFER
Definition net.h:103
bool fDiscover
Definition net.cpp:117
constexpr bool DEFAULT_FIXEDSEEDS
Definition net.h:101
constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:81
constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition net.h:91
void ClearLocal()
Definition net.cpp:271
bool fListen
Definition net.cpp:118
@ LOCAL_NONE
Definition net.h:158
@ LOCAL_MAPPED
Definition net.h:161
@ LOCAL_MANUAL
Definition net.h:162
@ LOCAL_MAX
Definition net.h:164
@ LOCAL_BIND
Definition net.h:160
@ LOCAL_IF
Definition net.h:159
constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition net.h:65
constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:63
constexpr size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:102
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:87
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:241
std::map< std::string, uint64_t > mapMsgTypeSize
Definition net.h:193
constexpr bool DEFAULT_FORCEDNSSEED
Definition net.h:99
constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition net.h:77
constexpr bool DEFAULT_DNSSEED
Definition net.h:100
int64_t NodeId
Definition net.h:107
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:73
CService GetLocalAddress(const CNode &peer)
Definition net.cpp:221
constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition net.h:97
constexpr int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:95
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:61
constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT
Default percentage of inbound connection slots that tx-relaying peers can use.
Definition net.h:85
constexpr bool DEFAULT_V2_TRANSPORT
Definition net.h:105
constexpr int MAX_PEER_CONNECTIONS
Maximum value of -maxconnections.
Definition net.h:83
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:69
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:3456
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:118
CService resolvedAddress
Definition net.h:116
AddedNodeParams m_params
Definition net.h:115
bool fConnected
Definition net.h:117
std::string m_added_node
Definition net.h:110
bool m_use_v2transport
Definition net.h:111
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1681
std::chrono::microseconds m_cache_entry_expiration
Definition net.h:1683
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1682
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition net.h:1440
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition net.h:1441
NetPermissionFlags m_permissions
Definition net.h:1447
std::shared_ptr< Sock > sock
Definition net.h:1439
unsigned int nReceiveFloodSize
Definition net.h:1101
int m_full_relay_inbound_percent
Definition net.h:1096
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:1107
uint64_t nMaxOutboundLimit
Definition net.h:1102
CClientUIInterface * uiInterface
Definition net.h:1097
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1105
std::vector< CService > onion_binds
Definition net.h:1109
std::vector< std::string > m_specified_outgoing
Definition net.h:1114
bool whitelist_relay
Definition net.h:1118
NetEventsInterface * m_msgproc
Definition net.h:1098
std::vector< std::string > m_added_nodes
Definition net.h:1115
int64_t m_peer_connect_timeout
Definition net.h:1103
std::vector< CService > vBinds
Definition net.h:1108
bool m_capture_messages
Definition net.h:1119
unsigned int nSendBufferMaxSize
Definition net.h:1100
int m_max_automatic_connections
Definition net.h:1095
ServiceFlags m_local_services
Definition net.h:1094
bool m_i2p_accept_incoming
Definition net.h:1116
std::vector< std::string > vSeedNodes
Definition net.h:1104
BanMan * m_banman
Definition net.h:1099
bool m_use_addrman_outgoing
Definition net.h:1113
bool whitelist_forcerelay
Definition net.h:1117
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:1112
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1106
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
NetPermissionFlags permission_flags
Definition net.h:675
std::unique_ptr< i2p::sam::Session > i2p_sam_session
Definition net.h:677
bool prefer_evict
Definition net.h:678
bool use_v2transport
Definition net.h:680
std::optional< Proxy > proxy_override
Definition net.h:676
size_t recv_flood_size
Definition net.h:679
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition net.h:132
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition net.h:141
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition net.h:140
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:186
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:272
TransportProtocolType transport_type
Definition net.h:271
Bilingual messages:
Definition translation.h:24
#define AssertLockNotHeld(cs)
Definition sync.h:149
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
Definition sync.h:131
#define LOCK(cs)
Definition sync.h:268
#define WITH_LOCK(cs, code)
Definition sync.h:299
#define AssertLockHeld(cs)
Definition sync.h:144
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define LOCK_RETURNED(x)
assert(!tx.IsCoinBase())