/ test / functional / rpc_net.py
rpc_net.py
  1  #!/usr/bin/env python3
  2  # Copyright (c) 2017-present The Bitcoin Core developers
  3  # Distributed under the MIT software license, see the accompanying
  4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5  """Test RPC calls related to net.
  6  
  7  Tests correspond to code in rpc/net.cpp.
  8  """
  9  
 10  from decimal import Decimal
 11  from itertools import product
 12  import platform
 13  import time
 14  
 15  import test_framework.messages
 16  from test_framework.p2p import (
 17      P2PInterface,
 18      P2P_SERVICES,
 19  )
 20  from test_framework.test_framework import BitcoinTestFramework
 21  from test_framework.util import (
 22      assert_approx,
 23      assert_equal,
 24      assert_greater_than,
 25      assert_raises_rpc_error,
 26      p2p_port,
 27  )
 28  from test_framework.wallet import MiniWallet
 29  
 30  
 31  def assert_net_servicesnames(servicesflag, servicenames):
 32      """Utility that checks if all flags are correctly decoded in
 33      `getpeerinfo` and `getnetworkinfo`.
 34  
 35      :param servicesflag: The services as an integer.
 36      :param servicenames: The list of decoded services names, as strings.
 37      """
 38      servicesflag_generated = 0
 39      for servicename in servicenames:
 40          servicesflag_generated |= getattr(test_framework.messages, 'NODE_' + servicename)
 41      assert servicesflag_generated == servicesflag
 42  
 43  
 44  def seed_addrman(node):
 45      """ Populate the addrman with addresses from different networks.
 46      Here 2 ipv4, 2 ipv6, 1 cjdns, 2 onion and 1 i2p addresses are added.
 47      """
 48      # These addresses currently don't collide with a deterministic addrman.
 49      # If the addrman positioning/bucketing is changed, these might collide
 50      # and adding them fails.
 51      success = { "success": True }
 52      assert_equal(node.addpeeraddress(address="1.2.3.4", tried=True, port=8333), success)
 53      assert_equal(node.addpeeraddress(address="2.0.0.0", port=8333), success)
 54      assert_equal(node.addpeeraddress(address="1233:3432:2434:2343:3234:2345:6546:4534", tried=True, port=8333), success)
 55      assert_equal(node.addpeeraddress(address="2803:0:1234:abcd::1", port=45324), success)
 56      assert_equal(node.addpeeraddress(address="fc00:1:2:3:4:5:6:7", port=8333), success)
 57      assert_equal(node.addpeeraddress(address="pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", tried=True, port=8333), success)
 58      assert_equal(node.addpeeraddress(address="nrfj6inpyf73gpkyool35hcmne5zwfmse3jl3aw23vk7chdemalyaqad.onion", port=45324, tried=True), success)
 59      assert_equal(node.addpeeraddress(address="c4gfnttsuwqomiygupdqqqyy5y5emnk5c73hrfvatri67prd7vyq.b32.i2p", port=8333), success)
 60  
 61  
 62  class NetTest(BitcoinTestFramework):
 63      def set_test_params(self):
 64          self.num_nodes = 2
 65          self.extra_args = [["-minrelaytxfee=0.00001000"], ["-minrelaytxfee=0.00000500"]]
 66          self.supports_cli = False
 67  
 68      def run_test(self):
 69          # We need miniwallet to make a transaction
 70          self.wallet = MiniWallet(self.nodes[0])
 71  
 72          # By default, the test framework sets up an addnode connection from
 73          # node 1 --> node0. By connecting node0 --> node 1, we're left with
 74          # the two nodes being connected both ways.
 75          # Topology will look like: node0 <--> node1
 76          self.connect_nodes(0, 1)
 77          self.sync_all()
 78  
 79          self.test_connection_count()
 80          self.test_getpeerinfo()
 81          self.test_getnettotals()
 82          self.test_getnetworkinfo()
 83          self.test_addnode_getaddednodeinfo()
 84          self.test_service_flags()
 85          self.test_getnodeaddresses()
 86          self.test_addpeeraddress()
 87          self.test_sendmsgtopeer()
 88          self.test_getaddrmaninfo()
 89          self.test_getrawaddrman()
 90  
 91      def test_connection_count(self):
 92          self.log.info("Test getconnectioncount")
 93          # After using `connect_nodes` to connect nodes 0 and 1 to each other.
 94          assert_equal(self.nodes[0].getconnectioncount(), 2)
 95  
 96      def test_getpeerinfo(self):
 97          self.log.info("Test getpeerinfo")
 98          # Create a few getpeerinfo last_block/last_transaction values.
 99          self.wallet.send_self_transfer(from_node=self.nodes[0]) # Make a transaction so we can see it in the getpeerinfo results
