Bitcoin Core  25.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 <node/eviction.h>
10 #include <netaddress.h>
11 #include <net.h>
12 #include <util/sock.h>
13 
14 #include <array>
15 #include <cassert>
16 #include <cstring>
17 #include <memory>
18 #include <string>
19 
20 struct ConnmanTestMsg : public CConnman {
21  using CConnman::CConnman;
22 
23  void SetPeerConnectTimeout(std::chrono::seconds timeout)
24  {
25  m_peer_connect_timeout = timeout;
26  }
27 
29  {
31  m_nodes.push_back(&node);
32  }
34  {
36  for (CNode* node : m_nodes) {
37  delete node;
38  }
39  m_nodes.clear();
40  }
41 
42  void Handshake(CNode& node,
43  bool successfully_connected,
44  ServiceFlags remote_services,
45  ServiceFlags local_services,
46  int32_t version,
47  bool relay_txs)
49 
51 
52  void NodeReceiveMsgBytes(CNode& node, Span<const uint8_t> msg_bytes, bool& complete) const;
53 
54  bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg& ser_msg) const;
55 };
56 
58  NODE_NONE,
60  NODE_BLOOM,
64 };
65 
77 };
78 
86 };
87 
88 constexpr auto ALL_NETWORKS = std::array{
96 };
97 
103 class StaticContentsSock : public Sock
104 {
105 public:
106  explicit StaticContentsSock(const std::string& contents) : m_contents{contents}
107  {
108  // Just a dummy number that is not INVALID_SOCKET.
109  m_socket = INVALID_SOCKET - 1;
110  }
111 
113 
114  StaticContentsSock& operator=(Sock&& other) override
115  {
116  assert(false && "Move of Sock into MockSock not allowed.");
117  return *this;
118  }
119 
120  ssize_t Send(const void*, size_t len, int) const override { return len; }
121 
122  ssize_t Recv(void* buf, size_t len, int flags) const override
123  {
124  const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)};
125  std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes);
126  if ((flags & MSG_PEEK) == 0) {
127  m_consumed += consume_bytes;
128  }
129  return consume_bytes;
130  }
131 
132  int Connect(const sockaddr*, socklen_t) const override { return 0; }
133 
134  int Bind(const sockaddr*, socklen_t) const override { return 0; }
135 
136  int Listen(int) const override { return 0; }
137 
138  std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override
139  {
140  if (addr != nullptr) {
141  // Pretend all connections come from 5.5.5.5:6789
142  memset(addr, 0x00, *addr_len);
143  const socklen_t write_len = static_cast<socklen_t>(sizeof(sockaddr_in));
144  if (*addr_len >= write_len) {
145  *addr_len = write_len;
146  sockaddr_in* addr_in = reinterpret_cast<sockaddr_in*>(addr);
147  addr_in->sin_family = AF_INET;
148  memset(&addr_in->sin_addr, 0x05, sizeof(addr_in->sin_addr));
149  addr_in->sin_port = htons(6789);
150  }
151  }
152  return std::make_unique<StaticContentsSock>("");
153  };
154 
155  int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override
156  {
157  std::memset(opt_val, 0x0, *opt_len);
158  return 0;
159  }
160 
161  int SetSockOpt(int, int, const void*, socklen_t) const override { return 0; }
162 
163  int GetSockName(sockaddr* name, socklen_t* name_len) const override
164  {
165  std::memset(name, 0x0, *name_len);
166  return 0;
167  }
168 
169  bool SetNonBlocking() const override { return true; }
170 
171  bool IsSelectable() const override { return true; }
172 
173  bool Wait(std::chrono::milliseconds timeout,
174  Event requested,
175  Event* occurred = nullptr) const override
176  {
177  if (occurred != nullptr) {
178  *occurred = requested;
179  }
180  return true;
181  }
182 
183  bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override
184  {
185  for (auto& [sock, events] : events_per_sock) {
186  (void)sock;
187  events.occurred = events.requested;
188  }
189  return true;
190  }
191 
192 private:
193  const std::string m_contents;
194  mutable size_t m_consumed{0};
195 };
196 
197 std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext& random_context);
198 
199 #endif // BITCOIN_TEST_UTIL_NET_H
int flags
Definition: bitcoin-tx.cpp:528
Definition: net.h:696
std::atomic< bool > flagInterruptMsgProc
Definition: net.h:1124
m_peer_connect_timeout
Definition: net.h:745
RecursiveMutex m_nodes_mutex
Definition: net.h:1047
m_msgproc
Definition: net.h:742
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, bool network_active=true)
Definition: net.cpp:2253
Information about a peer.
Definition: net.h:360
Fast randomness source.
Definition: random.h:144
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
Definition: net.h:661
RAII helper class that manages a socket.
Definition: sock.h:28
SOCKET m_socket
Contained socket.
Definition: sock.h:273
uint8_t Event
Definition: sock.h:148
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:218
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
A mocked Sock alternative that returns a statically contained data upon read and succeeds and ignores...
Definition: net.h:104
int SetSockOpt(int, int, const void *, socklen_t) const override
setsockopt(2) wrapper.
Definition: net.h:161
bool IsSelectable() const override
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition: net.h:171
bool SetNonBlocking() const override
Set the non-blocking option on the socket.
Definition: net.h:169
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:173
int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const override
getsockopt(2) wrapper.
Definition: net.h:155
int Connect(const sockaddr *, socklen_t) const override
connect(2) wrapper.
Definition: net.h:132
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:183
size_t m_consumed
Definition: net.h:194
const std::string m_contents
Definition: net.h:193
ssize_t Send(const void *, size_t len, int) const override
send(2) wrapper.
Definition: net.h:120
int Bind(const sockaddr *, socklen_t) const override
bind(2) wrapper.
Definition: net.h:134
int GetSockName(sockaddr *name, socklen_t *name_len) const override
getsockname(2) wrapper.
Definition: net.h:163
int Listen(int) const override
listen(2) wrapper.
Definition: net.h:136
StaticContentsSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: net.h:114
~StaticContentsSock() override
Definition: net.h:112
StaticContentsSock(const std::string &contents)
Definition: net.h:106
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: net.h:122
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: net.h:138
#define INVALID_SOCKET
Definition: compat.h:54
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: init.h:25
NetPermissionFlags
@ NET_I2P
I2P.
Definition: netaddress.h:58
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:61
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
@ NET_IPV6
IPv6.
Definition: netaddress.h:52
@ NET_IPV4
IPv4.
Definition: netaddress.h:49
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
ServiceFlags
nServices flags
Definition: protocol.h:274
@ NODE_NONE
Definition: protocol.h:277
@ NODE_WITNESS
Definition: protocol.h:285
@ NODE_NETWORK_LIMITED
Definition: protocol.h:292
@ NODE_BLOOM
Definition: protocol.h:282
@ NODE_NETWORK
Definition: protocol.h:280
@ NODE_COMPACT_FILTERS
Definition: protocol.h:288
const char * name
Definition: rest.cpp:45
bool ReceiveMsgFrom(CNode &node, CSerializedNetMsg &ser_msg) const
Definition: net.cpp:73
void ClearTestNodes()
Definition: net.h:33
void NodeReceiveMsgBytes(CNode &node, Span< const uint8_t > msg_bytes, bool &complete) const
Definition: net.cpp:65
void Handshake(CNode &node, bool successfully_connected, ServiceFlags remote_services, ServiceFlags local_services, int32_t version, bool relay_txs) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface void ProcessMessagesOnce(CNode &node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface
Definition: net.h:50
void AddTestNode(CNode &node)
Definition: net.h:28
void SetPeerConnectTimeout(std::chrono::seconds timeout)
Definition: net.h:23
#define LOCK(cs)
Definition: sync.h:258
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:57
constexpr ConnectionType ALL_CONNECTION_TYPES[]
Definition: net.h:79
constexpr auto ALL_NETWORKS
Definition: net.h:88
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]
Definition: net.h:66
std::vector< NodeEvictionCandidate > GetRandomNodeEvictionCandidates(int n_candidates, FastRandomContext &random_context)
Definition: net.cpp:84
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
assert(!tx.IsCoinBase())