p2p_addr_relay.py raw
1 #!/usr/bin/env python3
2 # Copyright (c) 2020-2021 The Limenka developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """
6 Test addr relay
7 """
8
9 import random
10 import time
11
12 from test_framework.messages import (
13 CAddress,
14 NODE_REDUCED_DATA,
15 NODE_NETWORK,
16 NODE_WITNESS,
17 msg_addr,
18 msg_getaddr,
19 msg_verack,
20 )
21 from test_framework.p2p import (
22 P2PInterface,
23 p2p_lock,
24 P2P_SERVICES,
25 )
26 from test_framework.test_framework import LimenkaTestFramework
27 from test_framework.util import (
28 assert_equal,
29 assert_greater_than,
30 assert_greater_than_or_equal
31 )
32
33 ONE_MINUTE = 60
34 TEN_MINUTES = 10 * ONE_MINUTE
35 ONE_HOUR = 60 * ONE_MINUTE
36 TWO_HOURS = 2 * ONE_HOUR
37 ONE_DAY = 24 * ONE_HOUR
38
39 ADDR_DESTINATIONS_THRESHOLD = 4
40
41 class AddrReceiver(P2PInterface):
42 num_ipv4_received = 0
43 test_addr_contents = False
44 _tokens = 1
45 send_getaddr = True
46
47 def __init__(self, test_addr_contents=False, send_getaddr=True):
48 super().__init__()
49 self.test_addr_contents = test_addr_contents
50 self.send_getaddr = send_getaddr
51
52 def on_addr(self, message):
53 for addr in message.addrs:
54 self.num_ipv4_received += 1
55 if self.test_addr_contents:
56 # relay_tests checks the content of the addr messages match
57 # expectations based on the message creation in setup_addr_msg
58 assert_equal(addr.nServices, NODE_NETWORK | NODE_WITNESS | NODE_REDUCED_DATA)
59 if not 8333 <= addr.port < 8343:
60 raise AssertionError("Invalid addr.port of {} (8333-8342 expected)".format(addr.port))
61 assert addr.ip.startswith('123.123.')
62
63 def on_getaddr(self, message):
64 # When the node sends us a getaddr, it increments the addr relay tokens for the connection by 1000
65 self._tokens += 1000
66
67 @property
68 def tokens(self):
69 with p2p_lock:
70 return self._tokens
71
72 def increment_tokens(self, n):
73 # When we move mocktime forward, the node increments the addr relay tokens for its peers
74 with p2p_lock:
75 self._tokens += n
76
77 def addr_received(self):
78 return self.num_ipv4_received != 0
79
80 def on_version(self, message):
81 self.send_version()
82 self.send_message(msg_verack())
83 if (self.send_getaddr):
84 self.send_message(msg_getaddr())
85
86 def getaddr_received(self):
87 return self.message_count['getaddr'] > 0
88
89
90 class AddrTest(LimenkaTestFramework):
91 counter = 0
92 mocktime = int(time.time())
93
94 def set_test_params(self):
95 self.num_nodes = 1
96 self.extra_args = [["-whitelist=addr@127.0.0.1"]]
97
98 def run_test(self):
99 self.oversized_addr_test()
100 self.relay_tests()
101 self.inbound_blackhole_tests()
102
103 self.destination_rotates_once_in_24_hours_test()
104 self.destination_rotates_more_than_once_over_several_days_test()
105
106 # This test populates the addrman, which can impact the node's behavior
107 # in subsequent tests
108 self.getaddr_tests()
109 self.blocksonly_mode_tests()
110 self.rate_limit_tests()
111
112 def setup_addr_msg(self, num, sequential_ips=True):
113 addrs = []
114 for i in range(num):
115 addr = CAddress()
116 addr.time = self.mocktime + random.randrange(-100, 100)
117 addr.nServices = P2P_SERVICES
118 if sequential_ips:
119 assert self.counter < 256 ** 2 # Don't allow the returned ip addresses to wrap.
120 addr.ip = f"123.123.{self.counter // 256}.{self.counter % 256}"
121 self.counter += 1
122 else:
123 addr.ip = f"{random.randrange(128,169)}.{random.randrange(1,255)}.{random.randrange(1,255)}.{random.randrange(1,255)}"
124 addr.port = 8333 + i
125 addrs.append(addr)
126
127 msg = msg_addr()
128 msg.addrs = addrs
129 return msg
130
131 def send_addr_msg(self, source, msg, receivers):
132 source.send_and_ping(msg)
133 # invoke m_next_addr_send timer:
134 # `addr` messages are sent on an exponential distribution with mean interval of 30s.
135 # Setting the mocktime 600s forward gives a probability of (1 - e^-(600/30)) that
136 # the event will occur (i.e. this fails once in ~500 million repeats).
137 self.mocktime += 10 * 60
138 self.nodes[0].setmocktime(self.mocktime)
139 for peer in receivers:
140 peer.sync_with_ping()
141
142 def oversized_addr_test(self):
143 self.log.info('Send an addr message that is too large')
144 addr_source = self.nodes[0].add_p2p_connection(P2PInterface())
145
146 msg = self.setup_addr_msg(1010)
147 with self.nodes[0].assert_debug_log(['addr message size = 1010']):
148 addr_source.send_message(msg)
149 addr_source.wait_for_disconnect()
150
151 self.nodes[0].disconnect_p2ps()
152
153 def relay_tests(self):
154 self.log.info('Test address relay')
155 self.log.info('Check that addr message content is relayed and added to addrman')
156 addr_source = self.nodes[0].add_p2p_connection(P2PInterface())
157 num_receivers = 7
158 receivers = []
159 for _ in range(num_receivers):
160 receivers.append(self.nodes[0].add_p2p_connection(AddrReceiver(test_addr_contents=True)))
161
162 # Keep this with length <= 10. Addresses from larger messages are not
163 # relayed.
164 num_ipv4_addrs = 10
165 msg = self.setup_addr_msg(num_ipv4_addrs)
166 with self.nodes[0].assert_debug_log(
167 [
168 'received: addr (301 bytes) peer=1',
169 ]
170 ):
171 self.send_addr_msg(addr_source, msg, receivers)
172
173 total_ipv4_received = sum(r.num_ipv4_received for r in receivers)
174
175 # Every IPv4 address must be relayed to two peers, other than the
176 # originating node (addr_source).
177 ipv4_branching_factor = 2
178 assert_equal(total_ipv4_received, num_ipv4_addrs * ipv4_branching_factor)
179
180 self.nodes[0].disconnect_p2ps()
181
182 self.log.info('Check relay of addresses received from outbound peers')
183 inbound_peer = self.nodes[0].add_p2p_connection(AddrReceiver(test_addr_contents=True, send_getaddr=False))
184 full_outbound_peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay")
185 msg = self.setup_addr_msg(2)
186 self.send_addr_msg(full_outbound_peer, msg, [inbound_peer])
187 self.log.info('Check that the first addr message received from an outbound peer is not relayed')
188 # Currently, there is a flag that prevents the first addr message received
189 # from a new outbound peer to be relayed to others. Originally meant to prevent
190 # large GETADDR responses from being relayed, it now typically affects the self-announcement
191 # of the outbound peer which is often sent before the GETADDR response.
192 assert_equal(inbound_peer.num_ipv4_received, 0)
193
194 # Send an empty ADDR message to initialize address relay on this connection.
195 inbound_peer.send_and_ping(msg_addr())
196
197 self.log.info('Check that subsequent addr messages sent from an outbound peer are relayed')
198 msg2 = self.setup_addr_msg(2)
199 self.send_addr_msg(full_outbound_peer, msg2, [inbound_peer])
200 assert_equal(inbound_peer.num_ipv4_received, 2)
201
202 self.log.info('Check address relay to outbound peers')
203 block_relay_peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=1, connection_type="block-relay-only")
204 msg3 = self.setup_addr_msg(2)
205 self.send_addr_msg(inbound_peer, msg3, [full_outbound_peer, block_relay_peer])
206
207 self.log.info('Check that addresses are relayed to full outbound peers')
208 assert_equal(full_outbound_peer.num_ipv4_received, 2)
209 self.log.info('Check that addresses are not relayed to block-relay-only outbound peers')
210 assert_equal(block_relay_peer.num_ipv4_received, 0)
211
212 self.nodes[0].disconnect_p2ps()
213
214 def sum_addr_messages(self, msgs_dict):
215 return sum(bytes_received for (msg, bytes_received) in msgs_dict.items() if msg in ['addr', 'addrv2', 'getaddr'])
216
217 def inbound_blackhole_tests(self):
218 self.log.info('Check that we only relay addresses to inbound peers who have previously sent us addr related messages')
219
220 addr_source = self.nodes[0].add_p2p_connection(P2PInterface())
221 receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver())
222 blackhole_peer = self.nodes[0].add_p2p_connection(AddrReceiver(send_getaddr=False))
223 initial_addrs_received = receiver_peer.num_ipv4_received
224
225 peerinfo = self.nodes[0].getpeerinfo()
226 assert_equal(peerinfo[0]['addr_relay_enabled'], True) # addr_source
227 assert_equal(peerinfo[1]['addr_relay_enabled'], True) # receiver_peer
228 assert_equal(peerinfo[2]['addr_relay_enabled'], False) # blackhole_peer
229
230 # addr_source sends 2 addresses to node0
231 msg = self.setup_addr_msg(2)
232 addr_source.send_and_ping(msg)
233 self.mocktime += 30 * 60
234 self.nodes[0].setmocktime(self.mocktime)
235 receiver_peer.sync_with_ping()
236 blackhole_peer.sync_with_ping()
237
238 peerinfo = self.nodes[0].getpeerinfo()
239
240 # Confirm node received addr-related messages from receiver peer
241 assert_greater_than(self.sum_addr_messages(peerinfo[1]['bytesrecv_per_msg']), 0)
242 # And that peer received addresses
243 assert_equal(receiver_peer.num_ipv4_received - initial_addrs_received, 2)
244
245 # Confirm node has not received addr-related messages from blackhole peer
246 assert_equal(self.sum_addr_messages(peerinfo[2]['bytesrecv_per_msg']), 0)
247 # And that peer did not receive addresses
248 assert_equal(blackhole_peer.num_ipv4_received, 0)
249
250 self.log.info("After blackhole peer sends addr message, it becomes eligible for addr gossip")
251 blackhole_peer.send_and_ping(msg_addr())
252
253 # Confirm node has now received addr-related messages from blackhole peer
254 assert_greater_than(self.sum_addr_messages(peerinfo[1]['bytesrecv_per_msg']), 0)
255 assert_equal(self.nodes[0].getpeerinfo()[2]['addr_relay_enabled'], True)
256
257 msg = self.setup_addr_msg(2)
258 self.send_addr_msg(addr_source, msg, [receiver_peer, blackhole_peer])
259
260 # And that peer received addresses
261 assert_equal(blackhole_peer.num_ipv4_received, 2)
262
263 self.nodes[0].disconnect_p2ps()
264
265 def getaddr_tests(self):
266 # In the previous tests, the node answered GETADDR requests with an
267 # empty addrman. Due to GETADDR response caching (see
268 # CConnman::GetAddresses), the node would continue to provide 0 addrs
269 # in response until enough time has passed or the node is restarted.
270 self.restart_node(0)
271
272 self.log.info('Test getaddr behavior')
273 self.log.info('Check that we send a getaddr message upon connecting to an outbound-full-relay peer')
274 full_outbound_peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay")
275 full_outbound_peer.sync_with_ping()
276 assert full_outbound_peer.getaddr_received()
277
278 self.log.info('Check that we do not send a getaddr message to a block-relay-only or inbound peer')
279 block_relay_peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=1, connection_type="block-relay-only")
280 block_relay_peer.sync_with_ping()
281 assert_equal(block_relay_peer.getaddr_received(), False)
282
283 inbound_peer = self.nodes[0].add_p2p_connection(AddrReceiver(send_getaddr=False))
284 inbound_peer.sync_with_ping()
285 assert_equal(inbound_peer.getaddr_received(), False)
286
287 self.log.info('Check that we answer getaddr messages only from inbound peers')
288 # Add some addresses to addrman
289 for i in range(1000):
290 first_octet = i >> 8
291 second_octet = i % 256
292 a = f"{first_octet}.{second_octet}.1.1"
293 self.nodes[0].addpeeraddress(a, 8333)
294
295 full_outbound_peer.send_and_ping(msg_getaddr())
296 block_relay_peer.send_and_ping(msg_getaddr())
297 inbound_peer.send_and_ping(msg_getaddr())
298
299 # invoke m_next_addr_send timer, see under send_addr_msg() function for rationale
300 self.mocktime += 10 * 60
301 self.nodes[0].setmocktime(self.mocktime)
302 inbound_peer.wait_until(lambda: inbound_peer.addr_received() is True)
303
304 assert_equal(full_outbound_peer.num_ipv4_received, 0)
305 assert_equal(block_relay_peer.num_ipv4_received, 0)
306 assert inbound_peer.num_ipv4_received > 100
307
308 self.log.info('Check that we answer getaddr messages only once per connection')
309 received_addrs_before = inbound_peer.num_ipv4_received
310 with self.nodes[0].assert_debug_log(['Ignoring repeated "getaddr".']):
311 inbound_peer.send_and_ping(msg_getaddr())
312 self.mocktime += 10 * 60
313 self.nodes[0].setmocktime(self.mocktime)
314 inbound_peer.sync_with_ping()
315 received_addrs_after = inbound_peer.num_ipv4_received
316 assert_equal(received_addrs_before, received_addrs_after)
317
318 self.nodes[0].disconnect_p2ps()
319
320 def blocksonly_mode_tests(self):
321 self.log.info('Test addr relay in -blocksonly mode')
322 self.restart_node(0, ["-blocksonly", "-whitelist=addr@127.0.0.1"])
323 self.mocktime = int(time.time())
324
325 self.log.info('Check that we send getaddr messages')
326 full_outbound_peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=0, connection_type="outbound-full-relay")
327 full_outbound_peer.sync_with_ping()
328 assert full_outbound_peer.getaddr_received()
329
330 self.log.info('Check that we relay address messages')
331 addr_source = self.nodes[0].add_p2p_connection(P2PInterface())
332 msg = self.setup_addr_msg(2)
333 self.send_addr_msg(addr_source, msg, [full_outbound_peer])
334 assert_equal(full_outbound_peer.num_ipv4_received, 2)
335
336 self.nodes[0].disconnect_p2ps()
337
338 def send_addrs_and_test_rate_limiting(self, peer, no_relay, *, new_addrs, total_addrs):
339 """Send an addr message and check that the number of addresses processed and rate-limited is as expected"""
340
341 peer.send_and_ping(self.setup_addr_msg(new_addrs, sequential_ips=False))
342
343 peerinfo = self.nodes[0].getpeerinfo()[0]
344 addrs_processed = peerinfo['addr_processed']
345 addrs_rate_limited = peerinfo['addr_rate_limited']
346 self.log.debug(f"addrs_processed = {addrs_processed}, addrs_rate_limited = {addrs_rate_limited}")
347
348 if no_relay:
349 assert_equal(addrs_processed, 0)
350 assert_equal(addrs_rate_limited, 0)
351 else:
352 assert_equal(addrs_processed, min(total_addrs, peer.tokens))
353 assert_equal(addrs_rate_limited, max(0, total_addrs - peer.tokens))
354
355 def rate_limit_tests(self):
356 self.mocktime = int(time.time())
357 self.restart_node(0, [])
358 self.nodes[0].setmocktime(self.mocktime)
359
360 for conn_type, no_relay in [("outbound-full-relay", False), ("block-relay-only", True), ("inbound", False)]:
361 self.log.info(f'Test rate limiting of addr processing for {conn_type} peers')
362 if conn_type == "inbound":
363 peer = self.nodes[0].add_p2p_connection(AddrReceiver())
364 else:
365 peer = self.nodes[0].add_outbound_p2p_connection(AddrReceiver(), p2p_idx=0, connection_type=conn_type)
366
367 # Send 600 addresses. For all but the block-relay-only peer this should result in addresses being processed.
368 self.send_addrs_and_test_rate_limiting(peer, no_relay, new_addrs=600, total_addrs=600)
369
370 # Send 600 more addresses. For the outbound-full-relay peer (which we send a GETADDR, and thus will
371 # process up to 1001 incoming addresses), this means more addresses will be processed.
372 self.send_addrs_and_test_rate_limiting(peer, no_relay, new_addrs=600, total_addrs=1200)
373
374 # Send 10 more. As we reached the processing limit for all nodes, no more addresses should be procesesd.
375 self.send_addrs_and_test_rate_limiting(peer, no_relay, new_addrs=10, total_addrs=1210)
376
377 # Advance the time by 100 seconds, permitting the processing of 10 more addresses.
378 # Send 200 and verify that 10 are processed.
379 self.mocktime += 100
380 self.nodes[0].setmocktime(self.mocktime)
381 peer.increment_tokens(10)
382
383 self.send_addrs_and_test_rate_limiting(peer, no_relay, new_addrs=200, total_addrs=1410)
384
385 # Advance the time by 1000 seconds, permitting the processing of 100 more addresses.
386 # Send 200 and verify that 100 are processed.
387 self.mocktime += 1000
388 self.nodes[0].setmocktime(self.mocktime)
389 peer.increment_tokens(100)
390
391 self.send_addrs_and_test_rate_limiting(peer, no_relay, new_addrs=200, total_addrs=1610)
392
393 self.nodes[0].disconnect_p2ps()
394
395 def get_nodes_that_received_addr(self, peer, receiver_peer, addr_receivers,
396 time_interval_1, time_interval_2):
397
398 # Clean addr response related to the initial getaddr. There is no way to avoid initial
399 # getaddr because the peer won't self-announce then.
400 for addr_receiver in addr_receivers:
401 addr_receiver.num_ipv4_received = 0
402
403 for _ in range(10):
404 self.mocktime += time_interval_1
405 self.msg.addrs[0].time = self.mocktime + TEN_MINUTES
406 self.nodes[0].setmocktime(self.mocktime)
407 with self.nodes[0].assert_debug_log(['received: addr (31 bytes) peer=0']):
408 peer.send_and_ping(self.msg)
409 self.mocktime += time_interval_2
410 self.nodes[0].setmocktime(self.mocktime)
411 receiver_peer.sync_with_ping()
412 return [node for node in addr_receivers if node.addr_received()]
413
414 def destination_rotates_once_in_24_hours_test(self):
415 self.restart_node(0, [])
416
417 self.log.info('Test within 24 hours an addr relay destination is rotated at most once')
418 self.mocktime = int(time.time())
419 self.msg = self.setup_addr_msg(1)
420 self.addr_receivers = []
421 peer = self.nodes[0].add_p2p_connection(P2PInterface())
422 receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver())
423 addr_receivers = [self.nodes[0].add_p2p_connection(AddrReceiver()) for _ in range(20)]
424 nodes_received_addr = self.get_nodes_that_received_addr(peer, receiver_peer, addr_receivers, 0, TWO_HOURS) # 10 intervals of 2 hours
425 # Per RelayAddress, we would announce these addrs to 2 destinations per day.
426 # Since it's at most one rotation, at most 4 nodes can receive ADDR.
427 assert_greater_than_or_equal(ADDR_DESTINATIONS_THRESHOLD, len(nodes_received_addr))
428 self.nodes[0].disconnect_p2ps()
429
430 def destination_rotates_more_than_once_over_several_days_test(self):
431 self.restart_node(0, [])
432
433 self.log.info('Test after several days an addr relay destination is rotated more than once')
434 self.msg = self.setup_addr_msg(1)
435 peer = self.nodes[0].add_p2p_connection(P2PInterface())
436 receiver_peer = self.nodes[0].add_p2p_connection(AddrReceiver())
437 addr_receivers = [self.nodes[0].add_p2p_connection(AddrReceiver()) for _ in range(20)]
438 # 10 intervals of 1 day (+ 1 hour, which should be enough to cover 30-min Poisson in most cases)
439 nodes_received_addr = self.get_nodes_that_received_addr(peer, receiver_peer, addr_receivers, ONE_DAY, ONE_HOUR)
440 # Now that there should have been more than one rotation, more than
441 # ADDR_DESTINATIONS_THRESHOLD nodes should have received ADDR.
442 assert_greater_than(len(nodes_received_addr), ADDR_DESTINATIONS_THRESHOLD)
443 self.nodes[0].disconnect_p2ps()
444
445
446 if __name__ == '__main__':
447 AddrTest(__file__).main()
448