|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) 2022 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 -discover command.""" |
| 6 | + |
| 7 | +import socket |
| 8 | + |
| 9 | +from test_framework.test_framework import BitcoinTestFramework |
| 10 | +from test_framework.util import assert_equal |
| 11 | + |
| 12 | + |
| 13 | +def is_valid_ipv4_address(address): |
| 14 | + try: |
| 15 | + socket.inet_aton(address) |
| 16 | + except socket.error: |
| 17 | + return False |
| 18 | + return True |
| 19 | + |
| 20 | + |
| 21 | +def is_valid_ipv6_address(address): |
| 22 | + try: |
| 23 | + socket.inet_pton(socket.AF_INET6, address) |
| 24 | + except socket.error: |
| 25 | + return False |
| 26 | + return True |
| 27 | + |
| 28 | + |
| 29 | +class DiscoverTest(BitcoinTestFramework): |
| 30 | + def set_test_params(self): |
| 31 | + self.setup_clean_chain = True |
| 32 | + self.bind_to_localhost_only = False |
| 33 | + self.num_nodes = 1 |
| 34 | + |
| 35 | + def validate_addresses(self, addresses_obj): |
| 36 | + for address_obj in addresses_obj: |
| 37 | + address = address_obj['address'] |
| 38 | + self.log.info(f"Validating {address}") |
| 39 | + valid = (is_valid_ipv4_address(address) |
| 40 | + or is_valid_ipv6_address(address)) |
| 41 | + assert_equal(valid, True) |
| 42 | + |
| 43 | + def test_local_addresses(self, test_case, *, expect_empty=False): |
| 44 | + self.log.info(f"Restart node with {test_case}") |
| 45 | + self.restart_node(0, test_case) |
| 46 | + network_info = self.nodes[0].getnetworkinfo() |
| 47 | + network_enabled = [n for n in network_info['networks'] |
| 48 | + if n['reachable'] and n['name'] in ['ipv4', 'ipv6']] |
| 49 | + local_addrs = list(network_info["localaddresses"]) |
| 50 | + if expect_empty or not network_enabled: |
| 51 | + assert_equal(local_addrs, []) |
| 52 | + elif len(local_addrs) > 0: |
| 53 | + self.validate_addresses(local_addrs) |
| 54 | + |
| 55 | + def run_test(self): |
| 56 | + test_cases = [ |
| 57 | + ["-listen", "-discover"], |
| 58 | + ["-discover"], |
| 59 | + ] |
| 60 | + |
| 61 | + test_cases_empty = [ |
| 62 | + ["-discover=0"], |
| 63 | + ["-listen", "-discover=0"], |
| 64 | + [], |
| 65 | + ] |
| 66 | + |
| 67 | + for test_case in test_cases: |
| 68 | + self.test_local_addresses(test_case, expect_empty=False) |
| 69 | + |
| 70 | + for test_case in test_cases_empty: |
| 71 | + self.test_local_addresses(test_case, expect_empty=True) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + DiscoverTest().main() |
0 commit comments