Bitcoin Core  29.1.0
P2P Digital Currency
net.h
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 #ifndef BITCOIN_TEST_UTIL_NET_H
6 #define BITCOIN_TEST_UTIL_NET_H
7 
8 #include <compat/compat.h>
9 #include <netmessagemaker.h>
10 #include <net.h>
11 #include <net_permissions.h>
12 #include <net_processing.h>
13 #include <netaddress.h>
14 #include <node/connection_types.h>
15 #include <node/eviction.h>
16 #include <span.h>
17 #include <sync.h>
18 #include <util/sock.h>
19 
20 #include <algorithm>
21 #include <array>
22 #include <cassert>
23 #include <chrono>
24 #include <condition_variable>
25 #include <cstdint>
26 #include <cstring>
27 #include <memory>
28 #include <optional>
29 #include <string>
30 #include <unordered_map>
31 #include <vector>
32 
33 class FastRandomContext;
34 
35 struct ConnmanTestMsg : public CConnman {
36  using CConnman::CConnman;
37 
39  {
40  m_msgproc = msgproc;
41  }
42 
43  void SetPeerConnectTimeout(std::chrono::seconds timeout)
44  {
45  m_peer_connect_timeout = timeout;
46  }
47 
48  std::vector<CNode*> TestNodes()
49  {
51  return m_nodes;
52  }
53 
55  {
57  m_nodes.push_back(&node);
58 
59  if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];
60  }
61 
63  {
65  for (CNode* node : m_nodes) {
66  delete node;
67  }
68  m_nodes.clear();
69  }
70 
71  void Handshake(CNode& node,
72  bool successfully_connected,
73  ServiceFlags remote_services,
74  ServiceFlags local_services,
75  int32_t version,
76  bool relay_txs)
78 
80  {
81  return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc);
82  }
83 
84  void NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const;
85 
86  bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;
87  void FlushSendBuffer(CNode& node) const;
88 
89  bool AlreadyConnectedPublic(const CAddress& addr) { return AlreadyConnectedToAddress(addr); };
90 
91  CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
93 };
94 
96  NODE_NONE,
98  NODE_BLOOM,
102  NODE_P2P_V2,
103 };
104 
116 };
117 
125 };
126 
127 constexpr auto ALL_NETWORKS = std::array{
135 };
136 
141 class ZeroSock : public Sock
142 {
143 public:
144  ZeroSock();
145 
146  ~ZeroSock() override;
147 
148  ssize_t Send(const void*, size_t len, int) const override;
149 
150  ssize_t Recv(void* buf, size_t len, int flags) const override;
151 
152  int Connect(const sockaddr*, socklen_t) const override;
153 
154  int Bind(const sockaddr*, socklen_t) const override;
155 
156  int Listen(int) const override;
157 
158  std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
159 
160  int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;
161 
162  int SetSockOpt(int, int, const void*, socklen_t) const override;
163 
164  int GetSockName(sockaddr* name, socklen_t* name_len) const override;
165 
166  bool SetNonBlocking() const override;
167 
168  bool IsSelectable() const override;
169 
170  bool Wait(std::chrono::milliseconds timeout,
171  Event requested,
172  Event* occurred = nullptr) const override;
173 
174  bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
175 
176 private:
177  ZeroSock& operator=(Sock&& other) override;
178 };
179 
186 {
187 public:
188  explicit StaticContentsSock(const std::string& contents);
189 
194  ssize_t Recv(void* buf, size_t len, int flags) const override;
195 
196  bool IsConnected(std::string&) const override
197  {
198  return true;
199  }
200 
201 private:
202  StaticContentsSock& operator=(Sock&& other) override;
203 
204  const std::string m_contents;
205  mutable size_t m_consumed{0};
206 };
207 
212 class DynSock : public ZeroSock
213 {
214 public:
218  class Pipe
219  {
220  public:
229  ssize_t GetBytes(void* buf, size_t len, int flags = 0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
230 
236  std::optional<CNetMessage> GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
237 
241  void PushBytes(const void* buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
242 
246  template <typename... Args>
247  void PushNetMsg(const std::string& type, Args&&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
248 
253 
254  private:
260 
262  std::condition_variable m_cond;
263  std::vector<uint8_t> m_data GUARDED_BY(m_mutex);
264  bool m_eof GUARDED_BY(m_mutex){false};
265  };
266 
267  struct Pipes {
270  };
271 
275  class Queue
276  {
277  public:
278  using S = std::unique_ptr<DynSock>;
279 
281  {
282  LOCK(m_mutex);
283  m_queue.push(std::move(s));
284  }
285 
286  std::optional<S> Pop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
287  {
288  LOCK(m_mutex);
289  if (m_queue.empty()) {
290  return std::nullopt;
291  }
292  S front{std::move(m_queue.front())};
293  m_queue.pop();
294  return front;
295  }
296 
298  {
299  LOCK(m_mutex);
300  return m_queue.empty();
301  }
302 
303  private:
304  mutable Mutex m_mutex;
305  std::queue<S> m_queue GUARDED_BY(m_mutex);
306  };
307 
313  explicit DynSock(std::shared_ptr<Pipes> pipes, std::shared_ptr<Queue> accept_sockets);
314 
315  ~DynSock();
316 
317  ssize_t Recv(void* buf, size_t len, int flags) const override;
318 
319  ssize_t Send(const void* buf, size_t len, int) const override;
320 
321  std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
322 
323  bool Wait(std::chrono::milliseconds timeout,
324  Event requested,
325  Event* occurred = nullptr) const override;
326 
327  bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
328 
329 private:
330  DynSock& operator=(Sock&&) override;
331 
332  std::shared_ptr<Pipes> m_pipes;
333  std::shared_ptr<Queue> m_accept_sockets;
334 };
335 
336 template <typename... Args>
337 void DynSock::Pipe::PushNetMsg(const std::string& type, Args&&... payload)
338 {
339  auto msg = NetMsg::Make(type, std::forward<Args>(payload)...);
340  V1Transport transport{NodeId{0}};
341 
342  const bool queued{transport.SetMessageToSend(msg)};
343  assert(queued);
344 
345  LOCK(m_mutex);
346 
347  for (;;) {
348  const auto& [bytes, _more, _msg_type] = transport.GetBytesToSend(/*have_next_message=*/true);
349  if (bytes.empty()) {
350  break;
351  }
352  m_data.insert(m_data.end(), bytes.begin(), bytes.end());
353  transport.MarkBytesSent(bytes.size());
354  }
355 
356  m_cond.notify_all();
357 }
358 
359 std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
360 
361 #endif // BITCOIN_TEST_UTIL_NET_H
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1011
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1541
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:43
void Push(S s) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:280
AddrFetch connections are short lived connections used to solicit addresses from peers.
bool SetNonBlocking() const override
Set the non-blocking option on the socket.
Definition: net.cpp:199
A mocked Sock alternative that returns a statically contained data upon read and succeeds and ignores...
Definition: net.h:185
ServiceFlags
nServices flags
Definition: protocol.h:309
Inbound connections are those initiated by a peer.
assert(!tx.IsCoinBase())
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:53
std::condition_variable m_cond
Definition: net.h:262
Feeler connections are short-lived connections made to check that a node is alive.
bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock &events_per_sock) const override
Same as Wait(), but wait on many sockets within the same timeout.
Definition: net.cpp:211
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.cpp:342
IPv4.
Definition: netaddress.h:37
Mutex m_mutex
Definition: net.h:304
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]
Definition: net.h:105
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition: net.cpp:841
m_peer_connect_timeout
Definition: net.h:1099
ssize_t Send(const void *buf, size_t len, int) const override
send(2) wrapper.
Definition: net.cpp:347
A mocked Sock alternative that allows providing the data to be returned by Recv() and inspecting the ...
Definition: net.h:212
void ClearTestNodes()
Definition: net.h:62
bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const override
Wait for readiness for input (recv) or output (send).
Definition: net.cpp:203
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.cpp:353
void FlushSendBuffer(CNode &node) const
Definition: net.cpp:82
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we&#39;re already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:368
std::vector< NodeEvictionCandidate > GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext &random_context)
Definition: net.cpp:119
Unidirectional bytes or CNetMessage queue (FIFO).
Definition: net.h:218
Interface for message handling.
Definition: net.h:1007
StaticContentsSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:241
Pipe send
Definition: net.h:269
ZeroSock()
Definition: net.cpp:149
std::vector< CNode * > TestNodes()
Definition: net.h:48
NetPermissionFlags
These are the default connections that we use to connect with the network.
std::optional< S > Pop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:286
I2P.
Definition: netaddress.h:46
std::shared_ptr< Pipes > m_pipes
Definition: net.h:332
void WaitForDataOrEof(UniqueLock< Mutex > &lock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Return when there is some data to read or EOF has been signaled.
Definition: net.cpp:322
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
std::vector< uint8_t > m_data GUARDED_BY(m_mutex)
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1597
bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock &events_per_sock) const override
Same as Wait(), but wait on many sockets within the same timeout.
Definition: net.cpp:372
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:95
constexpr ConnectionType ALL_CONNECTION_TYPES[]
Definition: net.h:118
std::optional< CNetMessage > GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Deserialize a CNetMessage and remove it from the pipe.
Definition: net.cpp:269
void Eof() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Signal end-of-file on the receiving end (GetBytes() or GetNetMsg()).
Definition: net.cpp:315
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
Definition: sock.h:208
int Listen(int) const override
listen(2) wrapper.
Definition: net.cpp:166
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
bool IsSelectable() const override
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition: net.cpp:201
Fast randomness source.
Definition: random.h:376
Mutex m_mutex
Definition: net.h:261
void NodeReceiveMsgBytes(CNode &node, Span< const uint8_t > msg_bytes, bool &complete) const
Definition: net.cpp:74
A CService with information about it as peer.
Definition: protocol.h:366
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.cpp:168
int SetSockOpt(int, int, const void *, socklen_t) const override
setsockopt(2) wrapper.
Definition: net.cpp:191
std::queue< S > m_queue GUARDED_BY(m_mutex)
A mocked Sock alternative that succeeds on all operations.
Definition: net.h:141
int64_t NodeId
Definition: net.h:97
ZeroSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:220
Definition: net.h:1051
int Bind(const sockaddr *, socklen_t) const override
bind(2) wrapper.
Definition: net.cpp:164
uint8_t Event
Definition: sock.h:138
bool AlreadyConnectedPublic(const CAddress &addr)
Definition: net.h:89
bool IsConnected(std::string &) const override
Check if still connected.
Definition: net.h:196
bool ReceiveMsgFrom(CNode &node, CSerializedNetMsg &&ser_msg) const
Definition: net.cpp:94
StaticContentsSock(const std::string &contents)
Definition: net.cpp:226
bool m_eof GUARDED_BY(m_mutex)
Definition: net.h:264
std::unique_ptr< DynSock > S
Definition: net.h:278
RecursiveMutex m_nodes_mutex
Definition: net.h:1447
const std::string m_contents
Definition: net.h:204
m_msgproc
Definition: net.h:1096
Definition: messages.h:20
bool Empty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:297
int flags
Definition: bitcoin-tx.cpp:536
ssize_t GetBytes(void *buf, size_t len, int flags=0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get bytes and remove them from the pipe.
Definition: net.cpp:247
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const override
getsockopt(2) wrapper.
Definition: net.cpp:185
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.cpp:156
DynSock(std::shared_ptr< Pipes > pipes, std::shared_ptr< Queue > accept_sockets)
Create a new mocked sock.
Definition: net.cpp:332
void PushBytes(const void *buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Push bytes to the pipe.
Definition: net.cpp:307
~ZeroSock() override
Definition: net.cpp:152
IPv6.
Definition: netaddress.h:40
TOR (v2 or v3)
Definition: netaddress.h:43
ssize_t Recv(void *buf, size_t len, int flags) const override
Return parts of the contents that was provided at construction until it is exhausted and then return ...
Definition: net.cpp:231
constexpr auto ALL_NETWORKS
Definition: net.h:127
ConnectionType
Different types of connections to a peer.
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams &params, bool network_active=true)
Definition: net.cpp:3209
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:151
void SetMsgProc(NetEventsInterface *msgproc)
Definition: net.h:38
~DynSock()
Definition: net.cpp:337
RAII helper class that manages a socket and closes it automatically when it goes out of scope...
Definition: sock.h:26
ssize_t Send(const void *, size_t len, int) const override
send(2) wrapper.
Definition: net.cpp:154
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
Information about a peer.
Definition: net.h:672
int GetSockName(sockaddr *name, socklen_t *name_len) const override
getsockname(2) wrapper.
Definition: net.cpp:193
void Handshake(CNode &node, bool successfully_connected, ServiceFlags remote_services, ServiceFlags local_services, int32_t version, bool relay_txs) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface bool ProcessMessagesOnce(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface
Definition: net.h:79
int Connect(const sockaddr *, socklen_t) const override
connect(2) wrapper.
Definition: net.cpp:162
Pipe recv
Definition: net.h:268
void PushNetMsg(const std::string &type, Args &&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Construct and push CNetMessage to the pipe.
Definition: net.h:337
size_t m_consumed
Definition: net.h:205
CNode * ConnectNodePublic(PeerManager &peerman, const char *pszDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:108
CJDNS.
Definition: netaddress.h:49
void AddTestNode(CNode &node)
Definition: net.h:54
std::shared_ptr< Queue > m_accept_sockets
Definition: net.h:333
We use block-relay-only connections to help prevent against partition attacks.
A basic thread-safe queue, used for queuing sockets to be returned by Accept().
Definition: net.h:275
DynSock & operator=(Sock &&) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:406
bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const override
Wait for readiness for input (recv) or output (send).
Definition: net.cpp:359
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:34