1 #!/usr/bin/env python3
2 # Copyright (c) 2024-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 """
6 Test the -port option and its interactions with
7 -bind.
8 """
9 10 from test_framework.test_framework import (
11 BitcoinTestFramework,
12 )
13 from test_framework.util import (
14 p2p_port,
15 )
16 17 18 class PortTest(BitcoinTestFramework):
19 def set_test_params(self):
20 self.setup_clean_chain = True
21 # Avoid any -bind= on the command line.
22 self.bind_to_localhost_only = False
23 self.num_nodes = 1
24 25 def run_test(self):
26 node = self.nodes[0]
27 node.has_explicit_bind = True
28 port1 = p2p_port(self.num_nodes)
29 port2 = p2p_port(self.num_nodes + 5)
30 31 self.log.info("When starting with -port, bitcoind binds to it and uses port + 1 for an onion bind")
32 with node.assert_debug_log(expected_msgs=[f'Bound to 0.0.0.0:{port1}', f'Bound to 127.0.0.1:{port1 + 1}']):
33 self.restart_node(0, extra_args=["-listen", f"-port={port1}"])
34 35 self.log.info("When specifying -port multiple times, only the last one is taken")
36 with node.assert_debug_log(expected_msgs=[f'Bound to 0.0.0.0:{port2}', f'Bound to 127.0.0.1:{port2 + 1}'], unexpected_msgs=[f'Bound to 0.0.0.0:{port1}']):
37 self.restart_node(0, extra_args=["-listen", f"-port={port1}", f"-port={port2}"])
38 39 self.log.info("When specifying ports with both -port and -bind, the one from -port is ignored")
40 with node.assert_debug_log(expected_msgs=[f'Bound to 0.0.0.0:{port2}'], unexpected_msgs=[f'Bound to 0.0.0.0:{port1}']):
41 self.restart_node(0, extra_args=["-listen", f"-port={port1}", f"-bind=0.0.0.0:{port2}"])
42 43 self.log.info("When -bind specifies no port, the values from -port and -bind are combined")
44 with self.nodes[0].assert_debug_log(expected_msgs=[f'Bound to 0.0.0.0:{port1}']):
45 self.restart_node(0, extra_args=["-listen", f"-port={port1}", "-bind=0.0.0.0"])
46 47 self.log.info("When an onion bind specifies no port, the value from -port, incremented by 1, is taken")
48 with self.nodes[0].assert_debug_log(expected_msgs=[f'Bound to 127.0.0.1:{port1 + 1}']):
49 self.restart_node(0, extra_args=["-listen", f"-port={port1}", "-bind=127.0.0.1=onion"])
50 51 self.log.info("Invalid values for -port raise errors")
52 self.stop_node(0)
53 node.extra_args = ["-listen", "-port=65536"]
54 node.assert_start_raises_init_error(expected_msg="Error: Invalid port specified in -port: '65536'")
55 node.extra_args = ["-listen", "-port=0"]
56 node.assert_start_raises_init_error(expected_msg="Error: Invalid port specified in -port: '0'")
57 58 59 if __name__ == '__main__':
60 PortTest(__file__).main()
61