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 """Test block-relay-only anchors functionality"""
6 7 import os
8 9 from test_framework.p2p import P2PInterface, P2P_SERVICES
10 from test_framework.socks5 import Socks5Configuration, Socks5Server
11 from test_framework.messages import CAddress, hash256, ser_compact_size
12 from test_framework.test_framework import LimenkaTestFramework
13 from test_framework.util import check_node_connections, assert_equal, p2p_port
14 15 INBOUND_CONNECTIONS = 5
16 BLOCK_RELAY_CONNECTIONS = 2
17 ONION_ADDR = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:8333"
18 19 20 class AnchorsTest(LimenkaTestFramework):
21 def set_test_params(self):
22 self.num_nodes = 1
23 self.disable_autoconnect = False
24 25 def run_test(self):
26 node_anchors_path = self.nodes[0].chain_path / "anchors.dat"
27 28 self.log.info("When node starts, check if anchors.dat doesn't exist")
29 assert not os.path.exists(node_anchors_path)
30 31 self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node")
32 for i in range(BLOCK_RELAY_CONNECTIONS):
33 self.log.debug(f"block-relay-only: {i}")
34 self.nodes[0].add_outbound_p2p_connection(
35 P2PInterface(), p2p_idx=i, connection_type="block-relay-only"
36 )
37 38 self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node")
39 for i in range(INBOUND_CONNECTIONS):
40 self.log.debug(f"inbound: {i}")
41 self.nodes[0].add_p2p_connection(P2PInterface())
42 43 self.log.info("Check node connections")
44 check_node_connections(node=self.nodes[0], num_in=5, num_out=2)
45 46 # 127.0.0.1
47 ip = "7f000001"
48 49 # Since the ip is always 127.0.0.1 for this case,
50 # we store only the port to identify the peers
51 block_relay_nodes_port = []
52 inbound_nodes_port = []
53 for p in self.nodes[0].getpeerinfo():
54 addr_split = p["addr"].split(":")
55 if p["connection_type"] == "block-relay-only":
56 block_relay_nodes_port.append(hex(int(addr_split[1]))[2:])
57 else:
58 inbound_nodes_port.append(hex(int(addr_split[1]))[2:])
59 60 self.log.debug("Stop node")
61 self.stop_node(0)
62 63 # It should contain only the block-relay-only addresses
64 self.log.info("Check the addresses in anchors.dat")
65 66 with open(node_anchors_path, "rb") as file_handler:
67 anchors = file_handler.read()
68 69 anchors_hex = anchors.hex()
70 for port in block_relay_nodes_port:
71 ip_port = ip + port
72 assert ip_port in anchors_hex
73 for port in inbound_nodes_port:
74 ip_port = ip + port
75 assert ip_port not in anchors_hex
76 77 self.log.info("Perturb anchors.dat to test it doesn't throw an error during initialization")
78 with self.nodes[0].assert_debug_log(["0 block-relay-only anchors will be tried for connections."]):
79 with open(node_anchors_path, "wb") as out_file_handler:
80 tweaked_contents = bytearray(anchors)
81 tweaked_contents[20:20] = b'1'
82 out_file_handler.write(bytes(tweaked_contents))
83 84 self.log.debug("Start node")
85 self.start_node(0)
86 87 self.log.info("When node starts, check if anchors.dat doesn't exist anymore")
88 assert not os.path.exists(node_anchors_path)
89 90 self.log.info("Ensure addrv2 support")
91 # Use proxies to catch outbound connections to networks with 256-bit addresses
92 onion_conf = Socks5Configuration()
93 onion_conf.auth = True
94 onion_conf.unauth = True
95 onion_conf.addr = ('127.0.0.1', p2p_port(self.num_nodes))
96 onion_conf.keep_alive = True
97 onion_proxy = Socks5Server(onion_conf)
98 onion_proxy.start()
99 self.restart_node(0, extra_args=[f"-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}"])
100 101 self.log.info("Add 256-bit-address block-relay-only connections to node")
102 self.nodes[0].addconnection(ONION_ADDR, 'block-relay-only', v2transport=False)
103 104 self.log.debug("Stop node")
105 with self.nodes[0].assert_debug_log(["DumpAnchors: Flush 1 outbound block-relay-only peer addresses to anchors.dat"]):
106 self.stop_node(0)
107 # Manually close keep_alive proxy connection
108 onion_proxy.stop()
109 110 self.log.info("Check for addrv2 addresses in anchors.dat")
111 caddr = CAddress()
112 caddr.net = CAddress.NET_TORV3
113 caddr.ip, port_str = ONION_ADDR.split(":")
114 caddr.port = int(port_str)
115 # TorV3 addrv2 serialization:
116 # time(4) | services(CompactSize) | networkID(1) | address length(CompactSize) | address(32)
117 expected_pubkey = caddr.serialize_v2()[7:39].hex()
118 119 # position of services byte of first addr in anchors.dat
120 # network magic, vector length, version, nTime
121 services_index = 4 + 1 + 4 + 4
122 data = bytes()
123 with open(node_anchors_path, "rb") as file_handler:
124 data = file_handler.read()
125 assert_equal(data[services_index], 0x00) # services == NONE (CompactSize encoded as 1 byte)
126 anchors2 = data.hex()
127 assert expected_pubkey in anchors2
128 129 with open(node_anchors_path, "wb") as file_handler:
130 # Modify service flags for this address even though we never connected to it.
131 # This is necessary because on restart we will not attempt an anchor connection
132 # to a host without our required services, even if its address is in the anchors.dat file
133 new_data = bytearray(data)[:-32]
134 # Replace the 1-byte services field (0x00) with the CompactSize-encoded P2P_SERVICES (5 bytes for 0x08000009)
135 services_bytes = ser_compact_size(P2P_SERVICES)
136 new_data = new_data[:services_index] + services_bytes + new_data[services_index+1:]
137 new_data_hash = hash256(new_data)
138 file_handler.write(new_data + new_data_hash)
139 140 self.log.info("Restarting node attempts to reconnect to anchors")
141 with self.nodes[0].assert_debug_log([f"Trying to make an anchor connection to {ONION_ADDR}"]):
142 self.start_node(0, extra_args=[f"-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}"])
143 144 145 if __name__ == "__main__":
146 AnchorsTest(__file__).main()
147