100          self.generate(self.nodes[1], 1)
101          time_now = int(time.time())
102          peer_info = [x.getpeerinfo() for x in self.nodes]
103          # Verify last_block and last_transaction keys/values.
104          for node, peer, field in product(range(self.num_nodes), range(2), ['last_block', 'last_transaction']):
105              assert field in peer_info[node][peer].keys()
106              if peer_info[node][peer][field] != 0:
107                  assert_approx(peer_info[node][peer][field], time_now, vspan=60)
108          # check both sides of bidirectional connection between nodes
109          # the address bound to on one side will be the source address for the other node
110          assert_equal(peer_info[0][0]['addrbind'], peer_info[1][0]['addr'])
111          assert_equal(peer_info[1][0]['addrbind'], peer_info[0][0]['addr'])
112          assert_equal(peer_info[0][0]['minfeefilter'], Decimal("0.00000500"))
113          assert_equal(peer_info[1][0]['minfeefilter'], Decimal("0.00001000"))
114          # check the `servicesnames` field
115          for info in peer_info:
116              assert_net_servicesnames(int(info[0]["services"], 0x10), info[0]["servicesnames"])
117  
118          assert_equal(peer_info[0][0]['connection_type'], 'inbound')
119          assert_equal(peer_info[0][1]['connection_type'], 'manual')
120  
121          assert_equal(peer_info[1][0]['connection_type'], 'manual')
122          assert_equal(peer_info[1][1]['connection_type'], 'inbound')
123  
124          # Check dynamically generated networks list in getpeerinfo help output.
125          assert "(ipv4, ipv6, onion, i2p, cjdns, not_publicly_routable)" in self.nodes[0].help("getpeerinfo")
126  
127          self.log.info("Check getpeerinfo output before a version message was sent")
128          no_version_peer_id = 2
129          no_version_peer_conntime = int(time.time())
130          self.nodes[0].setmocktime(no_version_peer_conntime)
131          with self.nodes[0].wait_for_new_peer():
132              no_version_peer = self.nodes[0].add_p2p_connection(P2PInterface(), send_version=False, wait_for_verack=False)
133          if self.options.v2transport:
134              self.wait_until(lambda: self.nodes[0].getpeerinfo()[no_version_peer_id]["transport_protocol_type"] == "v2")
135          self.nodes[0].setmocktime(0)
136          peer_info = self.nodes[0].getpeerinfo()[no_version_peer_id]
137          peer_info.pop("addr")
138          peer_info.pop("addrbind")
139          # The next two fields will vary for v2 connections because we send a rng-based number of decoy messages
140          peer_info.pop("bytesrecv")
141          peer_info.pop("bytessent")
142          assert_equal(
143              peer_info,
144              {
145                  "addr_processed": 0,
146                  "addr_rate_limited": 0,
147                  "addr_relay_enabled": False,
148                  "bip152_hb_from": False,
149                  "bip152_hb_to": False,
150                  "bytesrecv_per_msg": {},
151                  "bytessent_per_msg": {},
152                  "connection_type": "inbound",
153                  "conntime": no_version_peer_conntime,
154                  "id": no_version_peer_id,
155                  "inbound": True,
156                  "inflight": [],
157                  "last_block": 0,
158                  "last_transaction": 0,
159                  "lastrecv": 0 if not self.options.v2transport else no_version_peer_conntime,
160                  "lastsend": 0 if not self.options.v2transport else no_version_peer_conntime,
161                  "minfeefilter": Decimal("0E-8"),
162                  "network": "not_publicly_routable",
163                  "permissions": [],
164                  "presynced_headers": -1,
165                  "relaytxes": False,
166                  "services": "0000000000000000",
167                  "servicesnames": [],
168                  "session_id": "" if not self.options.v2transport else no_version_peer.v2_state.peer['session_id'].hex(),
169                  "startingheight": -1,
170                  "subver": "",
171                  "synced_blocks": -1,
172                  "synced_headers": -1,
173                  "timeoffset": 0,
174                  "transport_protocol_type": "v1" if not self.options.v2transport else "v2",
175                  "version": 0,
176              },
177          )
178          no_version_peer.peer_disconnect()
179          self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 2)
180  
181      def test_getnettotals(self):
182          self.log.info("Test getnettotals")
183          # Test getnettotals and getpeerinfo by doing a ping. The bytes
184          # sent/received should increase by at least the size of one ping
185          # and one pong. Both have a payload size of 8 bytes, but the total
186          # size depends on the used p2p version:
187          #   - p2p v1: 24 bytes (header) + 8 bytes (payload) = 32 bytes
188          #   - p2p v2: 21 bytes (header/tag with short-id) + 8 bytes (payload) = 29 bytes
189          ping_size = 32 if not self.options.v2transport else 29
190          net_totals_before = self.nodes[0].getnettotals()
191          peer_info_before = self.nodes[0].getpeerinfo()
192  
193          self.nodes[0].ping()
194          self.wait_until(lambda: (self.nodes[0].getnettotals()['totalbytessent'] >= net_totals_before['totalbytessent'] + ping_size * 2), timeout=1)
195          self.wait_until(lambda: (self.nodes[0].getnettotals()['totalbytesrecv'] >= net_totals_before['totalbytesrecv'] + ping_size * 2), timeout=1)
196  
197          for peer_before in peer_info_before:
198              peer_after = lambda: next(p for p in self.nodes[0].getpeerinfo() if p['id'] == peer_before['id'])
199              self.wait_until(lambda: peer_after()['bytesrecv_per_msg'].get('pong', 0) >= peer_before['bytesrecv_per_msg'].get('pong', 0) + ping_size, timeout=1)
200              self.wait_until(lambda: peer_after()['bytessent_per_msg'].get('ping', 0) >= peer_before['bytessent_per_msg'].get('ping', 0) + ping_size, timeout=1)
201  
202      def test_getnetworkinfo(self):
203          self.log.info("Test getnetworkinfo")
204          info = self.nodes[0].getnetworkinfo()
205          assert_equal(info['networkactive'], True)
206          assert_equal(info['connections'], 2)
207          assert_equal(info['connections_in'], 1)
208          assert_equal(info['connections_out'], 1)
209  
210          with self.nodes[0].assert_debug_log(expected_msgs=['SetNetworkActive: false\n']):
211              self.nodes[0].setnetworkactive(state=False)
212          assert_equal(self.nodes[0].getnetworkinfo()['networkactive'], False)
213          # Wait a bit for all sockets to close
214          for n in self.nodes:
215              self.wait_until(lambda: n.getnetworkinfo()['connections'] == 0, timeout=3)
216  
217          with self.nodes[0].assert_debug_log(expected_msgs=['SetNetworkActive: true\n']):
218              self.nodes[0].setnetworkactive(state=True)
219          # Connect nodes both ways.
220          self.connect_nodes(0, 1)
221          self.connect_nodes(1, 0)
222  
223          info = self.nodes[0].getnetworkinfo()
224          assert_equal(info['networkactive'], True)
225          assert_equal(info['connections'], 2)
226          assert_equal(info['connections_in'], 1)
227          assert_equal(info['connections_out'], 1)
228  
229          # check the `servicesnames` field
230          network_info = [node.getnetworkinfo() for node in self.nodes]
231          for info in network_info:
232              assert_net_servicesnames(int(info["localservices"], 0x10), info["localservicesnames"])
233  
234          # Check dynamically generated networks list in getnetworkinfo help output.
235          assert "(ipv4, ipv6, onion, i2p, cjdns)" in self.nodes[0].help("getnetworkinfo")
236  
237      def test_addnode_getaddednodeinfo(self):
238          self.log.info("Test addnode and getaddednodeinfo")
239          assert_equal(self.nodes[0].getaddednodeinfo(), [])
240          # add a node (node2) to node0
241          ip_port = "127.0.0.1:{}".format(p2p_port(2))
242          self.nodes[0].addnode(node=ip_port, command='add')
243          # try to add an equivalent ip
244          # (note that OpenBSD doesn't support the IPv4 shorthand notation with omitted zero-bytes)
245          if platform.system() != "OpenBSD":
246              ip_port2 = "127.1:{}".format(p2p_port(2))
247              assert_raises_rpc_error(-23, "Node already added", self.nodes[0].addnode, node=ip_port2, command='add')
248          # check that the node has indeed been added
249          added_nodes = self.nodes[0].getaddednodeinfo()
250          assert_equal(len(added_nodes), 1)
251          assert_equal(added_nodes[0]['addednode'], ip_port)
252          # check that node cannot be added again
253          assert_raises_rpc_error(-23, "Node already added", self.nodes[0].addnode, node=ip_port, command='add')
254          # check that node can be removed
255          self.nodes[0].addnode(node=ip_port, command='remove')
256          assert_equal(self.nodes[0].getaddednodeinfo(), [])
257          # check that an invalid command returns an error
258          assert_raises_rpc_error(-1, 'addnode "node" "command"', self.nodes[0].addnode, node=ip_port, command='abc')
259          # check that trying to remove the node again returns an error
260          assert_raises_rpc_error(-24, "Node could not be removed", self.nodes[0].addnode, node=ip_port, command='remove')
261          # check that a non-existent node returns an error
262          assert_raises_rpc_error(-24, "Node has not been added", self.nodes[0].getaddednodeinfo, '1.1.1.1')
263  
264      def test_service_flags(self):
265          self.log.info("Test service flags")
266          self.nodes[0].add_p2p_connection(P2PInterface(), services=(1 << 4) | (1 << 63))
267          if self.options.v2transport:
268              assert_equal(['UNKNOWN[2^4]', 'P2P_V2', 'UNKNOWN[2^63]'], self.nodes[0].getpeerinfo()[-1]['servicesnames'])
269          else:
270              assert_equal(['UNKNOWN[2^4]', 'UNKNOWN[2^63]'], self.nodes[0].getpeerinfo()[-1]['servicesnames'])
271          self.nodes[0].disconnect_p2ps()
272  
273      def test_getnodeaddresses(self):
274          self.log.info("Test getnodeaddresses")
275          self.nodes[0].add_p2p_connection(P2PInterface())
276  
277          # Add an IPv6 address to the address manager.
278          ipv6_addr = "1233:3432:2434:2343:3234:2345:6546:4534"
279          self.nodes[0].addpeeraddress(address=ipv6_addr, port=8333)
280  
281          # Add 10,000 IPv4 addresses to the address manager. Due to the way bucket
282          # and bucket positions are calculated, some of these addresses will collide.
283          imported_addrs = []
284          for i in range(10000):
285              first_octet = i >> 8
286              second_octet = i % 256
287              a = f"{first_octet}.{second_octet}.1.1"
288              imported_addrs.append(a)
289              self.nodes[0].addpeeraddress(a, 8333)
290  
291          # Fetch the addresses via the RPC and test the results.
292          assert_equal(len(self.nodes[0].getnodeaddresses()), 1)  # default count is 1
293          assert_equal(len(self.nodes[0].getnodeaddresses(count=2)), 2)
294          assert_equal(len(self.nodes[0].getnodeaddresses(network="ipv4", count=8)), 8)
295  
296          # Maximum possible addresses in AddrMan is 10000. The actual number will
297          # usually be less due to bucket and bucket position collisions.
298          node_addresses = self.nodes[0].getnodeaddresses(0, "ipv4")
299          assert_greater_than(len(node_addresses), 5000)
300          assert_greater_than(10000, len(node_addresses))
301          for a in node_addresses:
302              assert_greater_than(a["time"], 1527811200)  # 1st June 2018
303              assert_equal(a["services"], P2P_SERVICES)
304              assert a["address"] in imported_addrs
305              assert_equal(a["port"], 8333)
306              assert_equal(a["network"], "ipv4")
307  
308          # Test the IPv6 address.
309          res = self.nodes[0].getnodeaddresses(0, "ipv6")
310          assert_equal(len(res), 1)
311          assert_equal(res[0]["address"], ipv6_addr)
312          assert_equal(res[0]["network"], "ipv6")
313          assert_equal(res[0]["port"], 8333)
314          assert_equal(res[0]["services"], P2P_SERVICES)
315  
316          # Test for the absence of onion, I2P and CJDNS addresses.
317          for network in ["onion", "i2p", "cjdns"]:
318              assert_equal(self.nodes[0].getnodeaddresses(0, network), [])
319  
320          # Test invalid arguments.
321          assert_raises_rpc_error(-8, "Address count out of range", self.nodes[0].getnodeaddresses, -1)
322          assert_raises_rpc_error(-8, "Network not recognized: Foo", self.nodes[0].getnodeaddresses, 1, "Foo")
323  
324      def test_addpeeraddress(self):
325          self.log.info("Test addpeeraddress")
326          # The node has an existing, non-deterministic addrman from a previous test.
327          # Clear it to have a deterministic addrman.
328          self.restart_node(1, ["-checkaddrman=1", "-test=addrman"], clear_addrman=True)
329          node = self.nodes[1]
330  
331          self.log.debug("Test that addpeeraddress is a hidden RPC")
332          # It is hidden from general help, but its detailed help may be called directly.
333          assert "addpeeraddress" not in node.help()
334          assert "unknown command: addpeeraddress" not in node.help("addpeeraddress")
335  
336          self.log.debug("Test that adding an empty address fails")
337          assert_equal(node.addpeeraddress(address="", port=8333), {"success": False})
338          assert_equal(node.getnodeaddresses(count=0), [])
339  
340          self.log.debug("Test that non-bool tried fails")
341          assert_raises_rpc_error(-3, "JSON value of type string is not of expected type bool", self.nodes[0].addpeeraddress, address="1.2.3.4", tried="True", port=1234)
342  
343          self.log.debug("Test that adding an address with invalid port fails")
344          assert_raises_rpc_error(-1, "JSON integer out of range", self.nodes[0].addpeeraddress, address="1.2.3.4", port=-1)
345          assert_raises_rpc_error(-1, "JSON integer out of range", self.nodes[0].addpeeraddress, address="1.2.3.4", port=65536)
346  
347          self.log.debug("Test that adding a valid address to the new table succeeds")
348          assert_equal(node.addpeeraddress(address="1.0.0.0", tried=False, port=8333), {"success": True})
349          addrman = node.getrawaddrman()
350          assert_equal(len(addrman["tried"]), 0)
351          new_table = list(addrman["new"].values())
352          assert_equal(len(new_table), 1)
353          assert_equal(new_table[0]["address"], "1.0.0.0")
354          assert_equal(new_table[0]["port"], 8333)
355  
356          self.log.debug("Test that adding an already-present new address to the new and tried tables fails")
357          for value in [True, False]:
358              assert_equal(node.addpeeraddress(address="1.0.0.0", tried=value, port=8333), {"success": False, "error": "failed-adding-to-new"})
359          assert_equal(len(node.getnodeaddresses(count=0)), 1)
360  
361          self.log.debug("Test that adding a valid address to the tried table succeeds")
362          assert_equal(node.addpeeraddress(address="1.2.3.4", tried=True, port=8333), {"success": True})
363          addrman = node.getrawaddrman()
364          assert_equal(len(addrman["new"]), 1)
365          tried_table = list(addrman["tried"].values())
366          assert_equal(len(tried_table), 1)
367          assert_equal(tried_table[0]["address"], "1.2.3.4")
368          assert_equal(tried_table[0]["port"], 8333)
369          node.getnodeaddresses(count=0)  # getnodeaddresses re-runs the addrman checks
370  
371          self.log.debug("Test that adding an already-present tried address to the new and tried tables fails")
372          for value in [True, False]:
373              assert_equal(node.addpeeraddress(address="1.2.3.4", tried=value, port=8333), {"success": False, "error": "failed-adding-to-new"})
374          assert_equal(len(node.getnodeaddresses(count=0)), 2)
375  
376          self.log.debug("Test that adding an address, which collides with the address in tried table, fails")
377          colliding_address = "1.2.5.45"  # grinded address that produces a tried-table collision
378          assert_equal(node.addpeeraddress(address=colliding_address, tried=True, port=8333), {"success": False, "error": "failed-adding-to-tried"})
379          # When adding an address to the tried table, it's first added to the new table.
380          # As we fail to move it to the tried table, it remains in the new table.
381          addrman_info = node.getaddrmaninfo()
382          assert_equal(addrman_info["all_networks"]["tried"], 1)
383          assert_equal(addrman_info["all_networks"]["new"], 2)
384  
385          self.log.debug("Test that adding an another address to the new table succeeds")
386          assert_equal(node.addpeeraddress(address="2.0.0.0", port=8333), {"success": True})
387          addrman_info = node.getaddrmaninfo()
388          assert_equal(addrman_info["all_networks"]["tried"], 1)
389          assert_equal(addrman_info["all_networks"]["new"], 3)
390          node.getnodeaddresses(count=0)  # getnodeaddresses re-runs the addrman checks
391  
392      def test_sendmsgtopeer(self):
393          node = self.nodes[0]
394  
395          self.restart_node(0)
396          # we want to use a p2p v1 connection here in order to ensure
397          # a peer id of zero (a downgrade from v2 to v1 would lead
398          # to an increase of the peer id)
399          self.connect_nodes(0, 1, peer_advertises_v2=False)
400  
401          self.log.info("Test sendmsgtopeer")
402          self.log.debug("Send a valid message")
403          with self.nodes[1].assert_debug_log(expected_msgs=["received: addr"]):
404              node.sendmsgtopeer(peer_id=0, msg_type="addr", msg="FFFFFF")
405  
406          self.log.debug("Test error for sending to non-existing peer")
407          assert_raises_rpc_error(-1, "Error: Could not send message to peer", node.sendmsgtopeer, peer_id=100, msg_type="addr", msg="FF")
408  
409          self.log.debug("Test that zero-length msg_type is allowed")
410          node.sendmsgtopeer(peer_id=0, msg_type="addr", msg="")
411  
412          self.log.debug("Test error for msg_type that is too long")
413          assert_raises_rpc_error(-8, "Error: msg_type too long, max length is 12", node.sendmsgtopeer, peer_id=0, msg_type="long_msg_type", msg="FF")
414  
415          self.log.debug("Test that unknown msg_type is allowed")
416          node.sendmsgtopeer(peer_id=0, msg_type="unknown", msg="FF")
417  
418          self.log.debug("Test that empty msg is allowed")
419          node.sendmsgtopeer(peer_id=0, msg_type="addr", msg="FF")
420  
421          self.log.debug("Test that oversized messages are allowed, but get us disconnected")
422          zero_byte_string = b'\x00' * 4000001
423          node.sendmsgtopeer(peer_id=0, msg_type="addr", msg=zero_byte_string.hex())
424          self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0, timeout=10)
425  
426      def test_getaddrmaninfo(self):
427          self.log.info("Test getaddrmaninfo")
428          self.restart_node(1, extra_args=["-cjdnsreachable", "-test=addrman"], clear_addrman=True)
429          node = self.nodes[1]
430          seed_addrman(node)
431  
432          expected_network_count = {
433              'all_networks': {'new': 4, 'tried': 4, 'total': 8},
434              'ipv4': {'new': 1, 'tried': 1, 'total': 2},
435              'ipv6': {'new': 1, 'tried': 1, 'total': 2},
436              'onion': {'new': 0, 'tried': 2, 'total': 2},
437              'i2p': {'new': 1, 'tried': 0, 'total': 1},
438              'cjdns': {'new': 1, 'tried': 0, 'total': 1},
439          }
440  
441          self.log.debug("Test that count of addresses in addrman match expected values")
442          res = node.getaddrmaninfo()
443          for network, count in expected_network_count.items():
444              assert_equal(res[network]['new'], count['new'])
445              assert_equal(res[network]['tried'], count['tried'])
446              assert_equal(res[network]['total'], count['total'])
447  
448      def test_getrawaddrman(self):
449          self.log.info("Test getrawaddrman")
450          self.restart_node(1, extra_args=["-cjdnsreachable", "-test=addrman"], clear_addrman=True)
451          node = self.nodes[1]
452          self.addr_time = int(time.time())
453          node.setmocktime(self.addr_time)
454          seed_addrman(node)
455  
456          self.log.debug("Test that getrawaddrman is a hidden RPC")
457          # It is hidden from general help, but its detailed help may be called directly.
458          assert "getrawaddrman" not in node.help()
459          assert "unknown command: getrawaddrman" not in node.help("getrawaddrman")
460  
461          def check_addr_information(result, expected):
462              """Utility to compare a getrawaddrman result entry with an expected entry"""
463              assert_equal(result["address"], expected["address"])
464              assert_equal(result["port"], expected["port"])
465              assert_equal(result["services"], expected["services"])
466              assert_equal(result["network"], expected["network"])
467              assert_equal(result["source"], expected["source"])
468              assert_equal(result["source_network"], expected["source_network"])
469              assert_equal(result["time"], self.addr_time)
470  
471          def check_getrawaddrman_entries(expected):
472              """Utility to compare a getrawaddrman result with expected addrman contents"""
473              getrawaddrman = node.getrawaddrman()
474              getaddrmaninfo = node.getaddrmaninfo()
475              for (table_name, table_info) in expected.items():
476                  assert_equal(len(getrawaddrman[table_name]), len(table_info))
477                  assert_equal(len(getrawaddrman[table_name]), getaddrmaninfo["all_networks"][table_name])
478  
479                  for bucket_position in getrawaddrman[table_name].keys():
480                      entry = getrawaddrman[table_name][bucket_position]
481                      expected_entry = list(filter(lambda e: e["address"] == entry["address"], table_info))[0]
482                      assert bucket_position == expected_entry["bucket_position"]
483                      check_addr_information(entry, expected_entry)
484  
485          # we expect 4 new and 4 tried table entries in the addrman which were added using seed_addrman()
486          expected = {
487              "new": [
488                      {
489                          "bucket_position": "82/8",
490                          "address": "2.0.0.0",
491                          "port": 8333,
492                          "services": 9,
493                          "network": "ipv4",
494                          "source": "2.0.0.0",
495                          "source_network": "ipv4",
496                      },
497                      {
498                          "bucket_position": "336/24",
499                          "address": "fc00:1:2:3:4:5:6:7",
500                          "port": 8333,
501                          "services": 9,
502                          "network": "cjdns",
503                          "source": "fc00:1:2:3:4:5:6:7",
504                          "source_network": "cjdns",
505                      },
506                      {
507                          "bucket_position": "963/46",
508                          "address": "c4gfnttsuwqomiygupdqqqyy5y5emnk5c73hrfvatri67prd7vyq.b32.i2p",
509                          "port": 8333,
510                          "services": 9,
511                          "network": "i2p",
512                          "source": "c4gfnttsuwqomiygupdqqqyy5y5emnk5c73hrfvatri67prd7vyq.b32.i2p",
513                          "source_network": "i2p",
514                      },
515                      {
516                          "bucket_position": "613/6",
517                          "address": "2803:0:1234:abcd::1",
518                          "services": 9,
519                          "network": "ipv6",
520                          "source": "2803:0:1234:abcd::1",
521                          "source_network": "ipv6",
522                          "port": 45324,
523                      }
524              ],
525              "tried": [
526                      {
527                          "bucket_position": "6/33",
528                          "address": "1.2.3.4",
529                          "port": 8333,
530                          "services": 9,
531                          "network": "ipv4",
532                          "source": "1.2.3.4",
533                          "source_network": "ipv4",
534                      },
535                      {
536                          "bucket_position": "197/34",
537                          "address": "1233:3432:2434:2343:3234:2345:6546:4534",
538                          "port": 8333,
539                          "services": 9,
540                          "network": "ipv6",
541                          "source": "1233:3432:2434:2343:3234:2345:6546:4534",
542                          "source_network": "ipv6",
543                      },
544                      {
545                          "bucket_position": "72/61",
546                          "address": "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion",
547                          "port": 8333,
548                          "services": 9,
549                          "network": "onion",
550                          "source": "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion",
551                          "source_network": "onion"
552                      },
553                      {
554                          "bucket_position": "139/46",
555                          "address": "nrfj6inpyf73gpkyool35hcmne5zwfmse3jl3aw23vk7chdemalyaqad.onion",
556                          "services": 9,
557                          "network": "onion",
558                          "source": "nrfj6inpyf73gpkyool35hcmne5zwfmse3jl3aw23vk7chdemalyaqad.onion",
559                          "source_network": "onion",
560                          "port": 45324,
561                      }
562              ]
563          }
564  
565          self.log.debug("Test that getrawaddrman contains information about newly added addresses in each addrman table")
566          check_getrawaddrman_entries(expected)
567  
568  
569  if __name__ == '__main__':
570      NetTest().main()