Bitcoin Core 28.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
net.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 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 <span.h>
28#include <streams.h>
29#include <sync.h>
30#include <uint256.h>
31#include <util/check.h>
32#include <util/sock.h>
34
35#include <atomic>
36#include <condition_variable>
37#include <cstdint>
38#include <deque>
39#include <functional>
40#include <list>
41#include <map>
42#include <memory>
43#include <optional>
44#include <queue>
45#include <thread>
46#include <unordered_set>
47#include <vector>
48
49class AddrMan;
50class BanMan;
51class CChainParams;
52class CNode;
53class CScheduler;
54struct bilingual_str;
55
57static constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};
59static constexpr auto FEELER_INTERVAL = 2min;
61static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;
63static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
65static const unsigned int MAX_SUBVERSION_LENGTH = 256;
69static const int MAX_ADDNODE_CONNECTIONS = 8;
73static const int MAX_FEELER_CONNECTIONS = 1;
75static const bool DEFAULT_LISTEN = true;
77static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
79static const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};
81static const bool DEFAULT_BLOCKSONLY = false;
83static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;
85static const int NUM_FDS_MESSAGE_CAPTURE = 1;
87static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};
88
89static constexpr bool DEFAULT_FORCEDNSSEED{false};
90static constexpr bool DEFAULT_DNSSEED{true};
91static constexpr bool DEFAULT_FIXEDSEEDS{true};
92static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
93static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
94
95static constexpr bool DEFAULT_V2_TRANSPORT{true};
96
97typedef int64_t NodeId;
98
100 std::string m_added_node;
102};
103
110
111class CNodeStats;
113
115 CSerializedNetMsg() = default;
118 // No implicit copying, only moves.
121
123 {
125 copy.data = data;
126 copy.m_type = m_type;
127 return copy;
128 }
129
130 std::vector<unsigned char> data;
131 std::string m_type;
132
134 size_t GetMemoryUsage() const noexcept;
135};
136
142void Discover();
143
144uint16_t GetListenPort();
145
146enum
147{
148 LOCAL_NONE, // unknown
149 LOCAL_IF, // address a local interface listens on
150 LOCAL_BIND, // address explicit bound to
151 LOCAL_MAPPED, // address reported by UPnP or NAT-PMP
152 LOCAL_MANUAL, // address explicitly specified (-externalip=)
153
156
158std::optional<CService> GetLocalAddrForPeer(CNode& node);
159
160bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
161bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
162void RemoveLocal(const CService& addr);
163bool SeenLocal(const CService& addr);
164bool IsLocal(const CService& addr);
165CService GetLocalAddress(const CNode& peer);
166
167extern bool fDiscover;
168extern bool fListen;
169
171extern std::string strSubVersion;
172
175 uint16_t nPort;
176};
177
179extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);
180
181extern const std::string NET_MESSAGE_TYPE_OTHER;
182using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;
183
185{
186public:
188 std::chrono::seconds m_last_send;
189 std::chrono::seconds m_last_recv;
190 std::chrono::seconds m_last_tx_time;
191 std::chrono::seconds m_last_block_time;
192 std::chrono::seconds m_connected;
193 std::string m_addr_name;
195 std::string cleanSubVer;
197 // We requested high bandwidth connection to peer
199 // Peer requested high bandwidth connection
202 uint64_t nSendBytes;
204 uint64_t nRecvBytes;
207 std::chrono::microseconds m_last_ping_time;
208 std::chrono::microseconds m_min_ping_time;
209 // Our address, as reported by the peer
210 std::string addrLocal;
211 // Address of this peer
213 // Bind address of our side of the connection
215 // Network the peer connected through
217 uint32_t m_mapped_as;
222 std::string m_session_id;
223};
224
225
231{
232public:
234 std::chrono::microseconds m_time{0};
235 uint32_t m_message_size{0};
236 uint32_t m_raw_message_size{0};
237 std::string m_type;
238
239 explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
240 // Only one CNetMessage object will exist for the same message on either
241 // the receive or processing queue. For performance reasons we therefore
242 // delete the copy constructor and assignment operator to avoid the
243 // possibility of copying CNetMessage objects.
245 CNetMessage(const CNetMessage&) = delete;
248};
249
252public:
253 virtual ~Transport() = default;
254
255 struct Info
256 {
258 std::optional<uint256> session_id;
259 };
260
262 virtual Info GetInfo() const noexcept = 0;
263
264 // 1. Receiver side functions, for decoding bytes received on the wire into transport protocol
265 // agnostic CNetMessage (message type & payload) objects.
266
268 virtual bool ReceivedMessageComplete() const = 0;
269
276 virtual bool ReceivedBytes(Span<const uint8_t>& msg_bytes) = 0;
277
285 virtual CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) = 0;
286
287 // 2. Sending side functions, for converting messages into bytes to be sent over the wire.
288
295 virtual bool SetMessageToSend(CSerializedNetMsg& msg) noexcept = 0;
296
304 using BytesToSend = std::tuple<
305 Span<const uint8_t> /*to_send*/,
306 bool /*more*/,
307 const std::string& /*m_type*/
308 >;
309
345 virtual BytesToSend GetBytesToSend(bool have_next_message) const noexcept = 0;
346
353 virtual void MarkBytesSent(size_t bytes_sent) noexcept = 0;
354
356 virtual size_t GetSendMemoryUsage() const noexcept = 0;
357
358 // 3. Miscellaneous functions.
359
361 virtual bool ShouldReconnectV1() const noexcept = 0;
362};
363
364class V1Transport final : public Transport
365{
366private:
368 const NodeId m_node_id; // Only for logging
370 mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
371 mutable uint256 data_hash GUARDED_BY(m_recv_mutex);
372 bool in_data GUARDED_BY(m_recv_mutex); // parsing header (false) or data (true)
373 DataStream hdrbuf GUARDED_BY(m_recv_mutex){}; // partially received header
374 CMessageHeader hdr GUARDED_BY(m_recv_mutex); // complete header
375 DataStream vRecv GUARDED_BY(m_recv_mutex){}; // received message data
376 unsigned int nHdrPos GUARDED_BY(m_recv_mutex);
377 unsigned int nDataPos GUARDED_BY(m_recv_mutex);
378
379 const uint256& GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
380 int readHeader(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
381 int readData(Span<const uint8_t> msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
382
383 void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex) {
384 AssertLockHeld(m_recv_mutex);
385 vRecv.clear();
386 hdrbuf.clear();
387 hdrbuf.resize(24);
388 in_data = false;
389 nHdrPos = 0;
390 nDataPos = 0;
391 data_hash.SetNull();
392 hasher.Reset();
393 }
394
395 bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
396 {
397 AssertLockHeld(m_recv_mutex);
398 if (!in_data) return false;
399 return hdr.nMessageSize == nDataPos;
400 }
401
405 std::vector<uint8_t> m_header_to_send GUARDED_BY(m_send_mutex);
407 CSerializedNetMsg m_message_to_send GUARDED_BY(m_send_mutex);
409 bool m_sending_header GUARDED_BY(m_send_mutex) {false};
411 size_t m_bytes_sent GUARDED_BY(m_send_mutex) {0};
412
413public:
414 explicit V1Transport(const NodeId node_id) noexcept;
415
416 bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
417 {
418 AssertLockNotHeld(m_recv_mutex);
419 return WITH_LOCK(m_recv_mutex, return CompleteInternal());
420 }
421
422 Info GetInfo() const noexcept override;
423
424 bool ReceivedBytes(Span<const uint8_t>& msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
425 {
426 AssertLockNotHeld(m_recv_mutex);
427 LOCK(m_recv_mutex);
428 int ret = in_data ? readData(msg_bytes) : readHeader(msg_bytes);
429 if (ret < 0) {
430 Reset();
431 } else {
432 msg_bytes = msg_bytes.subspan(ret);
433 }
434 return ret >= 0;
435 }
436
437 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
438
439 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
440 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
441 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
442 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
443 bool ShouldReconnectV1() const noexcept override { return false; }
444};
445
446class V2Transport final : public Transport
447{
448private:
452 static constexpr std::array<std::byte, 0> VERSION_CONTENTS = {};
453
456 static constexpr size_t V1_PREFIX_LEN = 16;
457
458 // The sender side and receiver side of V2Transport are state machines that are transitioned
459 // through, based on what has been received. The receive state corresponds to the contents of,
460 // and bytes received to, the receive buffer. The send state controls what can be appended to
461 // the send buffer and what can be sent from it.
462
477 enum class RecvState : uint8_t {
483 KEY_MAYBE_V1,
484
490 KEY,
491
498 GARB_GARBTERM,
499
508 VERSION,
509
515 APP,
516
521 APP_READY,
522
526 V1,
527 };
528
542 enum class SendState : uint8_t {
549 MAYBE_V1,
550
556 AWAITING_KEY,
557
564 READY,
565
569 V1,
570 };
571
575 const bool m_initiating;
580
582 mutable Mutex m_recv_mutex ACQUIRED_BEFORE(m_send_mutex);
585 uint32_t m_recv_len GUARDED_BY(m_recv_mutex) {0};
587 std::vector<uint8_t> m_recv_buffer GUARDED_BY(m_recv_mutex);
589 std::vector<uint8_t> m_recv_aad GUARDED_BY(m_recv_mutex);
591 std::vector<uint8_t> m_recv_decode_buffer GUARDED_BY(m_recv_mutex);
593 RecvState m_recv_state GUARDED_BY(m_recv_mutex);
594
597 mutable Mutex m_send_mutex ACQUIRED_AFTER(m_recv_mutex);
599 std::vector<uint8_t> m_send_buffer GUARDED_BY(m_send_mutex);
601 uint32_t m_send_pos GUARDED_BY(m_send_mutex) {0};
603 std::vector<uint8_t> m_send_garbage GUARDED_BY(m_send_mutex);
605 std::string m_send_type GUARDED_BY(m_send_mutex);
607 SendState m_send_state GUARDED_BY(m_send_mutex);
609 bool m_sent_v1_header_worth GUARDED_BY(m_send_mutex) {false};
610
612 void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
614 void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
616 static std::optional<std::string> GetMessageType(Span<const uint8_t>& contents) noexcept;
618 size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
620 void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex);
622 void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
624 bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex, !m_send_mutex);
626 bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
628 bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex);
629
630public:
631 static constexpr uint32_t MAX_GARBAGE_LEN = 4095;
632
638 V2Transport(NodeId nodeid, bool initiating) noexcept;
639
641 V2Transport(NodeId nodeid, bool initiating, const CKey& key, Span<const std::byte> ent32, std::vector<uint8_t> garbage) noexcept;
642
643 // Receive side functions.
644 bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
645 bool ReceivedBytes(Span<const uint8_t>& msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
646 CNetMessage GetReceivedMessage(std::chrono::microseconds time, bool& reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
647
648 // Send side functions.
649 bool SetMessageToSend(CSerializedNetMsg& msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
650 BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
651 void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
652 size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex);
653
654 // Miscellaneous functions.
655 bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex, !m_send_mutex);
656 Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex);
657};
658
660{
662 std::unique_ptr<i2p::sam::Session> i2p_sam_session = nullptr;
663 bool prefer_evict = false;
664 size_t recv_flood_size{DEFAULT_MAXRECEIVEBUFFER * 1000};
665 bool use_v2transport = false;
666};
667
669class CNode
670{
671public:
674 const std::unique_ptr<Transport> m_transport;
675
677
686 std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
687
689 size_t m_send_memusage GUARDED_BY(cs_vSend){0};
691 uint64_t nSendBytes GUARDED_BY(cs_vSend){0};
693 std::deque<CSerializedNetMsg> vSendMsg GUARDED_BY(cs_vSend);
697
698 uint64_t nRecvBytes GUARDED_BY(cs_vRecv){0};
699
700 std::atomic<std::chrono::seconds> m_last_send{0s};
701 std::atomic<std::chrono::seconds> m_last_recv{0s};
703 const std::chrono::seconds m_connected;
704 // Address of this peer
706 // Bind address of our side of the connection
708 const std::string m_addr_name;
710 const std::string m_dest;
712 const bool m_inbound_onion;
713 std::atomic<int> nVersion{0};
719 std::string cleanSubVer GUARDED_BY(m_subver_mutex){};
720 const bool m_prefer_evict{false}; // This peer is preferred for eviction.
721 bool HasPermission(NetPermissionFlags permission) const {
722 return NetPermissions::HasFlag(m_permission_flags, permission);
723 }
725 std::atomic_bool fSuccessfullyConnected{false};
726 // Setting fDisconnect to true will cause the node to be disconnected the
727 // next time DisconnectNodes() runs
728 std::atomic_bool fDisconnect{false};
730 std::atomic<int> nRefCount{0};
731
732 const uint64_t nKeyedNetGroup;
733 std::atomic_bool fPauseRecv{false};
734 std::atomic_bool fPauseSend{false};
735
737
739 void MarkReceivedMsgsForProcessing()
740 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
741
747 std::optional<std::pair<CNetMessage, bool>> PollMessage()
748 EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex);
749
751 void AccountForSentBytes(const std::string& msg_type, size_t sent_bytes)
753 {
754 mapSendBytesPerMsgType[msg_type] += sent_bytes;
755 }
756
758 switch (m_conn_type) {
761 return true;
766 return false;
767 } // no default case, so the compiler can warn about missing cases
768
769 assert(false);
770 }
771
772 bool IsFullOutboundConn() const {
773 return m_conn_type == ConnectionType::OUTBOUND_FULL_RELAY;
774 }
775
776 bool IsManualConn() const {
777 return m_conn_type == ConnectionType::MANUAL;
778 }
779
781 {
782 switch (m_conn_type) {
787 return false;
790 return true;
791 } // no default case, so the compiler can warn about missing cases
792
793 assert(false);
794 }
795
796 bool IsBlockOnlyConn() const {
797 return m_conn_type == ConnectionType::BLOCK_RELAY;
798 }
799
800 bool IsFeelerConn() const {
801 return m_conn_type == ConnectionType::FEELER;
802 }
803
804 bool IsAddrFetchConn() const {
805 return m_conn_type == ConnectionType::ADDR_FETCH;
806 }
807
808 bool IsInboundConn() const {
809 return m_conn_type == ConnectionType::INBOUND;
810 }
811
813 switch (m_conn_type) {
817 return false;
821 return true;
822 } // no default case, so the compiler can warn about missing cases
823
824 assert(false);
825 }
826
837 Network ConnectedThroughNetwork() const;
838
840 [[nodiscard]] bool IsConnectedThroughPrivacyNet() const;
841
842 // We selected peer as (compact blocks) high-bandwidth peer (BIP152)
843 std::atomic<bool> m_bip152_highbandwidth_to{false};
844 // Peer selected us as (compact blocks) high-bandwidth peer (BIP152)
845 std::atomic<bool> m_bip152_highbandwidth_from{false};
846
848 std::atomic_bool m_has_all_wanted_services{false};
849
852 std::atomic_bool m_relays_txs{false};
853
856 std::atomic_bool m_bloom_filter_loaded{false};
857
863 std::atomic<std::chrono::seconds> m_last_block_time{0s};
864
869 std::atomic<std::chrono::seconds> m_last_tx_time{0s};
870
872 std::atomic<std::chrono::microseconds> m_last_ping_time{0us};
873
876 std::atomic<std::chrono::microseconds> m_min_ping_time{std::chrono::microseconds::max()};
877
878 CNode(NodeId id,
879 std::shared_ptr<Sock> sock,
880 const CAddress& addrIn,
881 uint64_t nKeyedNetGroupIn,
882 uint64_t nLocalHostNonceIn,
883 const CAddress& addrBindIn,
884 const std::string& addrNameIn,
885 ConnectionType conn_type_in,
886 bool inbound_onion,
887 CNodeOptions&& node_opts = {});
888 CNode(const CNode&) = delete;
889 CNode& operator=(const CNode&) = delete;
890
891 NodeId GetId() const {
892 return id;
893 }
894
895 uint64_t GetLocalNonce() const {
896 return nLocalHostNonce;
897 }
898
899 int GetRefCount() const
900 {
901 assert(nRefCount >= 0);
902 return nRefCount;
903 }
904
914 bool ReceiveMsgBytes(Span<const uint8_t> msg_bytes, bool& complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv);
915
916 void SetCommonVersion(int greatest_common_version)
917 {
918 Assume(m_greatest_common_version == INIT_PROTO_VERSION);
919 m_greatest_common_version = greatest_common_version;
920 }
922 {
923 return m_greatest_common_version;
924 }
925
926 CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
928 void SetAddrLocal(const CService& addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex);
929
930 CNode* AddRef()
931 {
932 nRefCount++;
933 return this;
934 }
935
936 void Release()
937 {
938 nRefCount--;
939 }
940
941 void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
942
943 void CopyStats(CNodeStats& stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex, !m_addr_local_mutex, !cs_vSend, !cs_vRecv);
944
945 std::string ConnectionTypeAsString() const { return ::ConnectionTypeAsString(m_conn_type); }
946
948 void PongReceived(std::chrono::microseconds ping_time) {
949 m_last_ping_time = ping_time;
950 m_min_ping_time = std::min(m_min_ping_time.load(), ping_time);
951 }
952
953private:
954 const NodeId id;
955 const uint64_t nLocalHostNonce;
956 std::atomic<int> m_greatest_common_version{INIT_PROTO_VERSION};
957
958 const size_t m_recv_flood_size;
959 std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
960
962 std::list<CNetMessage> m_msg_process_queue GUARDED_BY(m_msg_process_queue_mutex);
963 size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex){0};
964
965 // Our address, as reported by the peer
966 CService m_addr_local GUARDED_BY(m_addr_local_mutex);
968
969 mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend);
970 mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv);
971
982 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session GUARDED_BY(m_sock_mutex);
983};
984
989{
990public:
993
995 virtual void InitializeNode(const CNode& node, ServiceFlags our_services) = 0;
996
998 virtual void FinalizeNode(const CNode& node) = 0;
999
1004 virtual bool HasAllDesirableServiceFlags(ServiceFlags services) const = 0;
1005
1013 virtual bool ProcessMessages(CNode* pnode, std::atomic<bool>& interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1014
1021 virtual bool SendMessages(CNode* pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex) = 0;
1022
1023
1024protected:
1030};
1031
1033{
1034public:
1035
1036 struct Options
1037 {
1038 ServiceFlags nLocalServices = NODE_NONE;
1039 int m_max_automatic_connections = 0;
1041 NetEventsInterface* m_msgproc = nullptr;
1042 BanMan* m_banman = nullptr;
1043 unsigned int nSendBufferMaxSize = 0;
1044 unsigned int nReceiveFloodSize = 0;
1045 uint64_t nMaxOutboundLimit = 0;
1046 int64_t m_peer_connect_timeout = DEFAULT_PEER_CONNECT_TIMEOUT;
1047 std::vector<std::string> vSeedNodes;
1048 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1049 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1050 std::vector<NetWhitebindPermissions> vWhiteBinds;
1051 std::vector<CService> vBinds;
1052 std::vector<CService> onion_binds;
1056 bool m_use_addrman_outgoing = true;
1057 std::vector<std::string> m_specified_outgoing;
1058 std::vector<std::string> m_added_nodes;
1060 bool whitelist_forcerelay = DEFAULT_WHITELISTFORCERELAY;
1061 bool whitelist_relay = DEFAULT_WHITELISTRELAY;
1062 };
1063
1064 void Init(const Options& connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_total_bytes_sent_mutex)
1065 {
1066 AssertLockNotHeld(m_total_bytes_sent_mutex);
1067
1068 nLocalServices = connOptions.nLocalServices;
1069 m_max_automatic_connections = connOptions.m_max_automatic_connections;
1070 m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, m_max_automatic_connections);
1071 m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, m_max_automatic_connections - m_max_outbound_full_relay);
1072 m_max_automatic_outbound = m_max_outbound_full_relay + m_max_outbound_block_relay + m_max_feeler;
1073 m_max_inbound = std::max(0, m_max_automatic_connections - m_max_automatic_outbound);
1074 m_use_addrman_outgoing = connOptions.m_use_addrman_outgoing;
1075 m_client_interface = connOptions.uiInterface;
1076 m_banman = connOptions.m_banman;
1077 m_msgproc = connOptions.m_msgproc;
1078 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
1079 nReceiveFloodSize = connOptions.nReceiveFloodSize;
1080 m_peer_connect_timeout = std::chrono::seconds{connOptions.m_peer_connect_timeout};
1081 {
1082 LOCK(m_total_bytes_sent_mutex);
1083 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
1084 }
1085 vWhitelistedRangeIncoming = connOptions.vWhitelistedRangeIncoming;
1086 vWhitelistedRangeOutgoing = connOptions.vWhitelistedRangeOutgoing;
1087 {
1088 LOCK(m_added_nodes_mutex);
1089 // Attempt v2 connection if we support v2 - we'll reconnect with v1 if our
1090 // peer doesn't support it or immediately disconnects us for another reason.
1091 const bool use_v2transport(GetLocalServices() & NODE_P2P_V2);
1092 for (const std::string& added_node : connOptions.m_added_nodes) {
1093 m_added_node_params.push_back({added_node, use_v2transport});
1094 }
1095 }
1096 m_onion_binds = connOptions.onion_binds;
1097 whitelist_forcerelay = connOptions.whitelist_forcerelay;
1098 whitelist_relay = connOptions.whitelist_relay;
1099 }
1100
1101 CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
1102 const CChainParams& params, bool network_active = true);
1103
1104 ~CConnman();
1105
1106 bool Start(CScheduler& scheduler, const Options& options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !m_added_nodes_mutex, !m_addr_fetches_mutex, !mutexMsgProc);
1107
1108 void StopThreads();
1109 void StopNodes();
1110 void Stop()
1111 {
1112 StopThreads();
1113 StopNodes();
1114 };
1115
1116 void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1117 bool GetNetworkActive() const { return fNetworkActive; };
1118 bool GetUseAddrmanOutgoing() const { return m_use_addrman_outgoing; };
1119 void SetNetworkActive(bool active);
1120 void OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant&& grant_outbound, const char* strDest, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1121 bool CheckIncomingNonce(uint64_t nonce);
1122 void ASMapHealthCheck();
1123
1124 // alias for thread safety annotations only, not defined
1126
1127 bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
1128
1129 void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1130
1131 using NodeFn = std::function<void(CNode*)>;
1132 void ForEachNode(const NodeFn& func)
1133 {
1134 LOCK(m_nodes_mutex);
1135 for (auto&& node : m_nodes) {
1136 if (NodeFullyConnected(node))
1137 func(node);
1138 }
1139 };
1140
1141 void ForEachNode(const NodeFn& func) const
1142 {
1143 LOCK(m_nodes_mutex);
1144 for (auto&& node : m_nodes) {
1145 if (NodeFullyConnected(node))
1146 func(node);
1147 }
1148 };
1149
1150 // Addrman functions
1159 std::vector<CAddress> GetAddresses(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered = true) const;
1166 std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);
1167
1168 // This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding
1169 // a peer that is better than all our current peers.
1170 void SetTryNewOutboundPeer(bool flag);
1171 bool GetTryNewOutboundPeer() const;
1172
1173 void StartExtraBlockRelayPeers();
1174
1175 // Count the number of full-relay peer we have.
1176 int GetFullOutboundConnCount() const;
1177 // Return the number of outbound peers we have in excess of our target (eg,
1178 // if we previously called SetTryNewOutboundPeer(true), and have since set
1179 // to false, we may have extra peers that we wish to disconnect). This may
1180 // return a value less than (num_outbound_connections - num_outbound_slots)
1181 // in cases where some outbound connections are not yet fully connected, or
1182 // not yet fully disconnected.
1183 int GetExtraFullOutboundCount() const;
1184 // Count the number of block-relay-only peers we have over our limit.
1185 int GetExtraBlockRelayCount() const;
1186
1187 bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1188 bool RemoveAddedNode(const std::string& node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1189 bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1190 std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);
1191
1205 bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1206
1207 size_t GetNodeCount(ConnectionDirection) const;
1208 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;
1209 uint32_t GetMappedAS(const CNetAddr& addr) const;
1210 void GetNodeStats(std::vector<CNodeStats>& vstats) const;
1211 bool DisconnectNode(const std::string& node);
1212 bool DisconnectNode(const CSubNet& subnet);
1213 bool DisconnectNode(const CNetAddr& addr);
1214 bool DisconnectNode(NodeId id);
1215
1222 ServiceFlags GetLocalServices() const;
1223
1226 void AddLocalServices(ServiceFlags services) { nLocalServices = ServiceFlags(nLocalServices | services); };
1227 void RemoveLocalServices(ServiceFlags services) { nLocalServices = ServiceFlags(nLocalServices & ~services); }
1228
1229 uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1230 std::chrono::seconds GetMaxOutboundTimeframe() const;
1231
1235 bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1236
1239 uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1240
1241 std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1242
1243 uint64_t GetTotalBytesRecv() const;
1244 uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1245
1247 CSipHasher GetDeterministicRandomizer(uint64_t id) const;
1248
1249 void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1250
1252 bool ShouldRunInactivityChecks(const CNode& node, std::chrono::seconds now) const;
1253
1254 bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);
1255
1256private:
1258 public:
1259 std::shared_ptr<Sock> sock;
1261 ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)
1262 : sock{sock_}, m_permissions{permissions_}
1263 {
1264 }
1265
1266 private:
1268 };
1269
1272 std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);
1273
1274 bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);
1275 bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);
1276 bool InitBinds(const Options& options);
1277
1278 void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1279 void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);
1280 void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_unused_i2p_sessions_mutex);
1281 void ThreadOpenConnections(std::vector<std::string> connect) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex, !m_reconnections_mutex);
1282 void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);
1283 void ThreadI2PAcceptIncoming();
1284 void AcceptConnection(const ListenSocket& hListenSocket);
1285
1294 void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,
1295 NetPermissionFlags permission_flags,
1296 const CAddress& addr_bind,
1297 const CAddress& addr);
1298
1299 void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);
1300 void NotifyNumConnectionsChanged();
1302 bool InactivityCheck(const CNode& node) const;
1303
1309 Sock::EventsPerSock GenerateWaitSockets(Span<CNode* const> nodes);
1310
1314 void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1315
1321 void SocketHandlerConnected(const std::vector<CNode*>& nodes,
1322 const Sock::EventsPerSock& events_per_sock)
1323 EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);
1324
1329 void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
1330
1331 void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex);
1332 void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);
1333
1334 uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
1335
1336 CNode* FindNode(const CNetAddr& ip);
1337 CNode* FindNode(const std::string& addrName);
1338 CNode* FindNode(const CService& addr);
1339
1344 bool AlreadyConnectedToAddress(const CAddress& addr);
1345
1346 bool AttemptToEvictConnection();
1347 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
1348 void AddWhitelistPermissionFlags(NetPermissionFlags& flags, const CNetAddr &addr, const std::vector<NetWhitelistPermissions>& ranges) const;
1349
1350 void DeleteNode(CNode* pnode);
1351
1352 NodeId GetNewNodeId();
1353
1355 std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);
1356
1357 void DumpAddresses();
1358
1359 // Network stats
1360 void RecordBytesRecv(uint64_t bytes);
1361 void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);
1362
1367 std::unordered_set<Network> GetReachableEmptyNetworks() const;
1368
1372 std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const;
1373
1384 bool MaybePickPreferredNetwork(std::optional<Network>& network);
1385
1386 // Whether the node should be passed out in ForEach* callbacks
1387 static bool NodeFullyConnected(const CNode* pnode);
1388
1389 uint16_t GetDefaultPort(Network net) const;
1390 uint16_t GetDefaultPort(const std::string& addr) const;
1391
1392 // Network usage totals
1393 mutable Mutex m_total_bytes_sent_mutex;
1394 std::atomic<uint64_t> nTotalBytesRecv{0};
1395 uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};
1396
1397 // outbound limit & stats
1398 uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};
1399 std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};
1400 uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);
1401
1402 // P2P timeout in seconds
1403 std::chrono::seconds m_peer_connect_timeout;
1404
1405 // Whitelisted ranges. Any node connecting from these is automatically
1406 // whitelisted (as well as those connecting to whitelisted binds).
1407 std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;
1408 // Whitelisted ranges for outgoing connections.
1409 std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;
1410
1411 unsigned int nSendBufferMaxSize{0};
1412 unsigned int nReceiveFloodSize{0};
1413
1414 std::vector<ListenSocket> vhListenSocket;
1415 std::atomic<bool> fNetworkActive{true};
1416 bool fAddressesInitialized{false};
1419 std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);
1421
1422 // connection string and whether to use v2 p2p
1423 std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);
1424
1426 std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);
1427 std::list<CNode*> m_nodes_disconnected;
1429 std::atomic<NodeId> nLastNodeId{0};
1430 unsigned int nPrevNodeCount{0};
1431
1432 // Stores number of full-tx connections (outbound and manual) per network
1433 std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};
1434
1442 std::vector<CAddress> m_addrs_response_cache;
1443 std::chrono::microseconds m_cache_entry_expiration{0};
1444 };
1445
1460 std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;
1461
1473 std::atomic<ServiceFlags> nLocalServices;
1474
1475 std::unique_ptr<CSemaphore> semOutbound;
1476 std::unique_ptr<CSemaphore> semAddnode;
1477
1484
1485 /*
1486 * Maximum number of peers by connection type. Might vary from defaults
1487 * based on -maxconnections init value.
1488 */
1489
1490 // How many full-relay (tx, block, addr) outbound peers we want
1492
1493 // How many block-relay only outbound peers we want
1494 // We do not relay tx or addr messages with these peers
1496
1497 int m_max_addnode{MAX_ADDNODE_CONNECTIONS};
1498 int m_max_feeler{MAX_FEELER_CONNECTIONS};
1501
1507
1512 std::vector<CAddress> m_anchors;
1513
1515 const uint64_t nSeed0, nSeed1;
1516
1518 bool fMsgProcWake GUARDED_BY(mutexMsgProc);
1519
1520 std::condition_variable condMsgProc;
1522 std::atomic<bool> flagInterruptMsgProc{false};
1523
1531
1537 std::unique_ptr<i2p::sam::Session> m_i2p_sam_session;
1538
1545
1550
1555 std::atomic_bool m_start_extra_block_relay_peers{false};
1556
1561 std::vector<CService> m_onion_binds;
1562
1568
1574
1579
1587 std::queue<std::unique_ptr<i2p::sam::Session>> m_unused_i2p_sessions GUARDED_BY(m_unused_i2p_sessions_mutex);
1588
1593
1603
1607 std::list<ReconnectionInfo> m_reconnections GUARDED_BY(m_reconnections_mutex);
1608
1610 void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_unused_i2p_sessions_mutex);
1611
1616 static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE{10};
1617
1623 {
1624 public:
1625 explicit NodesSnapshot(const CConnman& connman, bool shuffle)
1626 {
1627 {
1628 LOCK(connman.m_nodes_mutex);
1629 m_nodes_copy = connman.m_nodes;
1630 for (auto& node : m_nodes_copy) {
1631 node->AddRef();
1632 }
1633 }
1634 if (shuffle) {
1635 std::shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
1636 }
1637 }
1638
1640 {
1641 for (auto& node : m_nodes_copy) {
1642 node->Release();
1643 }
1644 }
1645
1646 const std::vector<CNode*>& Nodes() const
1647 {
1648 return m_nodes_copy;
1649 }
1650
1651 private:
1652 std::vector<CNode*> m_nodes_copy;
1653 };
1654
1656
1657 friend struct ConnmanTestMsg;
1658};
1659
1661extern std::function<void(const CAddress& addr,
1662 const std::string& msg_type,
1664 bool is_incoming)>
1666
1667#endif // BITCOIN_NET_H
int ret
int flags
Interrupt(node)
#define Assume(val)
Assume is the identity function.
Definition check.h:89
Stochastic address manager.
Definition addrman.h:88
The BIP324 packet cipher, encapsulating its key derivation, stream cipher, and AEAD.
Definition bip324.h:20
A CService with information about it as peer.
Definition protocol.h:367
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:81
Signals for UI communication.
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
Definition net.h:1623
const std::vector< CNode * > & Nodes() const
Definition net.h:1646
NodesSnapshot(const CConnman &connman, bool shuffle)
Definition net.h:1625
std::vector< CNode * > m_nodes_copy
Definition net.h:1652
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
Definition net.h:1573
std::condition_variable condMsgProc
Definition net.h:1520
std::thread threadMessageHandler
Definition net.h:1543
void RemoveLocalServices(ServiceFlags services)
Definition net.h:1227
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1407
CClientUIInterface * m_client_interface
Definition net.h:1503
void ForEachNode(const NodeFn &func) const
Definition net.h:1141
std::vector< AddedNodeParams > m_added_node_params GUARDED_BY(m_added_nodes_mutex)
int m_max_inbound
Definition net.h:1500
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
void Stop()
Definition net.h:1110
int m_max_outbound_block_relay
Definition net.h:1495
std::array< unsigned int, Network::NET_MAX > m_network_conn_counts GUARDED_BY(m_nodes_mutex)
std::thread threadI2PAcceptIncoming
Definition net.h:1544
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:1499
uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex)
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
Definition net.h:1530
std::unique_ptr< CSemaphore > semAddnode
Definition net.h:1476
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:1483
BanMan * m_banman
Pointer to this node's banman.
Definition net.h:1506
uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1398
std::thread threadDNSAddressSeed
Definition net.h:1539
std::atomic< ServiceFlags > nLocalServices
Services this node offers.
Definition net.h:1473
const NetGroupManager & m_netgroupman
Definition net.h:1418
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
Definition net.h:1512
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
Definition net.h:1567
std::chrono::seconds m_peer_connect_timeout
Definition net.h:1403
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:1549
std::vector< ListenSocket > vhListenSocket
Definition net.h:1414
std::unique_ptr< CSemaphore > semOutbound
Definition net.h:1475
std::thread threadOpenConnections
Definition net.h:1542
Mutex m_addr_fetches_mutex
Definition net.h:1420
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
Definition net.h:1592
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
Definition net.h:1515
RecursiveMutex m_nodes_mutex
Definition net.h:1428
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...
const CChainParams & m_params
Definition net.h:1655
std::deque< std::string > m_addr_fetches GUARDED_BY(m_addr_fetches_mutex)
void AddLocalServices(ServiceFlags services)
Updates the local services that this node advertises to other peers during connection handshake.
Definition net.h:1226
AddrMan & addrman
Definition net.h:1417
Mutex mutexMsgProc
Definition net.h:1521
std::thread threadOpenAddedConnections
Definition net.h:1541
Mutex m_added_nodes_mutex
Definition net.h:1425
int m_max_outbound_full_relay
Definition net.h:1491
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition net.h:1578
std::vector< CNode * > m_nodes GUARDED_BY(m_nodes_mutex)
std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1399
uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex)
Definition net.h:1395
bool GetUseAddrmanOutgoing() const
Definition net.h:1118
std::list< CNode * > m_nodes_disconnected
Definition net.h:1427
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
Definition net.h:1537
bool m_use_addrman_outgoing
Definition net.h:1502
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1409
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:1460
std::function< void(CNode *)> NodeFn
Definition net.h:1131
NetEventsInterface * m_msgproc
Definition net.h:1504
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:1561
RecursiveMutex & GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex)
std::thread threadSocketHandler
Definition net.h:1540
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition hash.h:24
An encapsulated private key.
Definition key.h:35
Message header.
Definition protocol.h:29
Network address.
Definition netaddress.h:112
Transport protocol agnostic message container.
Definition net.h:231
CNetMessage(CNetMessage &&)=default
CNetMessage(DataStream &&recv_in)
Definition net.h:239
std::string m_type
Definition net.h:237
DataStream m_recv
received message data
Definition net.h:233
CNetMessage & operator=(const CNetMessage &)=delete
CNetMessage(const CNetMessage &)=delete
CNetMessage & operator=(CNetMessage &&)=default
Information about a peer.
Definition net.h:670
const CAddress addrBind
Definition net.h:707
bool IsFeelerConn() const
Definition net.h:800
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
Definition net.h:703
bool ExpectServicesFromConn() const
Definition net.h:812
const std::string m_dest
The pszDest argument provided to ConnectNode().
Definition net.h:710
CService m_addr_local GUARDED_BY(m_addr_local_mutex)
uint64_t nRecvBytes GUARDED_BY(cs_vRecv)
Definition net.h:698
bool IsInboundConn() const
Definition net.h:808
bool HasPermission(NetPermissionFlags permission) const
Definition net.h:721
bool IsOutboundOrBlockRelayConn() const
Definition net.h:757
NodeId GetId() const
Definition net.h:891
bool IsManualConn() const
Definition net.h:776
const std::string m_addr_name
Definition net.h:708
CNode & operator=(const CNode &)=delete
void SetCommonVersion(int greatest_common_version)
Definition net.h:916
std::list< CNetMessage > vRecvMsg
Definition net.h:959
void PongReceived(std::chrono::microseconds ping_time)
A ping-pong round trip has completed successfully.
Definition net.h:948
size_t m_msg_process_queue_size GUARDED_BY(m_msg_process_queue_mutex)
Definition net.h:963
bool IsAddrFetchConn() const
Definition net.h:804
uint64_t GetLocalNonce() const
Definition net.h:895
const CAddress addr
Definition net.h:705
CSemaphoreGrant grantOutbound
Definition net.h:729
mapMsgTypeSize mapSendBytesPerMsgType GUARDED_BY(cs_vSend)
const uint64_t nKeyedNetGroup
Definition net.h:732
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:796
int GetCommonVersion() const
Definition net.h:921
mapMsgTypeSize mapRecvBytesPerMsgType GUARDED_BY(cs_vRecv)
bool IsFullOutboundConn() const
Definition net.h:772
Mutex m_subver_mutex
Definition net.h:714
Mutex cs_vSend
Definition net.h:694
int GetRefCount() const
Definition net.h:899
Mutex m_msg_process_queue_mutex
Definition net.h:961
const ConnectionType m_conn_type
Definition net.h:736
const size_t m_recv_flood_size
Definition net.h:958
const uint64_t nLocalHostNonce
Definition net.h:955
bool IsManualOrFullOutboundConn() const
Definition net.h:780
const std::unique_ptr< Transport > m_transport
Transport serializer/deserializer.
Definition net.h:674
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:676
Mutex m_addr_local_mutex
Definition net.h:967
CNode(const CNode &)=delete
size_t m_send_memusage GUARDED_BY(cs_vSend)
Sum of GetMemoryUsage of all vSendMsg entries.
Definition net.h:689
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
Definition net.h:712
const NodeId id
Definition net.h:954
Mutex cs_vRecv
Definition net.h:696
uint64_t nSendBytes GUARDED_BY(cs_vSend)
Total number of bytes sent on the wire to this peer.
Definition net.h:691
Mutex m_sock_mutex
Definition net.h:695
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:936
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:719
std::string m_session_id
BIP324 session id string in hex, if any.
Definition net.h:222
std::string addrLocal
Definition net.h:210
CAddress addrBind
Definition net.h:214
uint64_t nRecvBytes
Definition net.h:204
std::chrono::microseconds m_last_ping_time
Definition net.h:207
uint32_t m_mapped_as
Definition net.h:217
mapMsgTypeSize mapRecvBytesPerMsgType
Definition net.h:205
bool fInbound
Definition net.h:196
uint64_t nSendBytes
Definition net.h:202
std::chrono::seconds m_last_recv
Definition net.h:189
ConnectionType m_conn_type
Definition net.h:218
std::chrono::seconds m_last_send
Definition net.h:188
std::chrono::seconds m_last_tx_time
Definition net.h:190
CAddress addr
Definition net.h:212
mapMsgTypeSize mapSendBytesPerMsgType
Definition net.h:203
std::chrono::microseconds m_min_ping_time
Definition net.h:208
TransportProtocolType m_transport_type
Transport protocol type.
Definition net.h:220
std::chrono::seconds m_connected
Definition net.h:192
bool m_bip152_highbandwidth_from
Definition net.h:200
bool m_bip152_highbandwidth_to
Definition net.h:198
std::string m_addr_name
Definition net.h:193
int nVersion
Definition net.h:194
std::chrono::seconds m_last_block_time
Definition net.h:191
Network m_network
Definition net.h:216
NodeId nodeid
Definition net.h:187
std::string cleanSubVer
Definition net.h:195
int m_starting_height
Definition net.h:201
NetPermissionFlags m_permission_flags
Definition net.h:206
Simple class for background tasks that should be run periodically or once "after a while".
Definition scheduler.h:40
RAII-style semaphore lock.
Definition sync.h:353
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:531
SipHash-2-4.
Definition siphash.h:15
A helper class for interruptible sleeps.
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:147
Fast randomness source.
Definition random.h:377
Different type to mark Mutex at global scope.
Definition sync.h:140
Interface for message handling.
Definition net.h:989
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition net.h:992
virtual bool SendMessages(CNode *pnode) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Send queued protocol messages to a given node.
virtual void FinalizeNode(const CNode &node)=0
Handle removal of a peer (clear state)
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 ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt) EXCLUSIVE_LOCKS_REQUIRED(g_msgproc_mutex)=0
Process protocol messages received from 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:16
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition sock.h:27
A Span is an object that can refer to a contiguous sequence of objects.
Definition span.h:98
The Transport converts one connection's sent messages to wire bytes, and received bytes back.
Definition net.h:251
virtual ~Transport()=default
virtual Info GetInfo() const noexcept=0
Retrieve information about this transport.
std::tuple< Span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
Definition net.h:304
CHash256 hasher GUARDED_BY(m_recv_mutex)
DataStream hdrbuf GUARDED_BY(m_recv_mutex)
Definition net.h:373
bool m_sending_header GUARDED_BY(m_send_mutex)
Whether we're currently sending header bytes or message bytes.
Definition net.h:409
const NodeId m_node_id
Definition net.h:368
Mutex m_send_mutex
Lock for sending state.
Definition net.h:403
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:411
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:367
unsigned int nHdrPos GUARDED_BY(m_recv_mutex)
DataStream vRecv GUARDED_BY(m_recv_mutex)
Definition net.h:375
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Definition net.h:395
CMessageHeader hdr GUARDED_BY(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
Definition net.h:369
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:416
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:609
const NodeId m_nodeid
NodeId (for debug logging).
Definition net.h:577
BIP324Cipher m_cipher
Cipher state.
Definition net.h:573
SendState
State type that controls the sender side.
Definition net.h:542
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
Definition net.h:579
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:575
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:585
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:601
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:477
256-bit opaque blob.
Definition uint256.h:178
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ 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.
static CService ip(uint32_t i)
CClientUIInterface uiInterface
std::array< uint8_t, 4 > MessageStartChars
unsigned int nonce
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
Definition net.cpp:3956
uint16_t GetListenPort()
Definition net.cpp:133
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:77
bool IsLocal(const CService &addr)
check whether a given address is potentially local
Definition net.cpp:318
void RemoveLocal(const CService &addr)
Definition net.cpp:299
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:65
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
Definition net.h:57
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:69
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
Definition net.cpp:266
bool fDiscover
Definition net.cpp:113
static const size_t DEFAULT_MAXSENDBUFFER
Definition net.h:93
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:85
static constexpr bool DEFAULT_FIXEDSEEDS
Definition net.h:91
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:81
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:63
bool fListen
Definition net.cpp:114
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
Definition net.h:61
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:92
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition net.cpp:117
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition net.h:79
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
Definition net.cpp:235
std::map< std::string, uint64_t > mapMsgTypeSize
Definition net.h:182
const std::string NET_MESSAGE_TYPE_OTHER
Definition net.cpp:105
static constexpr bool DEFAULT_FORCEDNSSEED
Definition net.h:89
static constexpr bool DEFAULT_DNSSEED
Definition net.h:90
int64_t NodeId
Definition net.h:97
CService GetLocalAddress(const CNode &peer)
Definition net.cpp:215
GlobalMutex g_maplocalhost_mutex
Definition net.cpp:115
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition net.h:73
static const bool DEFAULT_LISTEN
-listen default
Definition net.h:75
static constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
Definition net.h:87
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
Definition net.h:59
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
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:67
@ LOCAL_NONE
Definition net.h:148
@ LOCAL_MAPPED
Definition net.h:151
@ LOCAL_MANUAL
Definition net.h:152
@ LOCAL_MAX
Definition net.h:154
@ LOCAL_BIND
Definition net.h:150
@ LOCAL_IF
Definition net.h:149
static constexpr bool DEFAULT_V2_TRANSPORT
Definition net.h:95
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:71
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:3088
bool SeenLocal(const CService &addr)
vote for a local address
Definition net.cpp:307
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetPermissionFlags
Network
A network type.
Definition netaddress.h:32
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:108
CService resolvedAddress
Definition net.h:106
AddedNodeParams m_params
Definition net.h:105
bool fConnected
Definition net.h:107
std::string m_added_node
Definition net.h:100
bool m_use_v2transport
Definition net.h:101
Cache responses to addr requests to minimize privacy leak.
Definition net.h:1441
std::vector< CAddress > m_addrs_response_cache
Definition net.h:1442
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
Definition net.h:1260
ListenSocket(std::shared_ptr< Sock > sock_, NetPermissionFlags permissions_)
Definition net.h:1261
NetPermissionFlags m_permissions
Definition net.h:1267
std::shared_ptr< Sock > sock
Definition net.h:1259
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition net.h:1050
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition net.h:1048
std::vector< CService > onion_binds
Definition net.h:1052
std::vector< std::string > m_specified_outgoing
Definition net.h:1057
std::vector< std::string > m_added_nodes
Definition net.h:1058
std::vector< CService > vBinds
Definition net.h:1051
bool m_i2p_accept_incoming
Definition net.h:1059
std::vector< std::string > vSeedNodes
Definition net.h:1047
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition net.h:1055
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition net.h:1049
Struct for entries in m_reconnections.
Definition net.h:1596
CSemaphoreGrant grant
Definition net.h:1598
ConnectionType conn_type
Definition net.h:1600
std::string destination
Definition net.h:1599
CSerializedNetMsg(const CSerializedNetMsg &msg)=delete
CSerializedNetMsg Copy() const
Definition net.h:122
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::string m_type
Definition net.h:131
CSerializedNetMsg & operator=(const CSerializedNetMsg &)=delete
CSerializedNetMsg()=default
CSerializedNetMsg(CSerializedNetMsg &&)=default
std::vector< unsigned char > data
Definition net.h:130
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
Definition net.cpp:119
uint16_t nPort
Definition net.h:175
std::optional< uint256 > session_id
Definition net.h:258
TransportProtocolType transport_type
Definition net.h:257
Bilingual messages:
Definition translation.h:18
#define AssertLockNotHeld(cs)
Definition sync.h:147
#define LOCK(cs)
Definition sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:301
#define AssertLockHeld(cs)
Definition sync.h:142
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
#define LOCK_RETURNED(x)
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
assert(!tx.IsCoinBase())