Bitcoin Core 29.99.0
P2P Digital Currency
net.h
Go to the documentation of this file.
1// Copyright (c) 2020-present 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>
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
34
35struct ConnmanTestMsg : public 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 void ResetAddrCache();
50
51 std::vector<CNode*> TestNodes()
52 {
54 return m_nodes;
55 }
56
58 {
60 m_nodes.push_back(&node);
61
62 if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];
63 }
64
66 {
68 for (CNode* node : m_nodes) {
69 delete node;
70 }
71 m_nodes.clear();
72 }
73
74 void Handshake(CNode& node,
75 bool successfully_connected,
76 ServiceFlags remote_services,
77 ServiceFlags local_services,
78 int32_t version,
79 bool relay_txs)
81
83 {
84 return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc);
85 }
86
87 void NodeReceiveMsgBytes(CNode& node, std::span<const uint8_t> msg_bytes, bool& complete) const;
88
89 bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;
90 void FlushSendBuffer(CNode& node) const;
91
92 bool AlreadyConnectedPublic(const CAddress& addr) { return AlreadyConnectedToAddress(addr); };
93
94 CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
96};
97
106};
107
119};
120
128};
129
130constexpr auto ALL_NETWORKS = std::array{
138};
139
144class ZeroSock : public Sock
145{
146public:
147 ZeroSock();
148
149 ~ZeroSock() override;
150
151 ssize_t Send(const void*, size_t len, int) const override;
152
153 ssize_t Recv(void* buf, size_t len, int flags) const override;
154
155 int Connect(const sockaddr*, socklen_t) const override;
156
157 int Bind(const sockaddr*, socklen_t) const override;
158
159 int Listen(int) const override;
160
161 std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
162
163 int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;
164
165 int SetSockOpt(int, int, const void*, socklen_t) const override;
166
167 int GetSockName(sockaddr* name, socklen_t* name_len) const override;
168
169 bool SetNonBlocking() const override;
170
171 bool IsSelectable() const override;
172
173 bool Wait(std::chrono::milliseconds timeout,
174 Event requested,
175 Event* occurred = nullptr) const override;
176
177 bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
178
179private:
180 ZeroSock& operator=(Sock&& other) override;
181};
182
189{
190public:
191 explicit StaticContentsSock(const std::string& contents);
192
197 ssize_t Recv(void* buf, size_t len, int flags) const override;
198
199 bool IsConnected(std::string&) const override
200 {
201 return true;
202 }
203
204private:
205 StaticContentsSock& operator=(Sock&& other) override;
206
207 const std::string m_contents;
208 mutable size_t m_consumed{0};
209};
210
215class DynSock : public ZeroSock
216{
217public:
221 class Pipe
222 {
223 public:
232 ssize_t GetBytes(void* buf, size_t len, int flags = 0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
233
239 std::optional<CNetMessage> GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
240
244 void PushBytes(const void* buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
245
249 template <typename... Args>
250 void PushNetMsg(const std::string& type, Args&&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
251
256
257 private:
263
265 std::condition_variable m_cond;
266 std::vector<uint8_t> m_data GUARDED_BY(m_mutex);
267 bool m_eof GUARDED_BY(m_mutex){false};
268 };
269
270 struct Pipes {
273 };
274
278 class Queue
279 {
280 public:
281 using S = std::unique_ptr<DynSock>;
282
284 {
285 LOCK(m_mutex);
286 m_queue.push(std::move(s));
287 }
288
290 {
291 LOCK(m_mutex);
292 if (m_queue.empty()) {
293 return std::nullopt;
294 }
295 S front{std::move(m_queue.front())};
296 m_queue.pop();
297 return front;
298 }
299
301 {
302 LOCK(m_mutex);
303 return m_queue.empty();
304 }
305
306 private:
307 mutable Mutex m_mutex;
308 std::queue<S> m_queue GUARDED_BY(m_mutex);
309 };
310
316 explicit DynSock(std::shared_ptr<Pipes> pipes, std::shared_ptr<Queue> accept_sockets);
317
318 ~DynSock();
319
320 ssize_t Recv(void* buf, size_t len, int flags) const override;
321
322 ssize_t Send(const void* buf, size_t len, int) const override;
323
324 std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
325
326 bool Wait(std::chrono::milliseconds timeout,
327 Event requested,
328 Event* occurred = nullptr) const override;
329
330 bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
331
332private:
333 DynSock& operator=(Sock&&) override;
334
335 std::shared_ptr<Pipes> m_pipes;
336 std::shared_ptr<Queue> m_accept_sockets;
337};
338
339template <typename... Args>
340void DynSock::Pipe::PushNetMsg(const std::string& type, Args&&... payload)
341{
342 auto msg = NetMsg::Make(type, std::forward<Args>(payload)...);
343 V1Transport transport{NodeId{0}};
344
345 const bool queued{transport.SetMessageToSend(msg)};
346 assert(queued);
347
348 LOCK(m_mutex);
349
350 for (;;) {
351 const auto& [bytes, _more, _msg_type] = transport.GetBytesToSend(/*have_next_message=*/true);
352 if (bytes.empty()) {
353 break;
354 }
355 m_data.insert(m_data.end(), bytes.begin(), bytes.end());
356 transport.MarkBytesSent(bytes.size());
357 }
358
359 m_cond.notify_all();
360}
361
362std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
363
364#endif // BITCOIN_TEST_UTIL_NET_H
int flags
Definition: bitcoin-tx.cpp:529
A CService with information about it as peer.
Definition: protocol.h:367
Definition: net.h:1054
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:367
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams &params, bool network_active=true)
Definition: net.cpp:3211
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1554
m_peer_connect_timeout
Definition: net.h:1101
RecursiveMutex m_nodes_mutex
Definition: net.h:1460
m_msgproc
Definition: net.h:1098
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1610
Information about a peer.
Definition: net.h:675
Unidirectional bytes or CNetMessage queue (FIFO).
Definition: net.h:222
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:256
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:331
void Eof() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Signal end-of-file on the receiving end (GetBytes() or GetNetMsg()).
Definition: net.cpp:324
std::condition_variable m_cond
Definition: net.h:265
std::optional< CNetMessage > GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Deserialize a CNetMessage and remove it from the pipe.
Definition: net.cpp:278
Mutex m_mutex
Definition: net.h:264
void PushNetMsg(const std::string &type, Args &&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Construct and push CNetMessage to the pipe.
Definition: net.h:340
std::vector< uint8_t > m_data GUARDED_BY(m_mutex)
void PushBytes(const void *buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Push bytes to the pipe.
Definition: net.cpp:316
bool m_eof GUARDED_BY(m_mutex)
Definition: net.h:267
A basic thread-safe queue, used for queuing sockets to be returned by Accept().
Definition: net.h:279
std::unique_ptr< DynSock > S
Definition: net.h:281
std::optional< S > Pop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:289
std::queue< S > m_queue GUARDED_BY(m_mutex)
void Push(S s) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:283
Mutex m_mutex
Definition: net.h:307
bool Empty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: net.h:300
A mocked Sock alternative that allows providing the data to be returned by Recv() and inspecting the ...
Definition: net.h:216
DynSock & operator=(Sock &&) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:415
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.cpp:351
std::shared_ptr< Pipes > m_pipes
Definition: net.h:335
std::shared_ptr< Queue > m_accept_sockets
Definition: net.h:336
~DynSock()
Definition: net.cpp:346
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:368
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.cpp:362
ssize_t Send(const void *buf, size_t len, int) const override
send(2) wrapper.
Definition: net.cpp:356
DynSock(std::shared_ptr< Pipes > pipes, std::shared_ptr< Queue > accept_sockets)
Create a new mocked sock.
Definition: net.cpp:341
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:381
Fast randomness source.
Definition: random.h:386
Interface for message handling.
Definition: net.h:1010
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1013
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:27
uint8_t Event
Definition: sock.h:138
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
A mocked Sock alternative that returns a statically contained data upon read and succeeds and ignores...
Definition: net.h:189
bool IsConnected(std::string &) const override
Check if still connected.
Definition: net.h:199
size_t m_consumed
Definition: net.h:208
const std::string m_contents
Definition: net.h:207
StaticContentsSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:250
StaticContentsSock(const std::string &contents)
Definition: net.cpp:235
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:240
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:147
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Definition: net.cpp:842
A mocked Sock alternative that succeeds on all operations.
Definition: net.h:145
int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const override
getsockopt(2) wrapper.
Definition: net.cpp:194
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:212
ZeroSock()
Definition: net.cpp:158
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:220
int GetSockName(sockaddr *name, socklen_t *name_len) const override
getsockname(2) wrapper.
Definition: net.cpp:202
int Listen(int) const override
listen(2) wrapper.
Definition: net.cpp:175
~ZeroSock() override
Definition: net.cpp:161
int Bind(const sockaddr *, socklen_t) const override
bind(2) wrapper.
Definition: net.cpp:173
int Connect(const sockaddr *, socklen_t) const override
connect(2) wrapper.
Definition: net.cpp:171
ssize_t Send(const void *, size_t len, int) const override
send(2) wrapper.
Definition: net.cpp:163
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.cpp:177
bool SetNonBlocking() const override
Set the non-blocking option on the socket.
Definition: net.cpp:208
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.cpp:165
ZeroSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.cpp:229
int SetSockOpt(int, int, const void *, socklen_t) const override
setsockopt(2) wrapper.
Definition: net.cpp:200
bool IsSelectable() const override
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition: net.cpp:210
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.
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
Definition: messages.h:20
int64_t NodeId
Definition: net.h:98
NetPermissionFlags
@ NET_I2P
I2P.
Definition: netaddress.h:46
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:49
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:43
@ NET_IPV6
IPv6.
Definition: netaddress.h:40
@ NET_IPV4
IPv4.
Definition: netaddress.h:37
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:34
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:53
ServiceFlags
nServices flags
Definition: protocol.h:309
@ NODE_NONE
Definition: protocol.h:312
@ NODE_P2P_V2
Definition: protocol.h:330
@ NODE_WITNESS
Definition: protocol.h:320
@ NODE_NETWORK_LIMITED
Definition: protocol.h:327
@ NODE_BLOOM
Definition: protocol.h:317
@ NODE_NETWORK
Definition: protocol.h:315
@ NODE_COMPACT_FILTERS
Definition: protocol.h:323
const char * name
Definition: rest.cpp:50
void NodeReceiveMsgBytes(CNode &node, std::span< const uint8_t > msg_bytes, bool &complete) const
Definition: net.cpp:83
bool ReceiveMsgFrom(CNode &node, CSerializedNetMsg &&ser_msg) const
Definition: net.cpp:103
CNode * ConnectNodePublic(PeerManager &peerman, const char *pszDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:117
void ClearTestNodes()
Definition: net.h:65
void ResetAddrCache()
Definition: net.cpp:74
bool AlreadyConnectedPublic(const CAddress &addr)
Definition: net.h:92
void SetMsgProc(NetEventsInterface *msgproc)
Definition: net.h:38
void AddTestNode(CNode &node)
Definition: net.h:57
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:82
std::vector< CNode * > TestNodes()
Definition: net.h:51
void FlushSendBuffer(CNode &node) const
Definition: net.cpp:91
void ResetMaxOutboundCycle()
Definition: net.cpp:76
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:43
Pipe send
Definition: net.h:272
Pipe recv
Definition: net.h:271
#define LOCK(cs)
Definition: sync.h:259
std::vector< NodeEvictionCandidate > GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext &random_context)
Definition: net.cpp:128
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:98
constexpr ConnectionType ALL_CONNECTION_TYPES[]
Definition: net.h:121
constexpr auto ALL_NETWORKS
Definition: net.h:130
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]
Definition: net.h:108
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
assert(!tx.IsCoinBase())