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 : : #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 : : #include <sync.h>
18 : : #include <util/check.h>
19 : :
20 : : #include <chrono>
21 : : #include <optional>
22 : : #include <vector>
23 : :
24 : 25994 : void ConnmanTestMsg::Handshake(CNode& node,
25 : : bool successfully_connected,
26 : : ServiceFlags remote_services,
27 : : ServiceFlags local_services,
28 : : int32_t version,
29 : : bool relay_txs)
30 : : {
31 : 25994 : auto& peerman{static_cast<PeerManager&>(*m_msgproc)};
32 : 25994 : auto& connman{*this};
33 : :
34 : 25994 : peerman.InitializeNode(node, local_services);
35 : 25994 : peerman.SendMessages(node);
36 : 25994 : FlushSendBuffer(node); // Drop the version message added by SendMessages.
37 : :
38 : 25994 : CSerializedNetMsg msg_version{
39 : 25994 : NetMsg::Make(NetMsgType::VERSION,
40 : : version, //
41 [ + - ]: 25994 : Using<CustomUintFormatter<8>>(remote_services), //
42 : 25994 : int64_t{}, // dummy time
43 : 25994 : int64_t{}, // ignored service bits
44 [ + - ]: 51988 : CNetAddr::V1(CService{}), // dummy
45 : 25994 : int64_t{}, // ignored service bits
46 [ + - ]: 51988 : CNetAddr::V1(CService{}), // ignored
47 : 25994 : uint64_t{1}, // dummy nonce
48 [ + - ]: 25994 : std::string{}, // dummy subver
49 [ + - ]: 25994 : int32_t{}, // dummy starting_height
50 : : relay_txs),
51 [ + - ]: 25994 : };
52 : :
53 [ + - ]: 25994 : (void)connman.ReceiveMsgFrom(node, std::move(msg_version));
54 [ + - ]: 25994 : node.fPauseSend = false;
55 [ + - ]: 25994 : connman.ProcessMessagesOnce(node);
56 [ + - ]: 25994 : peerman.SendMessages(node);
57 [ + - ]: 25994 : FlushSendBuffer(node); // Drop the verack message added by SendMessages.
58 [ + + ]: 25994 : if (node.fDisconnect) return;
59 [ - + ]: 19670 : assert(node.nVersion == version);
60 [ + + + + : 40609 : assert(node.GetCommonVersion() == std::min(version, node.AdvertisedVersion()));
- + ]
61 [ + - ]: 19670 : CNodeStateStats statestats;
62 [ + - - + ]: 19670 : assert(peerman.GetNodeStateStats(node.GetId(), statestats));
63 [ + + + + : 20656 : assert(statestats.m_relay_txs == (relay_txs && !node.IsBlockOnlyConn()));
- + ]
64 [ - + ]: 19670 : assert(statestats.their_services == remote_services);
65 [ + + ]: 19670 : if (successfully_connected) {
66 [ + - + - ]: 16396 : CSerializedNetMsg msg_verack{NetMsg::Make(NetMsgType::VERACK)};
67 [ + - ]: 16396 : (void)connman.ReceiveMsgFrom(node, std::move(msg_verack));
68 [ + - ]: 16396 : node.fPauseSend = false;
69 [ + - ]: 16396 : connman.ProcessMessagesOnce(node);
70 [ + - ]: 16396 : peerman.SendMessages(node);
71 [ - + ]: 16396 : assert(node.fSuccessfullyConnected == true);
72 : 16396 : }
73 : 45664 : }
74 : :
75 : 15320 : void ConnmanTestMsg::ResetAddrCache() { m_addr_response_caches = {}; }
76 : :
77 : 15320 : void ConnmanTestMsg::ResetMaxOutboundCycle()
78 : : {
79 : 15320 : LOCK(m_total_bytes_sent_mutex);
80 : 15320 : nMaxOutboundCycleStartTime = 0s;
81 [ + - ]: 15320 : nMaxOutboundTotalBytesSentInCycle = 0;
82 : 15320 : }
83 : :
84 : 15320 : void ConnmanTestMsg::Reset()
85 : : {
86 : 15320 : ResetAddrCache();
87 : 15320 : ResetMaxOutboundCycle();
88 : 15320 : m_private_broadcast.m_outbound_tor_ok_at_least_once.store(false);
89 : 15320 : m_private_broadcast.m_num_to_open.store(0);
90 : 15320 : }
91 : :
92 : 1113261 : void ConnmanTestMsg::NodeReceiveMsgBytes(CNode& node, std::span<const uint8_t> msg_bytes, bool& complete) const
93 : : {
94 [ - + ]: 1113261 : assert(node.ReceiveMsgBytes(msg_bytes, complete));
95 [ + + ]: 1113261 : if (complete) {
96 : 554834 : node.MarkReceivedMsgsForProcessing();
97 : : }
98 : 1113261 : }
99 : :
100 : 579482 : void ConnmanTestMsg::FlushSendBuffer(CNode& node) const
101 : : {
102 : 579482 : LOCK(node.cs_vSend);
103 : 579482 : node.vSendMsg.clear();
104 : 579482 : node.m_send_memusage = 0;
105 : 60126 : while (true) {
106 [ + + ]: 639608 : const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false);
107 [ + + ]: 639608 : if (to_send.empty()) break;
108 : 60126 : node.m_transport->MarkBytesSent(to_send.size());
109 : 60126 : }
110 : 579482 : }
111 : :
112 : 569884 : bool ConnmanTestMsg::ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const
113 : : {
114 : 569884 : bool queued = node.m_transport->SetMessageToSend(ser_msg);
115 [ - + ]: 569884 : assert(queued);
116 : 569884 : bool complete{false};
117 : 1113261 : while (true) {
118 [ + + ]: 1683145 : const auto& [to_send, _more, _msg_type] = node.m_transport->GetBytesToSend(false);
119 [ + + ]: 1683145 : if (to_send.empty()) break;
120 : 1113261 : NodeReceiveMsgBytes(node, to_send, complete);
121 : 1113261 : node.m_transport->MarkBytesSent(to_send.size());
122 : 1113261 : }
123 : 569884 : return complete;
124 : : }
125 : :
126 : 0 : CNode* ConnmanTestMsg::ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
127 : : {
128 [ # # # # : 0 : CNode* node = ConnectNode(CAddress{}, pszDest, /*fCountFailure=*/false, conn_type, /*use_v2transport=*/true, /*proxy_override=*/std::nullopt);
# # ]
129 [ # # ]: 0 : if (!node) return nullptr;
130 : 0 : node->SetCommonVersion(PROTOCOL_VERSION);
131 : 0 : peerman.InitializeNode(*node, ServiceFlags(NODE_NETWORK | NODE_WITNESS));
132 : 0 : node->fSuccessfullyConnected = true;
133 : 0 : AddTestNode(*node);
134 : 0 : return node;
135 : : }
136 : :
137 : 0 : std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context)
138 : : {
139 : 0 : std::vector<NodeEvictionCandidate> candidates;
140 [ # # ]: 0 : candidates.reserve(n_candidates);
141 [ # # ]: 0 : for (int id = 0; id < n_candidates; ++id) {
142 [ # # ]: 0 : candidates.push_back({
143 : 0 : .id=id,
144 : 0 : .m_connected=NodeSeconds{std::chrono::seconds{random_context.randrange(100)}},
145 : 0 : .m_min_ping_time=std::chrono::microseconds{random_context.randrange(100)},
146 : 0 : .m_last_block_time=std::chrono::seconds{random_context.randrange(100)},
147 : 0 : .m_last_tx_time=std::chrono::seconds{random_context.randrange(100)},
148 : 0 : .fRelevantServices=random_context.randbool(),
149 : 0 : .m_relay_txs=random_context.randbool(),
150 : 0 : .fBloomFilter=random_context.randbool(),
151 : 0 : .nKeyedNetGroup=random_context.randrange(100u),
152 : 0 : .prefer_evict=random_context.randbool(),
153 : 0 : .m_is_local=random_context.randbool(),
154 [ # # ]: 0 : .m_network=ALL_NETWORKS[random_context.randrange(ALL_NETWORKS.size())],
155 : : .m_noban=false,
156 : : .m_conn_type=ConnectionType::INBOUND,
157 : : });
158 : : }
159 : 0 : return candidates;
160 : 0 : }
161 : :
162 : : // Have different ZeroSock (or others that inherit from it) objects have different
163 : : // m_socket because EqualSharedPtrSock compares m_socket and we want to avoid two
164 : : // different objects comparing as equal.
165 : : static std::atomic<SOCKET> g_mocked_sock_fd{0};
166 : :
167 : 1208 : ZeroSock::ZeroSock() : Sock{g_mocked_sock_fd++} {}
168 : :
169 : : // Sock::~Sock() would try to close(2) m_socket if it is not INVALID_SOCKET, avoid that.
170 : 2416 : ZeroSock::~ZeroSock() { m_socket = INVALID_SOCKET; }
171 : :
172 : 9504 : ssize_t ZeroSock::Send(const void*, size_t len, int) const { return len; }
173 : :
174 : 0 : ssize_t ZeroSock::Recv(void* buf, size_t len, int flags) const
175 : : {
176 : 0 : memset(buf, 0x0, len);
177 : 0 : return len;
178 : : }
179 : :
180 : 0 : int ZeroSock::Connect(const sockaddr*, socklen_t) const { return 0; }
181 : :
182 : 0 : int ZeroSock::Bind(const sockaddr*, socklen_t) const { return 0; }
183 : :
184 : 0 : int ZeroSock::Listen(int) const { return 0; }
185 : :
186 : 0 : std::unique_ptr<Sock> ZeroSock::Accept(sockaddr* addr, socklen_t* addr_len) const
187 : : {
188 [ # # ]: 0 : if (addr != nullptr) {
189 : : // Pretend all connections come from 5.5.5.5:6789
190 [ # # ]: 0 : memset(addr, 0x00, *addr_len);
191 : 0 : const socklen_t write_len = static_cast<socklen_t>(sizeof(sockaddr_in));
192 [ # # ]: 0 : if (*addr_len >= write_len) {
193 : 0 : *addr_len = write_len;
194 : 0 : sockaddr_in* addr_in = reinterpret_cast<sockaddr_in*>(addr);
195 : 0 : addr_in->sin_family = AF_INET;
196 : 0 : memset(&addr_in->sin_addr, 0x05, sizeof(addr_in->sin_addr));
197 : 0 : addr_in->sin_port = htons(6789);
198 : : }
199 : : }
200 : 0 : return std::make_unique<ZeroSock>();
201 : : }
202 : :
203 : 0 : int ZeroSock::GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const
204 : : {
205 : 0 : std::memset(opt_val, 0x0, *opt_len);
206 : 0 : return 0;
207 : : }
208 : :
209 : 0 : int ZeroSock::SetSockOpt(int, int, const void*, socklen_t) const { return 0; }
210 : :
211 : 0 : int ZeroSock::GetSockName(sockaddr* name, socklen_t* name_len) const
212 : : {
213 : 0 : std::memset(name, 0x0, *name_len);
214 : 0 : return 0;
215 : : }
216 : :
217 : 0 : bool ZeroSock::SetNonBlocking() const { return true; }
218 : :
219 : 0 : bool ZeroSock::IsSelectable() const { return true; }
220 : :
221 : 0 : bool ZeroSock::Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred) const
222 : : {
223 [ # # ]: 0 : if (occurred != nullptr) {
224 : 0 : *occurred = requested;
225 : : }
226 : 0 : return true;
227 : : }
228 : :
229 : 0 : bool ZeroSock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const
230 : : {
231 [ # # ]: 0 : for (auto& [sock, events] : events_per_sock) {
232 : 0 : (void)sock;
233 : 0 : events.occurred = events.requested;
234 : : }
235 : 0 : return true;
236 : : }
237 : :
238 : 0 : ZeroSock& ZeroSock::operator=(Sock&& other)
239 : : {
240 : 0 : AssertUnreachable(); // Move of Sock into ZeroSock not allowed.
241 : : }
242 : :
243 : 0 : StaticContentsSock::StaticContentsSock(const std::string& contents)
244 [ # # ]: 0 : : m_contents{contents}
245 : : {
246 : 0 : }
247 : :
248 : 0 : ssize_t StaticContentsSock::Recv(void* buf, size_t len, int flags) const
249 : : {
250 [ # # # # ]: 0 : const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)};
251 [ # # ]: 0 : std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes);
252 [ # # ]: 0 : if ((flags & MSG_PEEK) == 0) {
253 : 0 : m_consumed += consume_bytes;
254 : : }
255 : 0 : return consume_bytes;
256 : : }
257 : :
258 : 0 : StaticContentsSock& StaticContentsSock::operator=(Sock&& other)
259 : : {
260 : 0 : AssertUnreachable(); // Move of Sock into StaticContentsSock not allowed.
261 : : }
262 : :
263 : 0 : ssize_t DynSock::Pipe::GetBytes(void* buf, size_t len, int flags)
264 : : {
265 : 0 : LOCK(m_mutex);
266 : :
267 [ # # ]: 0 : if (m_data.empty()) {
268 [ # # ]: 0 : if (m_eof) {
269 : : return 0;
270 : : }
271 : 0 : errno = EAGAIN; // Same as recv(2) on a non-blocking socket.
272 : 0 : return -1;
273 : : }
274 : :
275 [ # # # # ]: 0 : const size_t read_bytes{std::min(len, m_data.size())};
276 : :
277 [ # # ]: 0 : std::memcpy(buf, m_data.data(), read_bytes);
278 [ # # ]: 0 : if ((flags & MSG_PEEK) == 0) {
279 : 0 : m_data.erase(m_data.begin(), m_data.begin() + read_bytes);
280 : : }
281 : :
282 : 0 : return read_bytes;
283 : 0 : }
284 : :
285 : 0 : void DynSock::Pipe::PushBytes(const void* buf, size_t len)
286 : : {
287 : 0 : LOCK(m_mutex);
288 : 0 : const uint8_t* b = static_cast<const uint8_t*>(buf);
289 [ # # ]: 0 : m_data.insert(m_data.end(), b, b + len);
290 : 0 : }
291 : :
292 : 0 : void DynSock::Pipe::Eof()
293 : : {
294 : 0 : LOCK(m_mutex);
295 [ # # ]: 0 : m_eof = true;
296 : 0 : }
297 : :
298 : 0 : DynSock::DynSock(std::shared_ptr<Pipes> pipes, Queue* accept_sockets)
299 [ # # ]: 0 : : m_pipes{pipes}, m_accept_sockets{accept_sockets}
300 : : {
301 : 0 : }
302 : :
303 : 0 : DynSock::DynSock(std::shared_ptr<Pipes> pipes)
304 [ # # ]: 0 : : m_pipes{pipes}, m_accept_sockets{}
305 : : {
306 : 0 : }
307 : :
308 : 0 : DynSock::~DynSock()
309 : : {
310 : 0 : m_pipes->send.Eof();
311 [ # # ]: 0 : }
312 : :
313 : 0 : ssize_t DynSock::Recv(void* buf, size_t len, int flags) const
314 : : {
315 : 0 : return m_pipes->recv.GetBytes(buf, len, flags);
316 : : }
317 : :
318 : 0 : ssize_t DynSock::Send(const void* buf, size_t len, int) const
319 : : {
320 : 0 : m_pipes->send.PushBytes(buf, len);
321 : 0 : return len;
322 : : }
323 : :
324 : 0 : std::unique_ptr<Sock> DynSock::Accept(sockaddr* addr, socklen_t* addr_len) const
325 : : {
326 [ # # ]: 0 : assert(m_accept_sockets && "Accept() called on non-listening DynSock");
327 : 0 : ZeroSock::Accept(addr, addr_len);
328 [ # # ]: 0 : return m_accept_sockets->Pop().value_or(nullptr);
329 : : }
330 : :
331 : 0 : bool DynSock::Wait(std::chrono::milliseconds timeout,
332 : : Event requested,
333 : : Event* occurred) const
334 : : {
335 [ # # ]: 0 : EventsPerSock ev;
336 [ # # ]: 0 : ev.emplace(this, Events{requested});
337 [ # # ]: 0 : const bool ret{WaitMany(timeout, ev)};
338 [ # # ]: 0 : if (occurred != nullptr) {
339 : 0 : *occurred = ev.begin()->second.occurred;
340 : : }
341 : 0 : return ret;
342 : 0 : }
343 : :
344 : 0 : bool DynSock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const
345 : : {
346 : 0 : const auto deadline = std::chrono::steady_clock::now() + timeout;
347 : 0 : bool at_least_one_event_occurred{false};
348 : :
349 : 0 : for (;;) {
350 : : // Check all sockets for readiness without waiting.
351 [ # # # # ]: 0 : for (auto& [sock, events] : events_per_sock) {
352 [ # # ]: 0 : if ((events.requested & Sock::SendEvent) != 0) {
353 : : // Always ready for Send().
354 : 0 : events.occurred |= Sock::SendEvent;
355 : 0 : at_least_one_event_occurred = true;
356 : : }
357 : :
358 [ # # ]: 0 : if ((events.requested & Sock::RecvEvent) != 0) {
359 : 0 : auto dyn_sock = reinterpret_cast<const DynSock*>(sock.get());
360 : 0 : uint8_t b;
361 [ # # # # : 0 : if (dyn_sock->m_pipes->recv.GetBytes(&b, 1, MSG_PEEK) == 1 || (dyn_sock->m_accept_sockets && !dyn_sock->m_accept_sockets->Empty())) {
# # ]
362 : 0 : events.occurred |= Sock::RecvEvent;
363 : 0 : at_least_one_event_occurred = true;
364 : : }
365 : : }
366 : : }
367 : :
368 [ # # # # ]: 0 : if (at_least_one_event_occurred || std::chrono::steady_clock::now() > deadline) {
369 : : break;
370 : : }
371 : :
372 : 0 : std::this_thread::sleep_for(10ms);
373 : 0 : }
374 : :
375 : 0 : return true;
376 : : }
377 : :
378 : 0 : DynSock& DynSock::operator=(Sock&&)
379 : : {
380 : 0 : AssertUnreachable(); // Move of Sock into DynSock not allowed.
381 : : }
|