Bitcoin Core 28.99.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 <net.h>
10#include <net_permissions.h>
11#include <net_processing.h>
12#include <netaddress.h>
14#include <node/eviction.h>
15#include <span.h>
16#include <sync.h>
17#include <util/sock.h>
18
19#include <algorithm>
20#include <array>
21#include <cassert>
22#include <chrono>
23#include <cstdint>
24#include <cstring>
25#include <memory>
26#include <string>
27#include <unordered_map>
28#include <vector>
29
31
32struct ConnmanTestMsg : public CConnman {
34
36 {
37 m_msgproc = msgproc;
38 }
39
40 void SetPeerConnectTimeout(std::chrono::seconds timeout)
41 {
42 m_peer_connect_timeout = timeout;
43 }
44
45 std::vector<CNode*> TestNodes()
46 {
48 return m_nodes;
49 }
50
52 {
54 m_nodes.push_back(&node);
55
56 if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];
57 }
58
60 {
62 for (CNode* node : m_nodes) {
63 delete node;
64 }
65 m_nodes.clear();
66 }
67
68 void Handshake(CNode& node,
69 bool successfully_connected,
70 ServiceFlags remote_services,
71 ServiceFlags local_services,
72 int32_t version,
73 bool relay_txs)
75
77 {
78 return m_msgproc->ProcessMessages(&node, flagInterruptMsgProc);
79 }
80
81 void NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const;
82
83 bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;
84 void FlushSendBuffer(CNode& node) const;
85
86 bool AlreadyConnectedPublic(const CAddress& addr) { return AlreadyConnectedToAddress(addr); };
87
88 CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)
90};
91
100};
101
113};
114
122};
123
124constexpr auto ALL_NETWORKS = std::array{
132};
133
140{
141public:
142 explicit StaticContentsSock(const std::string& contents)
144 m_contents{contents}
145 {
146 }
147
149
151 {
152 assert(false && "Move of Sock into MockSock not allowed.");
153 return *this;
154 }
155
156 ssize_t Send(const void*, size_t len, int) const override { return len; }
157
158 ssize_t Recv(void* buf, size_t len, int flags) const override
159 {
160 const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)};
161 std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes);
162 if ((flags & MSG_PEEK) == 0) {
163 m_consumed += consume_bytes;
164 }
165 return consume_bytes;
166 }
167
168 int Connect(const sockaddr*, socklen_t) const override { return 0; }
169
170 int Bind(const sockaddr*, socklen_t) const override { return 0; }
171
172 int Listen(int) const override { return 0; }
173
174 std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override
175 {
176 if (addr != nullptr) {
177 // Pretend all connections come from 5.5.5.5:6789
178 memset(addr, 0x00, *addr_len);
179 const socklen_t write_len = static_cast<socklen_t>(sizeof(sockaddr_in));
180 if (*addr_len >= write_len) {
181 *addr_len = write_len;
182 sockaddr_in* addr_in = reinterpret_cast<sockaddr_in*>(addr);
183 addr_in->sin_family = AF_INET;
184 memset(&addr_in->sin_addr, 0x05, sizeof(addr_in->sin_addr));
185 addr_in->sin_port = htons(6789);
186 }
187 }
188 return std::make_unique<StaticContentsSock>("");
189 };
190
191 int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override
192 {
193 std::memset(opt_val, 0x0, *opt_len);
194 return 0;
195 }
196
197 int SetSockOpt(int, int, const void*, socklen_t) const override { return 0; }
198
199 int GetSockName(sockaddr* name, socklen_t* name_len) const override
200 {
201 std::memset(name, 0x0, *name_len);
202 return 0;
203 }
204
205 bool SetNonBlocking() const override { return true; }
206
207 bool IsSelectable() const override { return true; }
208
209 bool Wait(std::chrono::milliseconds timeout,
210 Event requested,
211 Event* occurred = nullptr) const override
212 {
213 if (occurred != nullptr) {
214 *occurred = requested;
215 }
216 return true;
217 }
218
219 bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override
220 {
221 for (auto& [sock, events] : events_per_sock) {
222 (void)sock;
223 events.occurred = events.requested;
224 }
225 return true;
226 }
227
228 bool IsConnected(std::string&) const override
229 {
230 return true;
231 }
232
233private:
234 const std::string m_contents;
235 mutable size_t m_consumed{0};
236};
237
238std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
239
240#endif // BITCOIN_TEST_UTIL_NET_H
int flags
Definition: bitcoin-tx.cpp:536
A CService with information about it as peer.
Definition: protocol.h:367
Definition: net.h:1052
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
Definition: net.cpp:364
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams &params, bool network_active=true)
Definition: net.cpp:3179
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1541
m_peer_connect_timeout
Definition: net.h:1099
RecursiveMutex m_nodes_mutex
Definition: net.h:1447
m_msgproc
Definition: net.h:1096
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
Definition: net.h:1597
Information about a peer.
Definition: net.h:673
Fast randomness source.
Definition: random.h:377
Interface for message handling.
Definition: net.h:1008
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:1011
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:27
SOCKET m_socket
Contained socket.
Definition: sock.h:275
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 Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
A mocked Sock alternative that returns a statically contained data upon read and succeeds and ignores...
Definition: net.h:140
int SetSockOpt(int, int, const void *, socklen_t) const override
setsockopt(2) wrapper.
Definition: net.h:197
bool IsSelectable() const override
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition: net.h:207
bool IsConnected(std::string &) const override
Check if still connected.
Definition: net.h:228
bool SetNonBlocking() const override
Set the non-blocking option on the socket.
Definition: net.h:205
bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const override
Wait for readiness for input (recv) or output (send).
Definition: net.h:209
int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const override
getsockopt(2) wrapper.
Definition: net.h:191
int Connect(const sockaddr *, socklen_t) const override
connect(2) wrapper.
Definition: net.h:168
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.h:219
size_t m_consumed
Definition: net.h:235
const std::string m_contents
Definition: net.h:234
ssize_t Send(const void *, size_t len, int) const override
send(2) wrapper.
Definition: net.h:156
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.h:174
int Bind(const sockaddr *, socklen_t) const override
bind(2) wrapper.
Definition: net.h:170
StaticContentsSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.h:150
int GetSockName(sockaddr *name, socklen_t *name_len) const override
getsockname(2) wrapper.
Definition: net.h:199
int Listen(int) const override
listen(2) wrapper.
Definition: net.h:172
~StaticContentsSock() override
Definition: net.h:148
StaticContentsSock(const std::string &contents)
Definition: net.h:142
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.h:158
#define INVALID_SOCKET
Definition: compat.h:56
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.
Definition: messages.h:20
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:49
bool ReceiveMsgFrom(CNode &node, CSerializedNetMsg &&ser_msg) const
Definition: net.cpp:91
CNode * ConnectNodePublic(PeerManager &peerman, const char *pszDest, ConnectionType conn_type) EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex)
Definition: net.cpp:105
void ClearTestNodes()
Definition: net.h:59
bool AlreadyConnectedPublic(const CAddress &addr)
Definition: net.h:86
void NodeReceiveMsgBytes(CNode &node, Span< const uint8_t > msg_bytes, bool &complete) const
Definition: net.cpp:71
void SetMsgProc(NetEventsInterface *msgproc)
Definition: net.h:35
void AddTestNode(CNode &node)
Definition: net.h:51
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:76
std::vector< CNode * > TestNodes()
Definition: net.h:45
void FlushSendBuffer(CNode &node) const
Definition: net.cpp:79
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:40
#define LOCK(cs)
Definition: sync.h:257
std::vector< NodeEvictionCandidate > GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext &random_context)
Definition: net.cpp:116
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:92
constexpr ConnectionType ALL_CONNECTION_TYPES[]
Definition: net.h:115
constexpr auto ALL_NETWORKS
Definition: net.h:124
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]
Definition: net.h:102
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
assert(!tx.IsCoinBase())