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 = 125;
83static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
85static const bool DEFAULT_BLOCKSONLY = false;
87static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
89static constexpr bool DEFAULT_PRIVATE_BROADCAST{false};
91static const int NUM_FDS_MESSAGE_CAPTURE = 1;
93static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
94
95static constexpr bool DEFAULT_FORCEDNSSEED{false};
96static constexpr bool DEFAULT_DNSSEED{true};
97static constexpr bool DEFAULT_FIXEDSEEDS{true};
98static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
99static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
100
101static constexpr bool DEFAULT_V2_TRANSPORT{true};
102
103typedef int64_t NodeId;
104
106 std::string m_added_node;
108};
109
115};
116
117class CNodeStats;
119
121 CSerializedNetMsg() = default;
124 // No implicit copying, only moves.
127
129 {
131 copy.data = data;
132 copy.m_type = m_type;
133 return copy;
134 }
135
136 std::vector<unsigned char> data;
137 std::string m_type;
138
140 size_t GetMemoryUsage() const noexcept;
141};
142
148void Discover();
149
150uint16_t GetListenPort();
151
152enum
153{
154 LOCAL_NONE, // unknown
155 LOCAL_IF, // address a local interface listens on
156 LOCAL_BIND, // address explicit bound to
157 LOCAL_MAPPED, // address reported by PCP
158 LOCAL_MANUAL, // address explicitly specified (-externalip=)
159
162
164std::optional<CService> GetLocalAddrForPeer(CNode& node);
165
166void ClearLocal();
167bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
168bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
169void RemoveLocal(const CService& addr);
170bool SeenLocal(const CService& addr);
171bool IsLocal(const CService& addr);
172CService GetLocalAddress(const CNode& peer);
173
174extern bool fDiscover;
175extern bool fListen;
176
178extern std::string strSubVersion;
179
182 uint16_t nPort;
183};
184
186extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
187
188extern const std::string NET_MESSAGE_TYPE_OTHER;
189using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
190
192{
193public:
195 std::chrono::seconds m_last_send;
196 std::chrono::seconds m_last_recv;
197 std::chrono::seconds m_last_tx_time;
198 std::chrono::seconds m_last_block_time;
199 std::chrono::seconds m_connected;
200 std::string m_addr_name;
202 std::string cleanSubVer;
204 // We requested high bandwidth connection to peer
206 // Peer requested high bandwidth connection
208 uint64_t nSendBytes;
210 uint64_t nRecvBytes;
213 std::chrono::microseconds m_last_ping_time;
214 std::chrono::microseconds m_min_ping_time;
215 // Our address, as reported by the peer
216 std::string addrLocal;
217 // Address of this peer
219 // Bind address of our side of the connection
221 // Network the peer connected through
223 uint32_t m_mapped_as;
228 std::string m_session_id;
229};
230
231
237{
238public:
240 std::chrono::microseconds m_time{0};
241 uint32_t m_message_size{0};
242 uint32_t m_raw_message_size{0};
243 std::string m_type;
244
245 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
246 // Only one CNetMessage object will exist for the same message on either
247 // the receive or processing queue. For performance reasons we therefore
248 // delete the copy constructor and assignment operator to avoid the
249 // possibility of copying CNetMessage objects.
251 CNetMessage(const CNetMessage&) = delete;
254
256 size_t GetMemoryUsage() const noexcept;
257};
258
261public:
262 virtual ~Transport() = default;
263
264 struct Info
265 {
267 std::optional<uint256> session_id;
268 };
269
271 virtual Info GetInfo() const noexcept = 0;
272
273 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
274 // agnostic CNetMessage (message type & payload) objects.
275
277 virtual bool ReceivedMessageComplete() const = 0;
278
285 virtual bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) = 0;
286
294 virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
295
296 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
297
304 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
305
313 using BytesToSend = std::tuple<
314 std::span<const uint8_t> /*to_send*/,
315 bool /*more*/,
316 const std::string& /*m_type*/
317 >;
318
354 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
355
362 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
363
365 virtual size_t GetSendMemoryUsage() const noexcept = 0;
366
367 // 3. Miscellaneous functions.
368
370 virtual bool ShouldReconnectV1() const noexcept = 0;
371};
372
373class V1Transport final : public Transport
374{
375private:
377 const NodeId m_node_id; // Only for logging
379 mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
380 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
381 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
382 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
383 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
384 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
385 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
386 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
387
388 const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
389 int readHeader(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
390 int readData(std::span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
391
392 void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
393 AssertLockHeld(m_recv_mutex);
394 vRecv.clear();
395 hdrbuf.clear();
396 hdrbuf.resize(24);
397 in_data = false;
398 nHdrPos = 0;
399 nDataPos = 0;
400 data_hash.SetNull();
401 hasher.Reset();
402 }
403
404 bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
405 {
406 AssertLockHeld(m_recv_mutex);
407 if (!in_data) return false;
408 return hdr.nMessageSize == nDataPos;
409 }
410
414 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
416 CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
418 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
420 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
421
422public:
423 explicit V1Transport(NodeId node_id) noexcept;
424
425 bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
426 {
427 AssertLockNotHeld(m_recv_mutex);
428 return WITH_LOCK(m_recv_mutex, return CompleteInternal());
429 }
430
431 Info GetInfo() const noexcept override;
432
433 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
434 {
435 AssertLockNotHeld(m_recv_mutex);
436 LOCK(m_recv_mutex);
437 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
438 if (ret < 0) {
439 Reset();
440 } else {
441 msg_bytes = msg_bytes.subspan(ret);
442 }
443 return ret >= 0;
444 }
445
446 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
447
448 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
449 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
450 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
451 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
452 bool ShouldReconnectV1() const noexcept override { return false; }
453};
454
455class V2Transport final : public Transport
456{
457private:
461 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
462
465 static constexpr size_t V1_PREFIX_LEN = 16;
466
467 // The sender side and receiver side of V2Transport are state machines that are transitioned
468 // through, based on what has been received. The receive state corresponds to the contents of,
469 // and bytes received to, the receive buffer. The send state controls what can be appended to
470 // the send buffer and what can be sent from it.
471
486 enum class RecvState : uint8_t {
492 KEY_MAYBE_V1,
493
499 KEY,
500
507 GARB_GARBTERM,
508
517 VERSION,
518
524 APP,
525
530 APP_READY,
531
535 V1,
536 };
537
551 enum class SendState : uint8_t {
558 MAYBE_V1,
559
565 AWAITING_KEY,
566
573 READY,
574
578 V1,
579 };
580
584 const bool m_initiating;
589
591 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
594 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
596 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
598 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
600 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
602 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
603
606 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
608 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
610 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
612 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
614 std::string m_send_type GUARDED_BY(m_send_mutex);
616 SendState m_send_state GUARDED_BY(m_send_mutex);
618 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
619
621 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
623 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
625 static std::optional<std::string> GetMessageType(std::span<const uint8_t>& contents) noexcept;
627 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
629 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
631 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
633 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
635 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
637 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
638
639public:
640 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
641
647 V2Transport(NodeId nodeid, bool initiating) noexcept;
648
650 V2Transport(NodeId nodeid, bool initiating, const CKey& key, std::span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
651
652 // Receive side functions.
653 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
654 bool ReceivedBytes(std::span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
655 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
656
657 // Send side functions.
658 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
659 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
660 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
661 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
662
663 // Miscellaneous functions.
664 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
665 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
666};
667
669{
671 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
672 bool prefer_evict = false;
673 size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
674 bool use_v2transport = false;
675};
676
678class CNode
679{
680public:
683 const std::unique_ptr<Transport> m_transport;
684
686
695 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
696
698 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
700 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
702 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
706
707 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
708
709 std::atomic<std::chrono::seconds> m_last_send{0s};
710 std::atomic<std::chrono::seconds> m_last_recv{0s};
712 const std::chrono::seconds m_connected;
713 // Address of this peer
715 // Bind address of our side of the connection
717 const std::string m_addr_name;
719 const std::string m_dest;
721 const bool m_inbound_onion;
722 std::atomic<int> nVersion{0};
728 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
729 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
730 bool HasPermission(NetPermissionFlags permission) const {
731 return NetPermissions::HasFlag(m_permission_flags, permission);
732 }
734 std::atomic_bool fSuccessfullyConnected{false};
735 // Setting fDisconnect to true will cause the node to be disconnected the
736 // next time DisconnectNodes() runs
737 std::atomic_bool fDisconnect{false};
739 std::atomic<int> nRefCount{0};
740
741 const uint64_t nKeyedNetGroup;
742 std::atomic_bool fPauseRecv{false};
743 std::atomic_bool fPauseSend{false};
744
747 const uint64_t m_network_key;
748
750
752 void MarkReceivedMsgsForProcessing()
753 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
754
760 std::optional<std::pair<CNetMessage, bool>> PollMessage()
761 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
762
764 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
766 {
767 mapSendBytesPerMsgType[msg_type] += sent_bytes;
768 }
769
771 switch (m_conn_type) {
774 return true;
780 return false;
781 } // no default case, so the compiler can warn about missing cases
782
783 assert(false);
784 }
785
786 bool IsFullOutboundConn() const {
787 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
788 }
789
790 bool IsManualConn() const {
791 return m_conn_type == ConnectionType::MANUAL;
792 }
793
795 {
796 switch (m_conn_type) {
802 return false;
805 return true;
806 } // no default case, so the compiler can warn about missing cases
807
808 assert(false);
809 }
810
811 bool IsBlockOnlyConn() const {
812 return m_conn_type == ConnectionType::BLOCK_RELAY;
813 }
814
815 bool IsFeelerConn() const {
816 return m_conn_type == ConnectionType::FEELER;
817 }
818
819 bool IsAddrFetchConn() const {
820 return m_conn_type == ConnectionType::ADDR_FETCH;
821 }
822
824 {
825 return m_conn_type == ConnectionType::PRIVATE_BROADCAST;
826 }
827
828 bool IsInboundConn() const {
829 return m_conn_type == ConnectionType::INBOUND;
830 }
831
833 switch (m_conn_type) {
837 return false;
842 return true;
843 } // no default case, so the compiler can warn about missing cases
844
845 assert(false);
846 }
847
858 Network ConnectedThroughNetwork() const;
859
861 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
862
863 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
864 std::atomic<bool> m_bip152_highbandwidth_to{false};
865 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
866 std::atomic<bool> m_bip152_highbandwidth_from{false};
867
869 std::atomic_bool m_has_all_wanted_services{false};
870
873 std::atomic_bool m_relays_txs{false};
874
877 std::atomic_bool m_bloom_filter_loaded{false};
878
884 std::atomic<std::chrono::seconds> m_last_block_time{0s};
885
890 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
891
893 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
894
897 std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
898
899 CNode(NodeId id,
900 std::shared_ptr<Sock> sock,
901 const CAddress& addrIn,
902 uint64_t nKeyedNetGroupIn,
903 uint64_t nLocalHostNonceIn,
904 const CService& addrBindIn,
905 const std::string& addrNameIn,
906 ConnectionType conn_type_in,
907 bool inbound_onion,
908 uint64_t network_key,
909 CNodeOptions&& node_opts = {});
910 CNode(const CNode&) = delete;
911 CNode& operator=(const CNode&) = delete;
912
913 NodeId GetId() const {
914 return id;
915 }
916
917 uint64_t GetLocalNonce() const {
918 return nLocalHostNonce;
919 }
920
921 int GetRefCount() const
922 {
923 assert(nRefCount >= 0);
924 return nRefCount;
925 }
926
936 bool ReceiveMsgBytes(std::span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
937
938 void SetCommonVersion(int greatest_common_version)
939 {
940 Assume(m_greatest_common_version == INIT_PROTO_VERSION);
941 m_greatest_common_version = greatest_common_version;
942 }
944 {
945 return m_greatest_common_version;
946 }
947
948 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
950 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
951
952 CNode* AddRef()
953 {
954 nRefCount++;
955 return this;
956 }
957
958 void Release()
959 {
960 nRefCount--;
961 }
962
963 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
964
965 void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
966
968
974 std::string LogPeer() const;
975
981 std::string DisconnectMsg() const;
982
984 void PongReceived(std::chrono::microseconds ping_time) {
985 m_last_ping_time = ping_time;
986 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
987 }
988
989private:
990 const NodeId id;
991 const uint64_t nLocalHostNonce;
992 std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
993
994 const size_t m_recv_flood_size;
995 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
996
998 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
999 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
1000
1001 // Our address, as reported by the peer
1002 CService m_addr_local GUARDED_BY(m_addr_local_mutex);
1004
1005 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
1006 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
1007
1018 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
1019};
1020
1025{
1026public:
1029
1031 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
1032
1034 virtual void FinalizeNode(const CNode& node) = 0;
1035
1040 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1041
1049 virtual bool ProcessMessages(CNode& node, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1050
1057 virtual bool SendMessages(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1058
1059
1060protected:
1066};
1067
1069{
1070public:
1071
1072 struct Options
1073 {
1074 ServiceFlags m_local_services = NODE_NONE;
1075 int m_max_automatic_connections = 0;
1077 NetEventsInterface* m_msgproc = nullptr;
1078 BanMan* m_banman = nullptr;
1079 unsigned int nSendBufferMaxSize = 0;
1080 unsigned int nReceiveFloodSize = 0;
1081 uint64_t nMaxOutboundLimit = 0;
1082 int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1083 std::vector<std::string> vSeedNodes;
1084 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1085 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1086 std::vector<NetWhitebindPermissions> vWhiteBinds;
1087 std::vector<CService> vBinds;
1088 std::vector<CService> onion_binds;
1092 bool m_use_addrman_outgoing = true;
1093 std::vector<std::string> m_specified_outgoing;
1094 std::vector<std::string> m_added_nodes;
1096 bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1097 bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1098 bool m_capture_messages = false;
1099 };
1100
1101 void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1102 {
1103 AssertLockNotHeld(m_total_bytes_sent_mutex);
1104
1105 m_local_services = connOptions.m_local_services;
1106 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1107 m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1108 m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1109 m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1110 m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1111 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1112 m_client_interface = connOptions.uiInterface;
1113 m_banman = connOptions.m_banman;
1114 m_msgproc = connOptions.m_msgproc;
1115 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1116 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1117 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1118 {
1119 LOCK(m_total_bytes_sent_mutex);
1120 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1121 }
1122 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1123 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1124 {
1125 LOCK(m_added_nodes_mutex);
1126 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1127 // peer doesn't support it or immediately disconnects us for another reason.
1128 const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1129 for (const std::string& added_node : connOptions.m_added_nodes) {
1130 m_added_node_params.push_back({added_node, use_v2transport});
1131 }
1132 }
1133 m_onion_binds = connOptions.onion_binds;
1134 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1135 whitelist_relay = connOptions.whitelist_relay;
1136 m_capture_messages = connOptions.m_capture_messages;
1137 }
1138
1139 // test only
1140 void SetCaptureMessages(bool cap) { m_capture_messages = cap; }
1141
1142 CConnman(uint64_t seed0,
1143 uint64_t seed1,
1144 AddrMan& addrman,
1145 const NetGroupManager& netgroupman,
1146 const CChainParams& params,
1147 bool network_active = true,
1148 std::shared_ptr<CThreadInterrupt> interrupt_net = std::make_shared<CThreadInterrupt>());
1149
1150 ~CConnman();
1151
1152 bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1153
1154 void StopThreads();
1155 void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex);
1156 void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex)
1157 {
1158 AssertLockNotHeld(m_reconnections_mutex);
1159 StopThreads();
1160 StopNodes();
1161 };
1162
1163 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1164 bool GetNetworkActive() const { return fNetworkActive; };
1165 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1166 void SetNetworkActive(bool active);
1167
1180 bool OpenNetworkConnection(const CAddress& addrConnect,
1181 bool fCountFailure,
1182 CountingSemaphoreGrant<>&& grant_outbound,
1183 const char* pszDest,
1184 ConnectionType conn_type,
1185 bool use_v2transport,
1186 const std::optional<Proxy>& proxy_override = std::nullopt)
1187 EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1188
1191 {
1192 public:
1201 std::atomic_bool m_outbound_tor_ok_at_least_once{false};
1202
1207 std::counting_semaphore<> m_sem_conn_max{MAX_PRIVATE_BROADCAST_CONNECTIONS};
1208
1218 std::optional<Network> PickNetwork(std::optional<Proxy>& proxy) const;
1219
1221 size_t NumToOpen() const;
1222
1228 void NumToOpenAdd(size_t n);
1229
1236 size_t NumToOpenSub(size_t n);
1237
1239 void NumToOpenWait() const;
1240
1241 protected:
1247 std::optional<Proxy> ProxyForIPv4or6() const;
1248
1250 std::atomic_size_t m_num_to_open{0};
1251
1252 friend struct ConnmanTestMsg;
1254
1255 bool CheckIncomingNonce(uint64_t nonce);
1256 void ASMapHealthCheck();
1257
1258 // alias for thread safety annotations only, not defined
1260
1261 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1262
1264
1265 using NodeFn = std::function<void(CNode*)>;
1266 void ForEachNode(const NodeFn& func)
1267 {
1269 for (auto&& node : m_nodes) {
1271 func(node);
1272 }
1273 };
1274
1275 void ForEachNode(const NodeFn& func) const
1276 {
1278 for (auto&& node : m_nodes) {
1280 func(node);
1281 }
1282 };
1283
1284 // Addrman functions
1296 std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;
1311 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1312
1313 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1314 // a peer that is better than all our current peers.
1315 void SetTryNewOutboundPeer(bool flag);
1316 bool GetTryNewOutboundPeer() const;
1317
1319
1320 // Count the number of full-relay peer we have.
1321 int GetFullOutboundConnCount() const;
1322 // Return the number of outbound peers we have in excess of our target (eg,
1323 // if we previously called SetTryNewOutboundPeer(true), and have since set
1324 // to false, we may have extra peers that we wish to disconnect). This may
1325 // return a value less than (num_outbound_connections - num_outbound_slots)
1326 // in cases where some outbound connections are not yet fully connected, or
1327 // not yet fully disconnected.
1328 int GetExtraFullOutboundCount() const;
1329 // Count the number of block-relay-only peers we have over our limit.
1330 int GetExtraBlockRelayCount() const;
1331
1335 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1336
1350 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1351
1352 size_t GetNodeCount(ConnectionDirection) const;
1353 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1354 uint32_t GetMappedAS(const CNetAddr& addr) const;
1355 void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1356 bool DisconnectNode(std::string_view node);
1357 bool DisconnectNode(const CSubNet& subnet);
1358 bool DisconnectNode(const CNetAddr& addr);
1359 bool DisconnectNode(NodeId id);
1360
1368
1373
1375 std::chrono::seconds GetMaxOutboundTimeframe() const;
1376
1380 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1381
1385
1387
1388 uint64_t GetTotalBytesRecv() const;
1390
1392 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1393
1395
1397 bool ShouldRunInactivityChecks(const CNode& node, std::chrono::microseconds now) const;
1398
1400
1401private:
1403 public:
1404 std::shared_ptr<Sock> sock;
1406 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1407 : sock{sock_}, m_permissions{permissions_}
1408 {
1409 }
1410
1411 private:
1413 };
1414
1418
1419 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1420 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1421 bool InitBinds(const Options& options);
1422
1424 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1430 void AcceptConnection(const ListenSocket& hListenSocket);
1431
1440 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1441 NetPermissionFlags permission_flags,
1442 const CService& addr_bind,
1443 const CService& addr);
1444
1448 bool InactivityCheck(const CNode& node, std::chrono::microseconds now) const;
1449
1455 Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);
1456
1461
1467 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1468 const Sock::EventsPerSock& events_per_sock)
1470
1475 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1476
1479
1480 uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;
1481
1489 bool AlreadyConnectedToHost(std::string_view host) const;
1490
1498 bool AlreadyConnectedToAddressPort(const CService& addr_port) const;
1499
1503 bool AlreadyConnectedToAddress(const CNetAddr& addr) const;
1504
1506
1517 CNode* ConnectNode(CAddress addrConnect,
1518 const char* pszDest,
1519 bool fCountFailure,
1520 ConnectionType conn_type,
1521 bool use_v2transport,
1522 const std::optional<Proxy>& proxy_override)
1524
1525 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1526
1527 void DeleteNode(CNode* pnode);
1528
1530
1532 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1533
1534 void DumpAddresses();
1535
1536 // Network stats
1537 void RecordBytesRecv(uint64_t bytes);
1539
1544 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1545
1550
1561 bool MaybePickPreferredNetwork(std::optional<Network>& network);
1562
1563 // Whether the node should be passed out in ForEach* callbacks
1564 static bool NodeFullyConnected(const CNode* pnode);
1565
1566 uint16_t GetDefaultPort(Network net) const;
1567 uint16_t GetDefaultPort(const std::string& addr) const;
1568
1569 // Network usage totals
1571 std::atomic<uint64_t> nTotalBytesRecv{0};
1572 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1573
1574 // outbound limit & stats
1575 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1576 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1578
1579 // P2P timeout in seconds
1580 std::chrono::seconds m_peer_connect_timeout;
1581
1582 // Whitelisted ranges. Any node connecting from these is automatically
1583 // whitelisted (as well as those connecting to whitelisted binds).
1584 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1585 // Whitelisted ranges for outgoing connections.
1586 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1587
1588 unsigned int nSendBufferMaxSize{0};
1589 unsigned int nReceiveFloodSize{0};
1590
1591 std::vector<ListenSocket> vhListenSocket;
1592 std::atomic<bool> fNetworkActive{true};
1594 std::reference_wrapper<AddrMan> addrman;
1596 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1598
1599 // connection string and whether to use v2 p2p
1600 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1601
1603 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1604 std::list<CNode*> m_nodes_disconnected;
1606 std::atomic<NodeId> nLastNodeId{0};
1607 unsigned int nPrevNodeCount{0};
1608
1609 // Stores number of full-tx connections (outbound and manual) per network
1610 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1611
1619 std::vector<CAddress> m_addrs_response_cache;
1620 std::chrono::microseconds m_cache_entry_expiration{0};
1621 };
1622
1637 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1638
1650 std::atomic<ServiceFlags> m_local_services;
1651
1652 std::unique_ptr<std::counting_semaphore<>> semOutbound;
1653 std::unique_ptr<std::counting_semaphore<>> semAddnode;
1654
1661
1662 /*
1663 * Maximum number of peers by connection type. Might vary from defaults
1664 * based on -maxconnections init value.
1665 */
1666
1667 // How many full-relay (tx, block, addr) outbound peers we want
1669
1670 // How many block-relay only outbound peers we want
1671 // We do not relay tx or addr messages with these peers
1673
1674 int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1675 int m_max_feeler{MAX_FEELER_CONNECTIONS};
1678
1684
1689 std::vector<CAddress> m_anchors;
1690
1692 const uint64_t nSeed0, nSeed1;
1693
1695 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1696
1697 std::condition_variable condMsgProc;
1699 std::atomic<bool> flagInterruptMsgProc{false};
1700
1705 const std::shared_ptr<CThreadInterrupt> m_interrupt_net;
1706
1712 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1713
1721
1726
1731 std::atomic_bool m_start_extra_block_relay_peers{false};
1732
1737 std::vector<CService> m_onion_binds;
1738
1744
1750
1754 bool m_capture_messages{false};
1755
1760
1768 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1769
1774
1777 {
1780 std::string destination;
1783 };
1784
1788 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1789
1791 void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1792
1797 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1798
1804 {
1805 public:
1806 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1807 {
1808 {
1809 LOCK(connman.m_nodes_mutex);
1810 m_nodes_copy = connman.m_nodes;
1811 for (auto& node : m_nodes_copy) {
1812 node->AddRef();
1813 }
1814 }
1815 if (shuffle) {
1816 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1817 }
1818 }
1819
1821 {
1822 for (auto& node : m_nodes_copy) {
1823 node->Release();
1824 }
1825 }
1826
1827 const std::vector<CNode*>& Nodes() const
1828 {
1829 return m_nodes_copy;
1830 }
1831
1832 private:
1833 std::vector<CNode*> m_nodes_copy;
1834 };
1835
1837
1838 friend struct ConnmanTestMsg;
1839};
1840
1842extern std::function<void(const CAddress& addr,
1843 const std::string& msg_type,
1844 std::span<const unsigned char> data,
1845 bool is_incoming)>
1847
1848#endif // BITCOIN_NET_H
int ret
int flags
Definition: bitcoin-tx.cpp:529
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
Stochastic address manager.
Definition: addrman.h:110
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition: bip324.h:20
Definition: banman.h:64
A CService with information about it as peer.
Definition: protocol.h:367
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
Signals for UI communication.
Definition: interface_ui.h:26
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition: net.h:1804
const std::vector< CNode * > & Nodes() const
Definition: net.h:1827
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition: net.h:1806
std::vector< CNode * > m_nodes_copy
Definition: net.h:1833
Group of private broadcast related members.
Definition: net.h:1191
Definition: net.h:1069
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition: net.h:1749
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:2493
std::condition_variable condMsgProc
Definition: net.h:1697
std::thread threadMessageHandler
Definition: net.h:1718
nSendBufferMaxSize
Definition: net.h:1115
void RemoveLocalServices(ServiceFlags services)
Definition: net.h:1372
bool AlreadyConnectedToHost(std::string_view host) const
Determine whether we're already connected to a given "host:port".
Definition: net.cpp:335
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1584
CClientUIInterface * m_client_interface
Definition: net.h:1680
std::reference_wrapper< AddrMan > addrman
Definition: net.h:1594
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:3127
void ForEachNode(const NodeFn &func) const
Definition: net.h:1275
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:4121
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
Definition: net.cpp:1912
void DeleteNode(CNode *pnode)
Definition: net.cpp:3673
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
Definition: net.cpp:1687
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::microseconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
Definition: net.cpp:2006
bool GetTryNewOutboundPeer() const
Definition: net.cpp:2429
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
int m_max_inbound
Definition: net.h:1677
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
class CConnman::PrivateBroadcast m_private_broadcast
uint16_t GetDefaultPort(Network net) const
Definition: net.cpp:3398
int m_max_outbound_block_relay
Definition: net.h:1672
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
void SetCaptureMessages(bool cap)
Definition: net.h:1140
std::thread threadI2PAcceptIncoming
Definition: net.h:1719
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
Definition: net.cpp:3697
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:2434
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Open a new P2P connection.
Definition: net.cpp:372
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
Definition: net.cpp:1764
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:1676
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
Definition: net.cpp:3789
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2258
int GetFullOutboundConnCount() const
Definition: net.cpp:2447
NodeId GetNewNodeId()
Definition: net.cpp:3393
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
std::atomic< NodeId > nLastNodeId
Definition: net.h:1606
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:1660
int GetExtraBlockRelayCount() const
Definition: net.cpp:2479
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Definition: net.cpp:2249
BanMan * m_banman
Pointer to this node's banman.
Definition: net.h:1683
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:3914
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1575
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3880
std::thread threadDNSAddressSeed
Definition: net.h:1714
void ASMapHealthCheck()
Definition: net.cpp:4173
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:2123
void ThreadI2PAcceptIncoming()
Definition: net.cpp:3166
void StartExtraBlockRelayPeers()
Definition: net.cpp:2440
const NetGroupManager & m_netgroupman
Definition: net.h:1595
bool DisconnectNode(std::string_view node)
Definition: net.cpp:3812
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition: net.h:1689
std::chrono::seconds GetMaxOutboundTimeframe() const
Definition: net.cpp:3887
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
Definition: net.cpp:4139
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition: net.h:1743
unsigned int nPrevNodeCount
Definition: net.h:1607
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
Definition: net.cpp:572
void NotifyNumConnectionsChanged()
Definition: net.cpp:1991
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
Definition: net.cpp:3957
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3735
std::chrono::seconds m_peer_connect_timeout
Definition: net.h:1580
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:1725
bool InitBinds(const Options &options)
Definition: net.cpp:3428
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
Definition: net.cpp:132
std::vector< ListenSocket > vhListenSocket
Definition: net.h:1591
bool AlreadyConnectedToAddress(const CNetAddr &addr) const
Determine whether we're already connected to a given address.
Definition: net.cpp:347
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
Definition: net.cpp:2899
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:4134
bool AddConnection(const std::string &address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Attempts to open a connection.
Definition: net.cpp:1874
Mutex m_total_bytes_sent_mutex
Definition: net.h:1570
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:2912
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
Definition: net.cpp:2972
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
Definition: net.cpp:3409
std::thread threadOpenConnections
Definition: net.h:1717
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3772
std::atomic< ServiceFlags > m_local_services
Services this node offers.
Definition: net.h:1650
uint32_t GetMappedAS(const CNetAddr &addr) const
Definition: net.cpp:3795
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2408
Mutex m_addr_fetches_mutex
Definition: net.h:1597
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition: net.h:1773
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:3800
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition: net.h:1692
m_local_services
Definition: net.h:1105
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
Definition: net.cpp:2095
int GetExtraFullOutboundCount() const
Definition: net.cpp:2465
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:3899
uint64_t GetTotalBytesRecv() const
Definition: net.cpp:3945
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:1600
RecursiveMutex m_nodes_mutex
Definition: net.h:1605
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:4045
std::unique_ptr< std::counting_semaphore<> > semOutbound
Definition: net.h:1652
nReceiveFloodSize
Definition: net.h:1116
const CChainParams & m_params
Definition: net.h:1836
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
Definition: net.cpp:2506
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3761
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3892
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
Definition: net.h:1705
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake.
Definition: net.h:1371
std::thread threadPrivateBroadcast
Definition: net.h:1720
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Definition: net.cpp:2528
Mutex mutexMsgProc
Definition: net.h:1698
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
Definition: net.cpp:3749
bool fAddressesInitialized
Definition: net.h:1593
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:3686
std::thread threadOpenAddedConnections
Definition: net.h:1716
Mutex m_added_nodes_mutex
Definition: net.h:1602
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Definition: net.cpp:2238
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3862
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:353
int m_max_outbound_full_relay
Definition: net.h:1668
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1759
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:3950
std::unique_ptr< std::counting_semaphore<> > semAddnode
Definition: net.h:1653
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:3209
bool MaybePickPreferredNetwork(std::optional< Network > &network)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
Definition: net.cpp:2512
void RecordBytesRecv(uint64_t bytes)
Definition: net.cpp:3857
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1576
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:3935
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition: net.h:1572
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
Definition: net.cpp:4061
bool GetUseAddrmanOutgoing() const
Definition: net.h:1165
std::list< CNode * > m_nodes_disconnected
Definition: net.h:1604
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition: net.h:1712
bool m_use_addrman_outgoing
Definition: net.h:1679
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1586
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:1637
std::function< void(CNode *)> NodeFn
Definition: net.h:1265
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
Definition: net.cpp:2064
NetEventsInterface * m_msgproc
Definition: net.h:1681
std::atomic< uint64_t > nTotalBytesRecv
Definition: net.h:1571
std::atomic< bool > fNetworkActive
Definition: net.h:1592
bool InactivityCheck(const CNode &node, std::chrono::microseconds now) const
Return true if the peer is inactive and should be disconnected.
Definition: net.cpp:2011
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
Definition: net.cpp:2225
void DumpAddresses()
Definition: net.cpp:2398
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:1737
bool AlreadyConnectedToAddressPort(const CService &addr_port) const
Determine whether we're already connected to a given address:port.
Definition: net.cpp:341
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
std::thread threadSocketHandler
Definition: net.h:1715
nMaxOutboundLimit
Definition: net.h:1120
void AcceptConnection(const ListenSocket &hListenSocket)
Definition: net.cpp:1736
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
Definition: net.cpp:3277
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
An encapsulated private key.
Definition: key.h:36
Message header.
Definition: protocol.h:29
Network address.
Definition: netaddress.h:113
Transport protocol agnostic message container.
Definition: net.h:237
CNetMessage(CNetMessage &&)=default
CNetMessage(DataStream &&recv_in)
Definition: net.h:245
std::string m_type
Definition: net.h:243
DataStream m_recv
received message data
Definition: net.h:239
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition: net.h:679
bool IsFeelerConn() const
Definition: net.h:815
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition: net.h:712
bool ExpectServicesFromConn() const
Definition: net.h:832
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition: net.h:719
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition: net.h:707
bool IsInboundConn() const
Definition: net.h:828
bool HasPermission(NetPermissionFlags permission) const
Definition: net.h:730
CountingSemaphoreGrant grantOutbound
Definition: net.h:738
bool IsOutboundOrBlockRelayConn() const
Definition: net.h:770
NodeId GetId() const
Definition: net.h:913
bool IsManualConn() const
Definition: net.h:790
const std::string m_addr_name
Definition: net.h:717
CNode & operator=(const CNode &)=delete
const CService addrBind
Definition: net.h:716
void SetCommonVersion(int greatest_common_version)
Definition: net.h:938
std::list< CNetMessage > vRecvMsg
Definition: net.h:995
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition: net.h:984
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition: net.h:999
bool IsAddrFetchConn() const
Definition: net.h:819
uint64_t GetLocalNonce() const
Definition: net.h:917
const CAddress addr
Definition: net.h:714
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition: net.h:741
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:811
int GetCommonVersion() const
Definition: net.h:943
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition: net.h:786
Mutex m_subver_mutex
Definition: net.h:723
Mutex cs_vSend
Definition: net.h:703
const uint64_t m_network_key
Network key used to prevent fingerprinting our node across networks.
Definition: net.h:747
int GetRefCount() const
Definition: net.h:921
Mutex m_msg_process_queue_mutex
Definition: net.h:997
const ConnectionType m_conn_type
Definition: net.h:749
const size_t m_recv_flood_size
Definition: net.h:994
const uint64_t nLocalHostNonce
Definition: net.h:991
bool IsManualOrFullOutboundConn() const
Definition: net.h:794
bool IsPrivateBroadcastConn() const
Definition: net.h:823
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition: net.h:683
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:685
Mutex m_addr_local_mutex
Definition: net.h:1003
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition: net.h:698
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition: net.h:721
const NodeId id
Definition: net.h:990
Mutex cs_vRecv
Definition: net.h:705
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition: net.h:700
Mutex m_sock_mutex
Definition: net.h:704
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:958
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:728
std::string m_session_id
BIP324 session id string in hex, if any.
Definition: net.h:228
std::string addrLocal
Definition: net.h:216
uint64_t nRecvBytes
Definition: net.h:210
std::chrono::microseconds m_last_ping_time
Definition: net.h:213
uint32_t m_mapped_as
Definition: net.h:223
mapMsgTypeSize mapRecvBytesPerMsgType
Definition: net.h:211
bool fInbound
Definition: net.h:203
uint64_t nSendBytes
Definition: net.h:208
std::chrono::seconds m_last_recv
Definition: net.h:196
ConnectionType m_conn_type
Definition: net.h:224
std::chrono::seconds m_last_send
Definition: net.h:195
std::chrono::seconds m_last_tx_time
Definition: net.h:197
CAddress addr
Definition: net.h:218
mapMsgTypeSize mapSendBytesPerMsgType
Definition: net.h:209
std::chrono::microseconds m_min_ping_time
Definition: net.h:214
CService addrBind
Definition: net.h:220
TransportProtocolType m_transport_type
Transport protocol type.
Definition: net.h:226
std::chrono::seconds m_connected
Definition: net.h:199
bool m_bip152_highbandwidth_from
Definition: net.h:207
bool m_bip152_highbandwidth_to
Definition: net.h:205
std::string m_addr_name
Definition: net.h:200
int nVersion
Definition: net.h:201
std::chrono::seconds m_last_block_time
Definition: net.h:198
Network m_network
Definition: net.h:222
NodeId nodeid
Definition: net.h:194
std::string cleanSubVer
Definition: net.h:202
NetPermissionFlags m_permission_flags
Definition: net.h:212
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:40
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:530
General SipHash-2-4 implementation.
Definition: siphash.h:27
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:133
Fast randomness source.
Definition: random.h:386
Different type to mark Mutex at global scope.
Definition: sync.h:140
Definition: init.h:13
Interface for message handling.
Definition: net.h:1025
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1028
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:59
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:28
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition: net.h:260
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:317
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition: net.h:382
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition: net.h:418
const NodeId m_node_id
Definition: net.h:377
Mutex m_send_mutex
Lock for sending state.
Definition: net.h:412
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:420
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:376
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition: net.h:384
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition: net.h:404
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
Definition: net.h:378
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:425
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:618
const NodeId m_nodeid
NodeId (for debug logging).
Definition: net.h:586
BIP324Cipher m_cipher
Cipher state.
Definition: net.h:582
SendState
State type that controls the sender side.
Definition: net.h:551
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition: net.h:588
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:584
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:594
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:610
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:486
256-bit opaque blob.
Definition: uint256.h:195
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::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
Definition: miner_tests.cpp:82
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
Definition: miniscript.h:197
Definition: messages.h:21
Definition: common.h:29
static const unsigned char VERSION[]
Definition: netaddress.cpp:188
const std::string KEY
Definition: walletdb.cpp:44
uint16_t GetListenPort()
Definition: net.cpp:138
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:81
static constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
Definition: net.h:89
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition: net.cpp:329
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:67
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition: net.h:59
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:71
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition: net.cpp:277
bool fDiscover
Definition: net.cpp:116
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:99
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:91
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:97
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:85
void ClearLocal()
Definition: net.cpp:270
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
Definition: net.h:65
bool fListen
Definition: net.cpp:117
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition: net.h:63
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:98
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:120
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:83
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition: net.cpp:240
const std::string NET_MESSAGE_TYPE_OTHER
Definition: net.cpp:108
std::map< std::string, uint64_t > mapMsgTypeSize
Definition: net.h:189
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:95
static constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
Definition: net.h:77
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:96
int64_t NodeId
Definition: net.h:103
CService GetLocalAddress(const CNode &peer)
Definition: net.cpp:220
GlobalMutex g_maplocalhost_mutex
Definition: net.cpp:118
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:75
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:79
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition: net.h:93
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition: net.h:61
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:87
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:4227
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:154
@ LOCAL_MAPPED
Definition: net.h:157
@ LOCAL_MANUAL
Definition: net.h:158
@ LOCAL_MAX
Definition: net.h:160
@ LOCAL_BIND
Definition: net.h:156
@ LOCAL_IF
Definition: net.h:155
static constexpr bool DEFAULT_V2_TRANSPORT
Definition: net.h:101
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:73
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition: net.cpp:3346
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:318
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition: netaddress.h:33
ConnectionDirection
Definition: netbase.h:33
ServiceFlags
nServices flags
Definition: protocol.h:309
@ NODE_NONE
Definition: protocol.h:312
@ NODE_P2P_V2
Definition: protocol.h:330
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
bool fInbound
Definition: net.h:114
CService resolvedAddress
Definition: net.h:112
AddedNodeParams m_params
Definition: net.h:111
bool fConnected
Definition: net.h:113
std::string m_added_node
Definition: net.h:106
bool m_use_v2transport
Definition: net.h:107
Cache responses to addr requests to minimize privacy leak.
Definition: net.h:1618
std::vector< CAddress > m_addrs_response_cache
Definition: net.h:1619
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition: net.h:1405
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition: net.h:1406
NetPermissionFlags m_permissions
Definition: net.h:1412
std::shared_ptr< Sock > sock
Definition: net.h:1404
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:1086
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:1084
std::vector< CService > onion_binds
Definition: net.h:1088
std::vector< std::string > m_specified_outgoing
Definition: net.h:1093
std::vector< std::string > m_added_nodes
Definition: net.h:1094
std::vector< CService > vBinds
Definition: net.h:1087
bool m_i2p_accept_incoming
Definition: net.h:1095
std::vector< std::string > vSeedNodes
Definition: net.h:1083
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:1091
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:1085
Struct for entries in m_reconnections.
Definition: net.h:1777
ConnectionType conn_type
Definition: net.h:1781
std::string destination
Definition: net.h:1780
CountingSemaphoreGrant grant
Definition: net.h:1779
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition: net.h:128
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition: net.h:137
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition: net.h:136
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition: net.cpp:122
uint16_t nPort
Definition: net.h:182
int nScore
Definition: net.h:181
std::optional< uint256 > session_id
Definition: net.h:267
TransportProtocolType transport_type
Definition: net.h:266
Bilingual messages:
Definition: translation.h:24
#define AssertLockNotHeld(cs)
Definition: sync.h:147
#define LOCK(cs)
Definition: sync.h:266
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:297
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
#define LOCK_RETURNED(x)
Definition: threadsafety.h:49
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())