Bitcoin Core  27.99.0
P2P Digital Currency
net.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <test/util/net.h>
6 
7 #include <net.h>
8 #include <net_processing.h>
9 #include <netaddress.h>
10 #include <netmessagemaker.h>
11 #include <node/connection_types.h>
12 #include <node/eviction.h>
13 #include <protocol.h>
14 #include <random.h>
15 #include <serialize.h>
16 #include <span.h>
17 
18 #include <vector>
19 
20 void ConnmanTestMsg::Handshake(CNode& node,
21  bool successfully_connected,
22  ServiceFlags remote_services,
23  ServiceFlags local_services,
24  int32_t version,
25  bool relay_txs)
26 {
27  auto& peerman{static_cast<PeerManager&>(*m_msgproc)};
28  auto& connman{*this};
29 
30  peerman.InitializeNode(node, local_services);
31  peerman.SendMessages(&node);
32  FlushSendBuffer(node); // Drop the version message added by SendMessages.
33 
34  CSerializedNetMsg msg_version{
36  version, //
37  Using<CustomUintFormatter<8>>(remote_services), //
38  int64_t{}, // dummy time
39  int64_t{}, // ignored service bits
40  CNetAddr::V1(CService{}), // dummy
41  int64_t{}, // ignored service bits
42  CNetAddr::V1(CService{}), // ignored
43  uint64_t{1}, // dummy nonce
44  std::string{}, // dummy subver
45  int32_t{}, // dummy starting_height
46  relay_txs),
47  };
48 
49  (void)connman.ReceiveMsgFrom(node, std::move(msg_version));
50  node.fPauseSend = false;
51  connman.ProcessMessagesOnce(node);
52  peerman.SendMessages(&node);
53  FlushSendBuffer(node); // Drop the verack message added by SendMessages.
54  if (node.fDisconnect) return;
55  assert(node.nVersion == version);
56  assert(node.GetCommonVersion() == std::min(version, PROTOCOL_VERSION));
57  CNodeStateStats statestats;
58  assert(peerman.GetNodeStateStats(node.GetId(), statestats));
59  assert(statestats.m_relay_txs == (relay_txs && !node.IsBlockOnlyConn()));
60  assert(statestats.their_services == remote_services);
61  if (successfully_connected) {
63  (void)connman.ReceiveMsgFrom(node, std::move(msg_verack));
64  node.fPauseSend = false;
65  connman.ProcessMessagesOnce(node);
66  peerman.SendMessages(&node);
67  assert(node.fSuccessfullyConnected == true);
68  }
69 }
70 
71 void ConnmanTestMsg::NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const
72 {
73  assert(node.ReceiveMsgBytes(msg_bytes, complete));
74  if (complete) {
75  node.MarkReceivedMsgsForProcessing();
76  }
77 }
78 
80 {
81  LOCK(node.cs_vSend);
82  node.vSendMsg.clear();
83  node.m_send_memusage = 0;
84  while (true) {
85  const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false);
86  if (to_send.empty()) break;
87  node.m_transport->MarkBytesSent(to_send.size());
88  }
89 }
90 
92 {
93  bool queued = node.m_transport->SetMessageToSend(ser_msg);
94  assert(queued);
95  bool complete{false};
96  while (true) {
97  const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false);
98  if (to_send.empty()) break;
99  NodeReceiveMsgBytes(node, to_send, complete);
100  node.m_transport->MarkBytesSent(to_send.size());
101  }
102  return complete;
103 }
104 
105 CNode* ConnmanTestMsg::ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
106 {
107  CNode* node = ConnectNode(CAddress{}, pszDest, /*fCountFailure=*/false, conn_type, /*use_v2transport=*/true);
108  if (!node) return nullptr;
109  node->SetCommonVersion(PROTOCOL_VERSION);
111  node->fSuccessfullyConnected = true;
112  AddTestNode(*node);
113  return node;
114 }
115 
116 std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context)
117 {
118  std::vector<NodeEvictionCandidate> candidates;
119  candidates.reserve(n_candidates);
120  for (int id = 0; id < n_candidates; ++id) {
121  candidates.push_back({
122  .id=id,
123  .m_connected=std::chrono::seconds{random_context.randrange(100)},
124  .m_min_ping_time=std::chrono::microseconds{random_context.randrange(100)},
125  .m_last_block_time=std::chrono::seconds{random_context.randrange(100)},
126  .m_last_tx_time=std::chrono::seconds{random_context.randrange(100)},
127  .fRelevantServices=random_context.randbool(),
128  .m_relay_txs=random_context.randbool(),
129  .fBloomFilter=random_context.randbool(),
130  .nKeyedNetGroup=random_context.randrange(100u),
131  .prefer_evict=random_context.randbool(),
132  .m_is_local=random_context.randbool(),
133  .m_network=ALL_NETWORKS[random_context.randrange(ALL_NETWORKS.size())],
134  .m_noban=false,
135  .m_conn_type=ConnectionType::INBOUND,
136  });
137  }
138  return candidates;
139 }
A CService with information about it as peer.
Definition: protocol.h:367
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:386
static constexpr SerParams V1
Definition: netaddress.h:231
Information about a peer.
Definition: net.h:670
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
Fast randomness source.
Definition: random.h:377
virtual void InitializeNode(const CNode &node, ServiceFlags our_services)=0
Initialize a peer (setup state)
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:316
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
ConnectionType
Different types of connections to a peer.
@ INBOUND
Inbound connections are those initiated by a peer.
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
constexpr const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.h:70
constexpr const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.h:65
Definition: messages.h:20
ServiceFlags
nServices flags
Definition: protocol.h:309
@ NODE_WITNESS
Definition: protocol.h:320
@ NODE_NETWORK
Definition: protocol.h:315
static const int PROTOCOL_VERSION
network protocol versioning
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:495
ServiceFlags their_services
bool ReceiveMsgFrom(CNode &node, CSerializedNetMsg &&ser_msg) const
Definition: net.cpp:91
CNode * ConnectNodePublic(PeerManager &peerman, const char *pszDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:105
void NodeReceiveMsgBytes(CNode &node, Span< const uint8_t > msg_bytes, bool &complete) const
Definition: net.cpp:71
void AddTestNode(CNode &node)
Definition: net.h:48
void FlushSendBuffer(CNode &node) const
Definition: net.cpp:79
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:528
#define LOCK(cs)
Definition: sync.h:257
std::vector< NodeEvictionCandidate > GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext &random_context)
Definition: net.cpp:116
constexpr auto ALL_NETWORKS
Definition: net.h:121
assert(!tx.IsCoinBase())