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