You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rpcbind_test.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env python2
  2. # Copyright (c) 2014 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 for -rpcbind, as well as -rpcallowip and -rpcconnect
  6. # Add python-bitcoinrpc to module search path:
  7. import os
  8. import sys
  9. sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc"))
  10. import json
  11. import shutil
  12. import subprocess
  13. import tempfile
  14. import traceback
  15. from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
  16. from util import *
  17. from netutil import *
  18. def run_bind_test(tmpdir, allow_ips, connect_to, addresses, expected):
  19. '''
  20. Start a node with requested rpcallowip and rpcbind parameters,
  21. then try to connect, and check if the set of bound addresses
  22. matches the expected set.
  23. '''
  24. expected = [(addr_to_hex(addr), port) for (addr, port) in expected]
  25. base_args = ['-disablewallet', '-nolisten']
  26. if allow_ips:
  27. base_args += ['-rpcallowip=' + x for x in allow_ips]
  28. binds = ['-rpcbind='+addr for addr in addresses]
  29. nodes = start_nodes(1, tmpdir, [base_args + binds], connect_to)
  30. try:
  31. pid = bitcoind_processes[0].pid
  32. assert_equal(set(get_bind_addrs(pid)), set(expected))
  33. finally:
  34. stop_nodes(nodes)
  35. wait_bitcoinds()
  36. def run_allowip_test(tmpdir, allow_ips, rpchost, rpcport):
  37. '''
  38. Start a node with rpcwallow IP, and request getinfo
  39. at a non-localhost IP.
  40. '''
  41. base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
  42. nodes = start_nodes(1, tmpdir, [base_args])
  43. try:
  44. # connect to node through non-loopback interface
  45. url = "http://rt:rt@%s:%d" % (rpchost, rpcport,)
  46. node = AuthServiceProxy(url)
  47. node.getinfo()
  48. finally:
  49. node = None # make sure connection will be garbage collected and closed
  50. stop_nodes(nodes)
  51. wait_bitcoinds()
  52. def run_test(tmpdir):
  53. assert(sys.platform == 'linux2') # due to OS-specific network stats queries, this test works only on Linux
  54. # find the first non-loopback interface for testing
  55. non_loopback_ip = None
  56. for name,ip in all_interfaces():
  57. if ip != '127.0.0.1':
  58. non_loopback_ip = ip
  59. break
  60. if non_loopback_ip is None:
  61. assert(not 'This test requires at least one non-loopback IPv4 interface')
  62. print("Using interface %s for testing" % non_loopback_ip)
  63. defaultport = rpc_port(0)
  64. # check default without rpcallowip (IPv4 and IPv6 localhost)
  65. run_bind_test(tmpdir, None, '127.0.0.1', [],
  66. [('127.0.0.1', defaultport), ('::1', defaultport)])
  67. # check default with rpcallowip (IPv6 any)
  68. run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', [],
  69. [('::0', defaultport)])
  70. # check only IPv4 localhost (explicit)
  71. run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],
  72. [('127.0.0.1', defaultport)])
  73. # check only IPv4 localhost (explicit) with alternative port
  74. run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
  75. [('127.0.0.1', 32171)])
  76. # check only IPv4 localhost (explicit) with multiple alternative ports on same host
  77. run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],
  78. [('127.0.0.1', 32171), ('127.0.0.1', 32172)])
  79. # check only IPv6 localhost (explicit)
  80. run_bind_test(tmpdir, ['[::1]'], '[::1]', ['[::1]'],
  81. [('::1', defaultport)])
  82. # check both IPv4 and IPv6 localhost (explicit)
  83. run_bind_test(tmpdir, ['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],
  84. [('127.0.0.1', defaultport), ('::1', defaultport)])
  85. # check only non-loopback interface
  86. run_bind_test(tmpdir, [non_loopback_ip], non_loopback_ip, [non_loopback_ip],
  87. [(non_loopback_ip, defaultport)])
  88. # Check that with invalid rpcallowip, we are denied
  89. run_allowip_test(tmpdir, [non_loopback_ip], non_loopback_ip, defaultport)
  90. try:
  91. run_allowip_test(tmpdir, ['1.1.1.1'], non_loopback_ip, defaultport)
  92. assert(not 'Connection not denied by rpcallowip as expected')
  93. except ValueError:
  94. pass
  95. def main():
  96. import optparse
  97. parser = optparse.OptionParser(usage="%prog [options]")
  98. parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
  99. help="Leave bitcoinds and test.* datadir on exit or error")
  100. parser.add_option("--srcdir", dest="srcdir", default="../../src",
  101. help="Source directory containing bitcoind/bitcoin-cli (default: %default%)")
  102. parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
  103. help="Root directory for datadirs")
  104. (options, args) = parser.parse_args()
  105. os.environ['PATH'] = options.srcdir+":"+os.environ['PATH']
  106. check_json_precision()
  107. success = False
  108. nodes = []
  109. try:
  110. print("Initializing test directory "+options.tmpdir)
  111. if not os.path.isdir(options.tmpdir):
  112. os.makedirs(options.tmpdir)
  113. initialize_chain(options.tmpdir)
  114. run_test(options.tmpdir)
  115. success = True
  116. except AssertionError as e:
  117. print("Assertion failed: "+e.message)
  118. except Exception as e:
  119. print("Unexpected exception caught during testing: "+str(e))
  120. traceback.print_tb(sys.exc_info()[2])
  121. if not options.nocleanup:
  122. print("Cleaning up")
  123. wait_bitcoinds()
  124. shutil.rmtree(options.tmpdir)
  125. if success:
  126. print("Tests successful")
  127. sys.exit(0)
  128. else:
  129. print("Failed")
  130. sys.exit(1)
  131. if __name__ == '__main__':
  132. main()