Branch data Line data Source code
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>
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 : 4 : struct ConnmanTestMsg : public CConnman {
36 [ + - ]: 181 : using CConnman::CConnman;
37 : :
38 : : void SetMsgProc(NetEventsInterface* msgproc)
39 : : {
40 : : m_msgproc = msgproc;
41 : : }
42 : :
43 : 1 : void SetPeerConnectTimeout(std::chrono::seconds timeout)
44 : : {
45 [ + - ]: 1 : m_peer_connect_timeout = timeout;
46 : : }
47 : :
48 : : void ResetAddrCache();
49 : : void ResetMaxOutboundCycle();
50 : :
51 : 4 : std::vector<CNode*> TestNodes()
52 : : {
53 : 4 : LOCK(m_nodes_mutex);
54 [ + - ]: 4 : return m_nodes;
55 : 4 : }
56 : :
57 : 23 : void AddTestNode(CNode& node)
58 : : {
59 : 23 : LOCK(m_nodes_mutex);
60 [ + - ]: 23 : m_nodes.push_back(&node);
61 : :
62 [ + + + - ]: 23 : if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];
63 : 23 : }
64 : :
65 : 4 : void ClearTestNodes()
66 : : {
67 : 4 : LOCK(m_nodes_mutex);
68 [ + + ]: 27 : for (CNode* node : m_nodes) {
69 [ + - ]: 23 : delete node;
70 : : }
71 [ + - + - ]: 8 : m_nodes.clear();
72 : 4 : }
73 : :
74 : : void CreateNodeFromAcceptedSocketPublic(std::unique_ptr<Sock> sock,
75 : : NetPermissionFlags permissions,
76 : : const CAddress& addr_bind,
77 : : const CAddress& addr_peer)
78 : : {
79 : : CreateNodeFromAcceptedSocket(std::move(sock), permissions, addr_bind, addr_peer);
80 : : }
81 : :
82 : : bool InitBindsPublic(const CConnman::Options& options)
83 : : {
84 : : return InitBinds(options);
85 : : }
86 : :
87 : : void SocketHandlerPublic()
88 : : {
89 : : SocketHandler();
90 : : }
91 : :
92 : : void Handshake(CNode& node,
93 : : bool successfully_connected,
94 : : ServiceFlags remote_services,
95 : : ServiceFlags local_services,
96 : : int32_t version,
97 : : bool relay_txs)
98 : : EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
99 : :
100 : 2 : bool ProcessMessagesOnce(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex)
101 : : {
102 : 2 : return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc);
103 : : }
104 : :
105 : : void NodeReceiveMsgBytes(CNode& node, std::span<const uint8_t> msg_bytes, bool& complete) const;
106 : :
107 : : bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;
108 : : void FlushSendBuffer(CNode& node) const;
109 : :
110 [ + - ]: 6 : bool AlreadyConnectedToAddressPublic(const CNetAddr& addr) { return AlreadyConnectedToAddress(addr); };
111 : :
112 : : CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
113 : : EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);
114 : : };
115 : :
116 : : constexpr ServiceFlags ALL_SERVICE_FLAGS[]{
117 : : NODE_NONE,
118 : : NODE_NETWORK,
119 : : NODE_BLOOM,
120 : : NODE_WITNESS,
121 : : NODE_COMPACT_FILTERS,
122 : : NODE_NETWORK_LIMITED,
123 : : NODE_P2P_V2,
124 : : };
125 : :
126 : : constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]{
127 : : NetPermissionFlags::None,
128 : : NetPermissionFlags::BloomFilter,
129 : : NetPermissionFlags::Relay,
130 : : NetPermissionFlags::ForceRelay,
131 : : NetPermissionFlags::NoBan,
132 : : NetPermissionFlags::Mempool,
133 : : NetPermissionFlags::Addr,
134 : : NetPermissionFlags::Download,
135 : : NetPermissionFlags::Implicit,
136 : : NetPermissionFlags::All,
137 : : };
138 : :
139 : : constexpr ConnectionType ALL_CONNECTION_TYPES[]{
140 : : ConnectionType::INBOUND,
141 : : ConnectionType::OUTBOUND_FULL_RELAY,
142 : : ConnectionType::MANUAL,
143 : : ConnectionType::FEELER,
144 : : ConnectionType::BLOCK_RELAY,
145 : : ConnectionType::ADDR_FETCH,
146 : : ConnectionType::PRIVATE_BROADCAST,
147 : : };
148 : :
149 : : constexpr auto ALL_NETWORKS = std::array{
150 : : Network::NET_UNROUTABLE,
151 : : Network::NET_IPV4,
152 : : Network::NET_IPV6,
153 : : Network::NET_ONION,
154 : : Network::NET_I2P,
155 : : Network::NET_CJDNS,
156 : : Network::NET_INTERNAL,
157 : : };
158 : :
159 : : /**
160 : : * A mocked Sock alternative that succeeds on all operations.
161 : : * Returns infinite amount of 0x0 bytes on reads.
162 : : */
163 : : class ZeroSock : public Sock
164 : : {
165 : : public:
166 : : ZeroSock();
167 : :
168 : : ~ZeroSock() override;
169 : :
170 : : ssize_t Send(const void*, size_t len, int) const override;
171 : :
172 : : ssize_t Recv(void* buf, size_t len, int flags) const override;
173 : :
174 : : int Connect(const sockaddr*, socklen_t) const override;
175 : :
176 : : int Bind(const sockaddr*, socklen_t) const override;
177 : :
178 : : int Listen(int) const override;
179 : :
180 : : std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
181 : :
182 : : int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;
183 : :
184 : : int SetSockOpt(int, int, const void*, socklen_t) const override;
185 : :
186 : : int GetSockName(sockaddr* name, socklen_t* name_len) const override;
187 : :
188 : : bool SetNonBlocking() const override;
189 : :
190 : : bool IsSelectable() const override;
191 : :
192 : : bool Wait(std::chrono::milliseconds timeout,
193 : : Event requested,
194 : : Event* occurred = nullptr) const override;
195 : :
196 : : bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
197 : :
198 : : private:
199 : : ZeroSock& operator=(Sock&& other) override;
200 : : };
201 : :
202 : : /**
203 : : * A mocked Sock alternative that returns a statically contained data upon read and succeeds
204 : : * and ignores all writes. The data to be returned is given to the constructor and when it is
205 : : * exhausted an EOF is returned by further reads.
206 : : */
207 : : class StaticContentsSock : public ZeroSock
208 : : {
209 : : public:
210 : : explicit StaticContentsSock(const std::string& contents);
211 : :
212 : : /**
213 : : * Return parts of the contents that was provided at construction until it is exhausted
214 : : * and then return 0 (EOF).
215 : : */
216 : : ssize_t Recv(void* buf, size_t len, int flags) const override;
217 : :
218 : 0 : bool IsConnected(std::string&) const override
219 : : {
220 : 0 : return true;
221 : : }
222 : :
223 : : private:
224 : : StaticContentsSock& operator=(Sock&& other) override;
225 : :
226 : : const std::string m_contents;
227 : : mutable size_t m_consumed{0};
228 : : };
229 : :
230 : : /**
231 : : * A mocked Sock alternative that allows providing the data to be returned by Recv()
232 : : * and inspecting the data that has been supplied to Send().
233 : : */
234 : : class DynSock : public ZeroSock
235 : : {
236 : : public:
237 : : /**
238 : : * Unidirectional bytes or CNetMessage queue (FIFO).
239 : : */
240 : : class Pipe
241 : : {
242 : : public:
243 : : /**
244 : : * Get bytes and remove them from the pipe.
245 : : * @param[in] buf Destination to write bytes to.
246 : : * @param[in] len Write up to this number of bytes.
247 : : * @param[in] flags Same as the flags of `recv(2)`. Just `MSG_PEEK` is honored.
248 : : * @return The number of bytes written to `buf`. `0` if `Eof()` has been called.
249 : : * If no bytes are available then `-1` is returned and `errno` is set to `EAGAIN`.
250 : : */
251 : : ssize_t GetBytes(void* buf, size_t len, int flags = 0) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
252 : :
253 : : /**
254 : : * Deserialize a `CNetMessage` and remove it from the pipe.
255 : : * If not enough bytes are available then the function will wait. If parsing fails
256 : : * or EOF is signaled to the pipe, then `std::nullopt` is returned.
257 : : */
258 : : std::optional<CNetMessage> GetNetMsg() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
259 : :
260 : : /**
261 : : * Push bytes to the pipe.
262 : : */
263 : : void PushBytes(const void* buf, size_t len) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
264 : :
265 : : /**
266 : : * Construct and push CNetMessage to the pipe.
267 : : */
268 : : template <typename... Args>
269 : : void PushNetMsg(const std::string& type, Args&&... payload) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
270 : :
271 : : /**
272 : : * Signal end-of-file on the receiving end (`GetBytes()` or `GetNetMsg()`).
273 : : */
274 : : void Eof() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
275 : :
276 : : private:
277 : : /**
278 : : * Return when there is some data to read or EOF has been signaled.
279 : : * @param[in,out] lock Unique lock that must have been derived from `m_mutex` by `WAIT_LOCK(m_mutex, lock)`.
280 : : */
281 : : void WaitForDataOrEof(UniqueLock<Mutex>& lock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex);
282 : :
283 : : Mutex m_mutex;
284 : : std::condition_variable m_cond;
285 : : std::vector<uint8_t> m_data GUARDED_BY(m_mutex);
286 : : bool m_eof GUARDED_BY(m_mutex){false};
287 : : };
288 : :
289 : : struct Pipes {
290 : : Pipe recv;
291 : : Pipe send;
292 : : };
293 : :
294 : : /**
295 : : * A basic thread-safe queue, used for queuing sockets to be returned by Accept().
296 : : */
297 : : class Queue
298 : : {
299 : : public:
300 : : using S = std::unique_ptr<DynSock>;
301 : :
302 : : void Push(S s) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
303 : : {
304 : : LOCK(m_mutex);
305 : : m_queue.push(std::move(s));
306 : : }
307 : :
308 : 0 : std::optional<S> Pop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
309 : : {
310 : 0 : LOCK(m_mutex);
311 [ # # ]: 0 : if (m_queue.empty()) {
312 : 0 : return std::nullopt;
313 : : }
314 : 0 : S front{std::move(m_queue.front())};
315 : 0 : m_queue.pop();
316 : 0 : return front;
317 : 0 : }
318 : :
319 : 0 : bool Empty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
320 : : {
321 : 0 : LOCK(m_mutex);
322 [ # # ]: 0 : return m_queue.empty();
323 : 0 : }
324 : :
325 : : private:
326 : : mutable Mutex m_mutex;
327 : : std::queue<S> m_queue GUARDED_BY(m_mutex);
328 : : };
329 : :
330 : : /**
331 : : * Create a new mocked sock.
332 : : * @param[in] pipes Send/recv pipes used by the Send() and Recv() methods.
333 : : * @param[in] accept_sockets Sockets to return by the Accept() method.
334 : : */
335 : : explicit DynSock(std::shared_ptr<Pipes> pipes, std::shared_ptr<Queue> accept_sockets);
336 : :
337 : : ~DynSock();
338 : :
339 : : ssize_t Recv(void* buf, size_t len, int flags) const override;
340 : :
341 : : ssize_t Send(const void* buf, size_t len, int) const override;
342 : :
343 : : std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
344 : :
345 : : bool Wait(std::chrono::milliseconds timeout,
346 : : Event requested,
347 : : Event* occurred = nullptr) const override;
348 : :
349 : : bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
350 : :
351 : : private:
352 : : DynSock& operator=(Sock&&) override;
353 : :
354 : : std::shared_ptr<Pipes> m_pipes;
355 : : std::shared_ptr<Queue> m_accept_sockets;
356 : : };
357 : :
358 : : template <typename... Args>
359 : : void DynSock::Pipe::PushNetMsg(const std::string& type, Args&&... payload)
360 : : {
361 : : auto msg = NetMsg::Make(type, std::forward<Args>(payload)...);
362 : : V1Transport transport{NodeId{0}};
363 : :
364 : : const bool queued{transport.SetMessageToSend(msg)};
365 : : assert(queued);
366 : :
367 : : LOCK(m_mutex);
368 : :
369 : : for (;;) {
370 : : const auto& [bytes, _more, _msg_type] = transport.GetBytesToSend(/*have_next_message=*/true);
371 : : if (bytes.empty()) {
372 : : break;
373 : : }
374 : : m_data.insert(m_data.end(), bytes.begin(), bytes.end());
375 : : transport.MarkBytesSent(bytes.size());
376 : : }
377 : :
378 : : m_cond.notify_all();
379 : : }
380 : :
381 : : std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
382 : :
383 : : #endif // BITCOIN_TEST_UTIL_NET_H
|