Bitcoin Core 31.99.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_NET_H
7#define BITCOIN_NET_H
8
9#include <bip324.h>
10#include <chainparams.h>
11#include <common/bloom.h>
12#include <compat/compat.h>
13#include <consensus/amount.h>
14#include <crypto/siphash.h>
15#include <hash.h>
16#include <i2p.h>
18#include <net_permissions.h>
19#include <netaddress.h>
20#include <netbase.h>
21#include <netgroup.h>
24#include <policy/feerate.h>
25#include <protocol.h>
26#include <random.h>
27#include <semaphore_grant.h>
28#include <span.h>
29#include <streams.h>
30#include <sync.h>
31#include <uint256.h>
32#include <util/check.h>
33#include <util/sock.h>
34#include <util/threadinterrupt.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{200};
83static const int DEFAULT_FULL_RELAY_INBOUND_PCT{50};
85static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
87static const bool DEFAULT_BLOCKSONLY = false;
89static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
91static constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
93static const int NUM_FDS_MESSAGE_CAPTURE = 1;
95static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
96
97static constexpr bool DEFAULT_FORCEDNSSEED{false};
98static constexpr bool DEFAULT_DNSSEED{true};
99static constexpr bool DEFAULT_FIXEDSEEDS{true};
100static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
101static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
102
103static constexpr bool DEFAULT_V2_TRANSPORT{true};
104
105typedef int64_t NodeId;
106
108 std::string m_added_node;
110};
111
117};
118
119class CNodeStats;
121
123 CSerializedNetMsg() = default;
126 // No implicit copying, only moves.
129
131 {
133 copy.data = data;
134 copy.m_type = m_type;
135 return copy;
136 }
137
138 std::vector<unsigned char> data;
139 std::string m_type;
140
142 size_t GetMemoryUsage() const noexcept;
143};
144
150void Discover();
151
152uint16_t GetListenPort();
153
154enum
155{
156 LOCAL_NONE, // unknown
157 LOCAL_IF, // address a local interface listens on
158 LOCAL_BIND, // address explicit bound to
159 LOCAL_MAPPED, // address reported by PCP
160 LOCAL_MANUAL, // address explicitly specified (-externalip=)
161
164
166std::optional<CService> GetLocalAddrForPeer(CNode& node);
167
168void ClearLocal();
169bool AddLocal(const CService& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
170bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);
171void RemoveLocal(const CService& addr);
172bool SeenLocal(const CService& addr);
173bool IsLocal(const CService& addr);
174CService GetLocalAddress(const CNode& peer);
175
176extern bool fDiscover;
177extern bool fListen;
178
180extern std::string strSubVersion;
181
184 uint16_t nPort;
185};
186
188extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
189
190extern const std::string NET_MESSAGE_TYPE_OTHER;
191using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
192
194{
195public:
199 std::chrono::seconds m_last_tx_time;
200 std::chrono::seconds m_last_block_time;
202 std::string m_addr_name;
204 std::string cleanSubVer;
206 // We requested high bandwidth connection to peer
208 // Peer requested high bandwidth connection
210 uint64_t nSendBytes;
212 uint64_t nRecvBytes;
215 NodeClock::duration m_last_ping_time;
216 NodeClock::duration m_min_ping_time;
217 // Our address, as reported by the peer
218 std::string addrLocal;
219 // Address of this peer
221 // Bind address of our side of the connection
223 // Network the peer connected through
225 uint32_t m_mapped_as;
230 std::string m_session_id;
231};
232
233
239{
240public:
244 uint32_t m_message_size{0};
245 uint32_t m_raw_message_size{0};
246 std::string m_type;
247
248 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
249 // Only one CNetMessage object will exist for the same message on either
250 // the receive or processing queue. For performance reasons we therefore
251 // delete the copy constructor and assignment operator to avoid the
252 // possibility of copying CNetMessage objects.
254 CNetMessage(const CNetMessage&) = delete;
257
259 size_t GetMemoryUsage() const noexcept;
260};
261
264public:
265 virtual ~Transport() = default;
266
267 struct Info
268 {
270 std::optional<uint256> session_id;
271 };
272
274 virtual Info GetInfo() const noexcept = 0;
275
276 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
277 // agnostic CNetMessage (message type & payload) objects.
278
280 virtual bool ReceivedMessageComplete() const = 0;
281
288 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
289
297 virtual CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) = 0;
298
299 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
300
307 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
308
316 using BytesToSend = std::tuple<
317 std::span<const uint8_t> /*to_send*/,
318 bool /*more*/,
319 const std::string& /*m_type*/
320 >;
321
357 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
358
365 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
366
368 virtual size_t GetSendMemoryUsage() const noexcept = 0;
369
370 // 3. Miscellaneous functions.
371
373 virtual bool ShouldReconnectV1() const noexcept = 0;
374};
375
376class V1Transport final : public Transport
377{
378private:
380 const NodeId m_node_id; // Only for logging
382 mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
383 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
384 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
385 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
386 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
387 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
388 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
389 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
390
391 const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
392 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
393 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
394
395 void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
396 AssertLockHeld(m_recv_mutex);
397 vRecv.clear();
398 hdrbuf.clear();
399 hdrbuf.resize(24);
400 in_data = false;
401 nHdrPos = 0;
402 nDataPos = 0;
403 data_hash.SetNull();
404 hasher.Reset();
405 }
406
407 bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
408 {
409 AssertLockHeld(m_recv_mutex);
410 if (!in_data) return false;
411 return hdr.nMessageSize == nDataPos;
412 }
413
417 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
419 CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
421 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
423 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
424
425public:
426 explicit V1Transport(NodeId node_id) noexcept;
427
428 bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
429 {
430 AssertLockNotHeld(m_recv_mutex);
431 return WITH_LOCK(m_recv_mutex, return CompleteInternal());
432 }
433
434 Info GetInfo() const noexcept override;
435
436 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
437 {
438 AssertLockNotHeld(m_recv_mutex);
439 LOCK(m_recv_mutex);
440 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
441 if (ret < 0) {
442 Reset();
443 } else {
444 msg_bytes = msg_bytes.subspan(ret);
445 }
446 return ret >= 0;
447 }
448
449 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
450
451 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
452 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
453 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
454 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
455 bool ShouldReconnectV1() const noexcept override { return false; }
456};
457
458class V2Transport final : public Transport
459{
460private:
464 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
465
468 static constexpr size_t V1_PREFIX_LEN = 16;
469
470 // The sender side and receiver side of V2Transport are state machines that are transitioned
471 // through, based on what has been received. The receive state corresponds to the contents of,
472 // and bytes received to, the receive buffer. The send state controls what can be appended to
473 // the send buffer and what can be sent from it.
474
489 enum class RecvState : uint8_t {
495 KEY_MAYBE_V1,
496
502 KEY,
503
510 GARB_GARBTERM,
511
520 VERSION,
521
527 APP,
528
533 APP_READY,
534
538 V1,
539 };
540
554 enum class SendState : uint8_t {
561 MAYBE_V1,
562
568 AWAITING_KEY,
569
576 READY,
577
581 V1,
582 };
583
587 const bool m_initiating;
592
594 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
597 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
599 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
601 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
603 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
605 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
606
609 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
611 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
613 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
615 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
617 std::string m_send_type GUARDED_BY(m_send_mutex);
619 SendState m_send_state GUARDED_BY(m_send_mutex);
621 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
622
624 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
626 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
628 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
630 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
632 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
634 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
636 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
638 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
640 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
641
642public:
643 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
644
650 V2Transport(NodeId nodeid, bool initiating) noexcept;
651
653 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
654
655 // Receive side functions.
656 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
657 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
658 CNetMessage GetReceivedMessage(NodeClock::time_point time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
659
660 // Send side functions.
661 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
662 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
663 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
664 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
665
666 // Miscellaneous functions.
667 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
668 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
669};
670
672{
674 std::optional<Proxy> proxy_override = {};
675 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
676 bool prefer_evict = false;
677 size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
678 bool use_v2transport = false;
679};
680
682class CNode
683{
684public:
687 const std::unique_ptr<Transport> m_transport;
688
690
699 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
700
702 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
704 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
706 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
710
711 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
712
713 std::atomic<NodeClock::time_point> m_last_send{NodeClock::epoch};
714 std::atomic<NodeClock::time_point> m_last_recv{NodeClock::epoch};
717
719 const std::optional<Proxy> m_proxy_override;
720
721 // Address of this peer
723 // Bind address of our side of the connection
725 const std::string m_addr_name;
727 const std::string m_dest;
729 const bool m_inbound_onion;
730 std::atomic<int> nVersion{0};
736 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
737 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
738 bool HasPermission(NetPermissionFlags permission) const {
739 return NetPermissions::HasFlag(m_permission_flags, permission);
740 }
742 std::atomic_bool fSuccessfullyConnected{false};
743 // Setting fDisconnect to true will cause the node to be disconnected the
744 // next time DisconnectNodes() runs
745 std::atomic_bool fDisconnect{false};
747 std::atomic<int> nRefCount{0};
748
749 const uint64_t nKeyedNetGroup;
750 std::atomic_bool fPauseRecv{false};
751 std::atomic_bool fPauseSend{false};
752
755 const uint64_t m_network_key;
756
758
760 void MarkReceivedMsgsForProcessing()
761 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
762
768 std::optional<std::pair<CNetMessage, bool>> PollMessage()
769 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
770
772 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
774 {
775 mapSendBytesPerMsgType[msg_type] += sent_bytes;
776 }
777
779 switch (m_conn_type) {
782 return true;
788 return false;
789 } // no default case, so the compiler can warn about missing cases
790
791 assert(false);
792 }
793
794 bool IsFullOutboundConn() const {
795 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
796 }
797
798 bool IsManualConn() const {
799 return m_conn_type == ConnectionType::MANUAL;
800 }
801
803 {
804 switch (m_conn_type) {
810 return false;
813 return true;
814 } // no default case, so the compiler can warn about missing cases
815
816 assert(false);
817 }
818
819 bool IsBlockOnlyConn() const {
820 return m_conn_type == ConnectionType::BLOCK_RELAY;
821 }
822
823 bool IsFeelerConn() const {
824 return m_conn_type == ConnectionType::FEELER;
825 }
826
827 bool IsAddrFetchConn() const {
828 return m_conn_type == ConnectionType::ADDR_FETCH;
829 }
830
832 {
833 return m_conn_type == ConnectionType::PRIVATE_BROADCAST;
834 }
835
839 {
840 return IsPrivateBroadcastConn() ? WTXID_RELAY_VERSION : PROTOCOL_VERSION;
841 }
842
843 bool IsInboundConn() const {
844 return m_conn_type == ConnectionType::INBOUND;
845 }
846
848 switch (m_conn_type) {
852 return false;
857 return true;
858 } // no default case, so the compiler can warn about missing cases
859
860 assert(false);
861 }
862
873 Network ConnectedThroughNetwork() const;
874
876 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
877
878 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
879 std::atomic<bool> m_bip152_highbandwidth_to{false};
880 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
881 std::atomic<bool> m_bip152_highbandwidth_from{false};
882
884 std::atomic_bool m_has_all_wanted_services{false};
885
888 std::atomic_bool m_relays_txs{false};
889
892 std::atomic_bool m_bloom_filter_loaded{false};
893
899 std::atomic<std::chrono::seconds> m_last_block_time{0s};
900
905 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
906
908 std::atomic<NodeClock::duration> m_last_ping_time{0us};
909
912 std::atomic<NodeClock::duration> m_min_ping_time{NodeClock::duration::max()};
913
914 CNode(NodeId id,
915 std::shared_ptr<Sock> sock,
916 const CAddress& addrIn,
917 uint64_t nKeyedNetGroupIn,
918 uint64_t nLocalHostNonceIn,
919 const CService& addrBindIn,
920 const std::string& addrNameIn,
921 ConnectionType conn_type_in,
922 bool inbound_onion,
923 uint64_t network_key,
924 CNodeOptions&& node_opts = {});
925 CNode(const CNode&) = delete;
926 CNode& operator=(const CNode&) = delete;
927
928 NodeId GetId() const {
929 return id;
930 }
931
932 uint64_t GetLocalNonce() const {
933 return nLocalHostNonce;
934 }
935
936 int GetRefCount() const
937 {
938 assert(nRefCount >= 0);
939 return nRefCount;
940 }
941
951 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
952
953 void SetCommonVersion(int greatest_common_version)
954 {
955 Assume(m_greatest_common_version == INIT_PROTO_VERSION);
956 m_greatest_common_version = greatest_common_version;
957 }
959 {
960 return m_greatest_common_version;
961 }
962
963 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
965 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
966
967 CNode* AddRef()
968 {
969 nRefCount++;
970 return this;
971 }
972
973 void Release()
974 {
975 nRefCount--;
976 }
977
978 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
979
980 void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
981
983
989 std::string LogPeer() const;
990
996 std::string DisconnectMsg() const;
997
999 void PongReceived(NodeClock::duration ping_time)
1000 {
1001 m_last_ping_time = ping_time;
1002 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
1003 }
1004
1005private:
1006 const NodeId id;
1007 const uint64_t nLocalHostNonce;
1008 std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
1009
1010 const size_t m_recv_flood_size;
1011 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
1012
1014 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
1015 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1016
1017 // Our address, as reported by the peer
1018 CService m_addr_local GUARDED_BY(m_addr_local_mutex);
1020
1021 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1022 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1023
1034 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1035};
1036
1041{
1042public:
1045
1047 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1048
1050 virtual void FinalizeNode(const CNode& node) = 0;
1051
1056 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1057
1065 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1066
1073 virtual bool SendMessages(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1074
1075
1076protected:
1082};
1083
1085{
1086public:
1087
1088 struct Options
1089 {
1090 ServiceFlags m_local_services = NODE_NONE;
1091 int m_max_automatic_connections = DEFAULT_MAX_PEER_CONNECTIONS;
1092 int m_full_relay_inbound_percent = DEFAULT_FULL_RELAY_INBOUND_PCT;
1094 NetEventsInterface* m_msgproc = nullptr;
1095 BanMan* m_banman = nullptr;
1096 unsigned int nSendBufferMaxSize = 0;
1097 unsigned int nReceiveFloodSize = 0;
1098 uint64_t nMaxOutboundLimit = 0;
1099 int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1100 std::vector<std::string> vSeedNodes;
1101 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1102 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1103 std::vector<NetWhitebindPermissions> vWhiteBinds;
1104 std::vector<CService> vBinds;
1105 std::vector<CService> onion_binds;
1109 bool m_use_addrman_outgoing = true;
1110 std::vector<std::string> m_specified_outgoing;
1111 std::vector<std::string> m_added_nodes;
1113 bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1114 bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1115 bool m_capture_messages = false;
1116 };
1117
1118 void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1119 {
1120 AssertLockNotHeld(m_total_bytes_sent_mutex);
1121
1122 m_local_services = connOptions.m_local_services;
1123 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1124 m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1125 m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1126 m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1127 m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1128 m_max_inbound_full_relay = std::max(0, static_cast<int>(connOptions.m_full_relay_inbound_percent / 100.0 * m_max_inbound));
1129 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1130 m_client_interface = connOptions.uiInterface;
1131 m_banman = connOptions.m_banman;
1132 m_msgproc = connOptions.m_msgproc;
1133 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1134 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1135 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1136 {
1137 LOCK(m_total_bytes_sent_mutex);
1138 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1139 }
1140 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1141 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1142 {
1143 LOCK(m_added_nodes_mutex);
1144 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1145 // peer doesn't support it or immediately disconnects us for another reason.
1146 const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1147 for (const std::string& added_node : connOptions.m_added_nodes) {
1148 m_added_node_params.push_back({added_node, use_v2transport});
1149 }
1150 }
1151 m_onion_binds = connOptions.onion_binds;
1152 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1153 whitelist_relay = connOptions.whitelist_relay;
1154 m_capture_messages = connOptions.m_capture_messages;
1155 }
1156
1157 // test only
1158 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1159
1160 CConnman(uint64_t seed0,
1161 uint64_t seed1,
1162 AddrMan& addrman,
1163 const NetGroupManager& netgroupman,
1164 const CChainParams& params,
1165 bool network_active = true,
1166 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1167
1168 ~CConnman();
1169
1170 bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1171
1172 void StopThreads();
1173 void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex);
1174 void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex)
1175 {
1176 AssertLockNotHeld(m_nodes_mutex);
1177 AssertLockNotHeld(m_reconnections_mutex);
1180 };
1181
1182 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1183 bool GetNetworkActive() const { return fNetworkActive; };
1184 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1185 void SetNetworkActive(bool active);
1186
1199 bool OpenNetworkConnection(const CAddress& addrConnect,
1200 bool fCountFailure,
1201 CountingSemaphoreGrant<>&& grant_outbound,
1202 const char* pszDest,
1203 ConnectionType conn_type,
1204 bool use_v2transport,
1205 const std::optional<Proxy>& proxy_override)
1206 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);
1207
1210 {
1211 public:
1220 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1221
1226 std::counting_semaphore<> m_sem_conn_max{MAX_PRIVATE_BROADCAST_CONNECTIONS};
1227
1237 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1238
1240 size_t NumToOpen() const;
1241
1247 void NumToOpenAdd(size_t n);
1248
1255 size_t NumToOpenSub(size_t n);
1256
1258 void NumToOpenWait() const;
1259
1260 protected:
1266 std::optional<Proxy> ProxyForIPv4or6() const;
1267
1269 std::atomic_size_t m_num_to_open{0};
1270
1271 friend struct ConnmanTestMsg;
1273
1275 void ASMapHealthCheck();
1276
1277 // alias for thread safety annotations only, not defined
1279
1280 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1281
1283
1284 using NodeFn = std::function<void(CNode*)>;
1286 {
1288 for (auto&& node : m_nodes) {
1290 func(node);
1291 }
1292 };
1293
1295 {
1297 for (auto&& node : m_nodes) {
1299 func(node);
1300 }
1301 };
1302
1303 // Addrman functions
1315 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1330 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1331
1332 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1333 // a peer that is better than all our current peers.
1334 void SetTryNewOutboundPeer(bool flag);
1335 bool GetTryNewOutboundPeer() const;
1336
1338
1339 // Count the number of full-relay peer we have.
1341 // Return the number of outbound peers we have in excess of our target (eg,
1342 // if we previously called SetTryNewOutboundPeer(true), and have since set
1343 // to false, we may have extra peers that we wish to disconnect). This may
1344 // return a value less than (num_outbound_connections - num_outbound_slots)
1345 // in cases where some outbound connections are not yet fully connected, or
1346 // not yet fully disconnected.
1348 // Count the number of block-relay-only peers we have over our limit.
1359 bool EvictTxPeerIfFull(std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1360
1364 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const
1366
1380 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)
1382
1385 uint32_t GetMappedAS(const CNetAddr& addr) const;
1386 void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1391
1399
1404
1406 std::chrono::seconds GetMaxOutboundTimeframe() const;
1407
1411 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1412
1416
1418
1419 uint64_t GetTotalBytesRecv() const;
1421
1423 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1424
1426
1428 bool ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const;
1429
1431
1432private:
1434 public:
1435 std::shared_ptr<Sock> sock;
1437 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1438 : sock{sock_}, m_permissions{permissions_}
1439 {
1440 }
1441
1442 private:
1444 };
1445
1449
1450 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1451 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1452 bool InitBinds(const Options& options);
1453
1459
1460 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1461
1465
1467 void ThreadOpenConnections(std::vector<std::string> connect, std::span<const std::string> seed_nodes)
1473
1480
1489 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1490 NetPermissionFlags permission_flags,
1491 const CService& addr_bind,
1492 const CService& addr)
1494
1498 bool InactivityCheck(const CNode& node, NodeClock::time_point now) const;
1499
1505 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1506
1511
1517 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1518 const Sock::EventsPerSock& events_per_sock)
1520
1525 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
1527
1532
1533 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1534
1542 bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1543
1552
1557
1564 bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
1565
1576 CNode* ConnectNode(CAddress addrConnect,
1577 const char* pszDest,
1578 bool fCountFailure,
1579 ConnectionType conn_type,
1580 bool use_v2transport,
1581 const std::optional<Proxy>& proxy_override)
1583
1584 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1585
1586 void DeleteNode(CNode* pnode);
1587
1589
1591 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1592
1593 void DumpAddresses();
1594
1595 // Network stats
1596 void RecordBytesRecv(uint64_t bytes);
1598
1603 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1604
1609
1621
1622 // Whether the node should be passed out in ForEach* callbacks
1623 static bool NodeFullyConnected(const CNode* pnode);
1624
1625 uint16_t GetDefaultPort(Network net) const;
1626 uint16_t GetDefaultPort(const std::string& addr) const;
1627
1628 // Network usage totals
1630 std::atomic<uint64_t> nTotalBytesRecv{0};
1631 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1632
1633 // outbound limit & stats
1634 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1635 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1637
1638 // P2P timeout in seconds
1639 std::chrono::seconds m_peer_connect_timeout;
1640
1641 // Whitelisted ranges. Any node connecting from these is automatically
1642 // whitelisted (as well as those connecting to whitelisted binds).
1643 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1644 // Whitelisted ranges for outgoing connections.
1645 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1646
1647 unsigned int nSendBufferMaxSize{0};
1648 unsigned int nReceiveFloodSize{0};
1649
1650 std::vector<ListenSocket> vhListenSocket;
1651 std::atomic<bool> fNetworkActive{true};
1653 std::reference_wrapper<AddrMan> addrman;
1655 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1657
1658 // connection string and whether to use v2 p2p
1659 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1660
1662 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1663 std::list<CNode*> m_nodes_disconnected;
1665 std::atomic<NodeId> nLastNodeId{0};
1666 unsigned int nPrevNodeCount{0};
1667
1668 // Stores number of full-tx connections (outbound and manual) per network
1669 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1670
1678 std::vector<CAddress> m_addrs_response_cache;
1679 std::chrono::microseconds m_cache_entry_expiration{0};
1680 };
1681
1696 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1697
1709 std::atomic<ServiceFlags> m_local_services;
1710
1711 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1712 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1713
1720
1721 /*
1722 * Maximum number of peers by connection type. Might vary from defaults
1723 * based on -maxconnections init value.
1724 */
1725
1726 // How many full-relay (tx, block, addr) outbound peers we want
1728
1729 // How many block-relay only outbound peers we want
1730 // We do not relay tx or addr messages with these peers
1732
1733 int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1734 int m_max_feeler{MAX_FEELER_CONNECTIONS};
1738
1744
1749 std::vector<CAddress> m_anchors;
1750
1752 const uint64_t nSeed0, nSeed1;
1753
1755 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1756
1757 std::condition_variable condMsgProc;
1759 std::atomic<bool> flagInterruptMsgProc{false};
1760
1765 const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1766
1772 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1773
1781
1786
1791 std::atomic_bool m_start_extra_block_relay_peers{false};
1792
1797 std::vector<CService> m_onion_binds;
1798
1804
1810
1814 bool m_capture_messages{false};
1815
1820
1828 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1829
1834
1837 {
1838 std::optional<Proxy> proxy_override;
1841 std::string destination;
1844 };
1845
1849 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1850
1852 void PerformReconnections()
1853 EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1854
1859 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1860
1866 {
1867 public:
1868 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1869 EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
1870 {
1871 {
1872 LOCK(connman.m_nodes_mutex);
1873 m_nodes_copy = connman.m_nodes;
1874 for (auto& node : m_nodes_copy) {
1875 node->AddRef();
1876 }
1877 }
1878 if (shuffle) {
1879 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1880 }
1881 }
1882
1884 {
1885 for (auto& node : m_nodes_copy) {
1886 node->Release();
1887 }
1888 }
1889
1890 const std::vector<CNode*>& Nodes() const
1891 {
1892 return m_nodes_copy;
1893 }
1894
1895 private:
1896 std::vector<CNode*> m_nodes_copy;
1897 };
1898
1900
1901 friend struct ConnmanTestMsg;
1902};
1903
1905extern std::function<void(const CAddress& addr,
1906 const std::string& msg_type,
1907 std::span<const unsigned char> data,
1908 bool is_incoming)>
1910
1911#endif // BITCOIN_NET_H
int ret
int flags
Definition: bitcoin-tx.cpp:530
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
Stochastic address manager.
Definition: addrman.h:110
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:22
Definition: banman.h:64
A CService with information about it as peer.
Definition: protocol.h:387
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
Signals for UI communication.
Definition: interface_ui.h:22
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1866
const std::vector< CNode * > & Nodes() const
Definition: net.h:1890
NodesSnapshot(const CConnman &connman, bool shuffle) EXCLUSIVE_LOCKS_REQUIRED(!connman.m_nodes_mutex)
Definition: net.h:1868
std::vector< CNode * > m_nodes_copy
Definition: net.h:1896
Group of private broadcast related members.
Definition: net.h:1210
Definition: net.h:1085
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1809
void AcceptConnection(const ListenSocket &hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:1751
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:2555
std::condition_variable condMsgProc
Definition: net.h:1757
std::thread threadMessageHandler
Definition: net.h:1778
nSendBufferMaxSize
Definition: net.h:1133
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1403
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1643
CClientUIInterface * m_client_interface
Definition: net.h:1740
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:2574
std::reference_wrapper< AddrMan > addrman
Definition: net.h:1653
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition: net.cpp:1938
void DeleteNode(CNode *pnode)
Definition: net.cpp:3770
void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3257
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2468
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
int m_max_inbound
Definition: net.h:1736
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
class CConnman::PrivateBroadcast m_private_broadcast
uint16_t GetDefaultPort(Network net) const
Definition: net.cpp:3493
int m_max_outbound_block_relay
Definition: net.h:1731
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
bool AlreadyConnectedToAddress(const CNetAddr &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address.
Definition: net.cpp:353
bool ShouldRunInactivityChecks(const CNode &node, NodeClock::time_point now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:2035
void SetCaptureMessages(bool cap)
Definition: net.h:1158
std::thread threadI2PAcceptIncoming
Definition: net.h:1779
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
Definition: net.cpp:3794
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2473
std::list< ReconnectionInfo > m_reconnections GUARDED_BY(m_reconnections_mutex)
List of reconnections we have to make.
int m_max_automatic_outbound
Definition: net.h:1735
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition: net.cpp:3886
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2290
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2976
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:3488
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
std::atomic< NodeId > nLastNodeId
Definition: net.h:1665
bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given "host:port".
Definition: net.cpp:341
bool fMsgProcWake GUARDED_BY(mutexMsgProc)
flag for waking the message processor.
int m_max_automatic_connections
Maximum number of automatic connections permitted, excluding manual connections but including inbound...
Definition: net.h:1719
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2281
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1743
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
Definition: net.cpp:4015
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1634
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:2255
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3981
std::thread threadDNSAddressSeed
Definition: net.h:1774
void ForEachNode(const NodeFn &func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.h:1294
void ASMapHealthCheck()
Definition: net.cpp:4279
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:1893
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:2153
void StartExtraBlockRelayPeers()
Definition: net.cpp:2479
const NetGroupManager & m_netgroupman
Definition: net.h:1654
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1749
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:3988
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition: net.cpp:4243
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1803
unsigned int nPrevNodeCount
Definition: net.h:1666
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:580
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:4058
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3832
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2990
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection.
Definition: net.cpp:378
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1639
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:1785
bool InitBinds(const Options &options)
Definition: net.cpp:3523
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:133
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1650
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:4238
Mutex m_total_bytes_sent_mutex
Definition: net.h:1629
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:3052
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:3504
bool EvictTxPeerIfFull(std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
If we are at capacity for inbound tx-relay peers, attempt to evict one.
Definition: net.cpp:2538
std::thread threadOpenConnections
Definition: net.h:1777
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition: net.h:1709
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition: net.cpp:3302
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition: net.cpp:3892
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2440
Mutex m_addr_fetches_mutex
Definition: net.h:1656
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1833
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1752
m_local_services
Definition: net.h:1122
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
Definition: net.cpp:4000
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:4046
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:1607
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:4147
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition: net.h:1711
nReceiveFloodSize
Definition: net.h:1134
const CChainParams & m_params
Definition: net.h:1899
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
Definition: net.cpp:2568
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3858
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
bool InactivityCheck(const CNode &node, NodeClock::time_point now) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:2040
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3993
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition: net.h:1765
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:1781
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2592
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:1694
void GetNodeStats(std::vector< CNodeStats > &vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3897
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake.
Definition: net.h:1402
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:4223
std::thread threadPrivateBroadcast
Definition: net.h:1780
Mutex mutexMsgProc
Definition: net.h:1758
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3846
bool fAddressesInitialized
Definition: net.h:1652
std::vector< CAddress > GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return randomly selected addresses.
Definition: net.cpp:3783
void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2018
int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2522
std::thread threadOpenAddedConnections
Definition: net.h:1776
bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3911
Mutex m_added_nodes_mutex
Definition: net.h:1661
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2270
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3963
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Definition: net.cpp:3216
Mutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
int m_max_outbound_full_relay
Definition: net.h:1727
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1819
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
int m_max_inbound_full_relay
Definition: net.h:1737
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4051
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition: net.h:1712
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:3869
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3958
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1635
int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2506
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
Definition: net.cpp:4036
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:2124
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1631
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4163
bool GetUseAddrmanOutgoing() const
Definition: net.h:1184
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1663
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1772
bool m_use_addrman_outgoing
Definition: net.h:1739
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1645
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:1696
bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:359
std::function< void(CNode *)> NodeFn
Definition: net.h:1284
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:2093
NetEventsInterface * m_msgproc
Definition: net.h:1741
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1630
std::atomic< bool > fNetworkActive
Definition: net.h:1651
AssertLockNotHeld(m_reconnections_mutex)
void DumpAddresses()
Definition: net.cpp:2430
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
Definition: net.h:1797
Mutex m_nodes_mutex
Definition: net.h:1664
std::thread threadSocketHandler
Definition: net.h:1775
nMaxOutboundLimit
Definition: net.h:1138
int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition: net.cpp:2486
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:3371
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:32
An encapsulated private key.
Definition: key.h:37
Message header.
Definition: protocol.h:29
Network address.
Definition: netaddress.h:113
Transport protocol agnostic message container.
Definition: net.h:239
CNetMessage(CNetMessage &&)=default
CNetMessage(DataStream &&recv_in)
Definition: net.h:248
std::string m_type
Definition: net.h:246
DataStream m_recv
received message data
Definition: net.h:241
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition: net.h:683
bool IsFeelerConn() const
Definition: net.h:823
bool ExpectServicesFromConn() const
Definition: net.h:847
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:727
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:711
bool IsInboundConn() const
Definition: net.h:843
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:738
CountingSemaphoreGrant grantOutbound
Definition: net.h:746
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:778
NodeId GetId() const
Definition: net.h:928
bool IsManualConn() const
Definition: net.h:798
const std::string m_addr_name
Definition: net.h:725
CNode & operator=(const CNode &)=delete
const CService addrBind
Definition: net.h:724
void SetCommonVersion(int greatest_common_version)
Definition: net.h:953
std::list< CNetMessage > vRecvMsg
Definition: net.h:1011
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:1015
bool IsAddrFetchConn() const
Definition: net.h:827
uint64_t GetLocalNonce() const
Definition: net.h:932
const CAddress addr
Definition: net.h:722
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
Definition: net.h:716
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:749
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session GUARDED_BY(m_sock_mutex)
If an I2P session is created per connection (for outbound transient I2P connections) then it is store...
bool IsBlockOnlyConn() const
Definition: net.h:819
int GetCommonVersion() const
Definition: net.h:958
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:794
Mutex m_subver_mutex
Definition: net.h:731
Mutex cs_vSend
Definition: net.h:707
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition: net.h:755
int GetRefCount() const
Definition: net.h:936
void PongReceived(NodeClock::duration ping_time)
A ping-pong round trip has completed successfully. Update latest and minimum ping durations.
Definition: net.h:999
Mutex m_msg_process_queue_mutex
Definition: net.h:1013
const ConnectionType m_conn_type
Definition: net.h:757
const size_t m_recv_flood_size
Definition: net.h:1010
const uint64_t nLocalHostNonce
Definition: net.h:1007
bool IsManualOrFullOutboundConn() const
Definition: net.h:802
bool IsPrivateBroadcastConn() const
Definition: net.h:831
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:687
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:689
Mutex m_addr_local_mutex
Definition: net.h:1019
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition: net.h:702
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:729
const NodeId id
Definition: net.h:1006
Mutex cs_vRecv
Definition: net.h:709
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:704
int AdvertisedVersion() const
Protocol version advertised in our VERSION message.
Definition: net.h:838
Mutex m_sock_mutex
Definition: net.h:708
const std::optional< Proxy > m_proxy_override
Proxy to use regardless of global proxy settings if reconnecting to this node.
Definition: net.h:719
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:973
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:736
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:230
std::string addrLocal
Definition: net.h:218
NodeClock::duration m_min_ping_time
Definition: net.h:216
uint64_t nRecvBytes
Definition: net.h:212
uint32_t m_mapped_as
Definition: net.h:225
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:213
bool fInbound
Definition: net.h:205
uint64_t nSendBytes
Definition: net.h:210
ConnectionType m_conn_type
Definition: net.h:226
std::chrono::seconds m_last_tx_time
Definition: net.h:199
CAddress addr
Definition: net.h:220
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:211
CService addrBind
Definition: net.h:222
NodeClock::time_point m_last_recv
Definition: net.h:198
NodeClock::time_point m_last_send
Definition: net.h:197
NodeClock::duration m_last_ping_time
Definition: net.h:215
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:228
bool m_bip152_highbandwidth_from
Definition: net.h:209
bool m_bip152_highbandwidth_to
Definition: net.h:207
std::string m_addr_name
Definition: net.h:202
NodeClock::time_point m_connected
Definition: net.h:201
int nVersion
Definition: net.h:203
std::chrono::seconds m_last_block_time
Definition: net.h:200
Network m_network
Definition: net.h:224
NodeId nodeid
Definition: net.h:196
std::string cleanSubVer
Definition: net.h:204
NetPermissionFlags m_permission_flags
Definition: net.h:214
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:530
General SipHash-2-4 implementation.
Definition: siphash.h:99
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:165
Fast randomness source.
Definition: random.h:386
Different type to mark Mutex at global scope.
Definition: sync.h:142
Definition: init.h:13
Interface for message handling.
Definition: net.h:1041
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1044
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
virtual bool ProcessMessages(CNode &node, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from a given node.
virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const =0
Callback to determine whether the given set of service flags are sufficient for a peer to be "relevan...
virtual bool SendMessages(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state)
Netgroup manager.
Definition: netgroup.h:17
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
Definition: netbase.h:61
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:35
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition: net.h:263
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:320
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition: net.h:385
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition: net.h:421
const NodeId m_node_id
Definition: net.h:380
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:415
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:423
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:379
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition: net.h:387
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:407
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:381
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:428
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:621
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:589
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:585
SendState
State type that controls the sender side.
Definition: net.h:554
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:591
Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex)
Lock for sending-side fields.
SendState m_send_state GUARDED_BY(m_send_mutex)
Current sender state.
std::string m_send_type GUARDED_BY(m_send_mutex)
Type of the message being sent.
const bool m_initiating
Whether we are the initiator side.
Definition: net.h:587
std::vector< uint8_t > m_recv_buffer GUARDED_BY(m_recv_mutex)
Receive buffer; meaning is determined by m_recv_state.
std::vector< uint8_t > m_send_garbage GUARDED_BY(m_send_mutex)
The garbage sent, or to be sent (MAYBE_V1 and AWAITING_KEY state only).
uint32_t m_recv_len GUARDED_BY(m_recv_mutex)
In {VERSION, APP}, the decrypted packet length, if m_recv_buffer.size() >= BIP324Cipher::LENGTH_LEN.
Definition: net.h:597
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:613
RecvState m_recv_state GUARDED_BY(m_recv_mutex)
Current receiver state.
Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex)
Lock for receiver-side fields.
std::vector< uint8_t > m_recv_aad GUARDED_BY(m_recv_mutex)
AAD expected in next received packet (currently used only for garbage).
std::vector< uint8_t > m_recv_decode_buffer GUARDED_BY(m_recv_mutex)
Buffer to put decrypted contents in, for converting to CNetMessage.
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
Definition: net.h:489
256-bit opaque blob.
Definition: uint256.h:196
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
TransportProtocolType
Transport layer version.
@ V1
Unencrypted, plaintext protocol.
CClientUIInterface uiInterface
std::thread thread
Thread variable should be after other struct members so the thread does not start until the other mem...
std::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
Definition: miniscript.h:199
Definition: messages.h:22
static const unsigned char VERSION[]
Definition: netaddress.cpp:188
const std::string KEY
Definition: walletdb.cpp:44
uint16_t GetListenPort()
Definition: net.cpp:139
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:91
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:335
void RemoveLocal(const CService &addr)
Definition: net.cpp:313
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 fDiscover
Definition: net.cpp:117
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:101
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:93
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:99
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:87
void ClearLocal()
Definition: net.cpp:271
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:118
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:100
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:121
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:85
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:241
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:109
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:191
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:97
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:98
int64_t NodeId
Definition: net.h:105
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:221
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:119
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:95
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE, bool add_even_if_unreachable=false)
Definition: net.cpp:278
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:89
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:4333
static const int DEFAULT_FULL_RELAY_INBOUND_PCT
Default percentage of inbound connection slots that tx-relaying peers can use.
Definition: net.h:83
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
@ LOCAL_NONE
Definition: net.h:156
@ LOCAL_MAPPED
Definition: net.h:159
@ LOCAL_MANUAL
Definition: net.h:160
@ LOCAL_MAX
Definition: net.h:162
@ LOCAL_BIND
Definition: net.h:158
@ LOCAL_IF
Definition: net.h:157
static constexpr bool DEFAULT_V2_TRANSPORT
Definition: net.h:103
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:3440
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
static const int WTXID_RELAY_VERSION
"wtxidrelay" message type for wtxid-based relay starts with this version
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
static const int PROTOCOL_VERSION
network protocol versioning
bool fInbound
Definition: net.h:116
CService resolvedAddress
Definition: net.h:114
AddedNodeParams m_params
Definition: net.h:113
bool fConnected
Definition: net.h:115
std::string m_added_node
Definition: net.h:108
bool m_use_v2transport
Definition: net.h:109
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1677
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1678
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1436
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1437
NetPermissionFlags m_permissions
Definition: net.h:1443
std::shared_ptr< Sock > sock
Definition: net.h:1435
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1103
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1101
std::vector< CService > onion_binds
Definition: net.h:1105
std::vector< std::string > m_specified_outgoing
Definition: net.h:1110
std::vector< std::string > m_added_nodes
Definition: net.h:1111
std::vector< CService > vBinds
Definition: net.h:1104
bool m_i2p_accept_incoming
Definition: net.h:1112
std::vector< std::string > vSeedNodes
Definition: net.h:1100
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:1108
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1102
Struct for entries in m_reconnections.
Definition: net.h:1837
std::optional< Proxy > proxy_override
Definition: net.h:1838
ConnectionType conn_type
Definition: net.h:1842
std::string destination
Definition: net.h:1841
CountingSemaphoreGrant grant
Definition: net.h:1840
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:130
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:139
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:138
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:184
int nScore
Definition: net.h:183
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:270
TransportProtocolType transport_type
Definition: net.h:269
Bilingual messages:
Definition: translation.h:24
#define AssertLockNotHeld(cs)
Definition: sync.h:149
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())