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.

keypool.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. # Exercise the wallet keypool, and interaction with wallet encryption/locking
  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. def check_array_result(object_array, to_match, expected):
  18. """
  19. Pass in array of JSON objects, a dictionary with key/value pairs
  20. to match against, and another dictionary with expected key/value
  21. pairs.
  22. """
  23. num_matched = 0
  24. for item in object_array:
  25. all_match = True
  26. for key,value in to_match.items():
  27. if item[key] != value:
  28. all_match = False
  29. if not all_match:
  30. continue
  31. for key,value in expected.items():
  32. if item[key] != value:
  33. raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
  34. num_matched = num_matched+1
  35. if num_matched == 0:
  36. raise AssertionError("No objects matched %s"%(str(to_match)))
  37. def run_test(nodes, tmpdir):
  38. # Encrypt wallet and wait to terminate
  39. nodes[0].encryptwallet('test')
  40. bitcoind_processes[0].wait()
  41. # Restart node 0
  42. nodes[0] = start_node(0, tmpdir)
  43. # Keep creating keys
  44. addr = nodes[0].getnewaddress()
  45. try:
  46. addr = nodes[0].getnewaddress()
  47. raise AssertionError('Keypool should be exhausted after one address')
  48. except JSONRPCException,e:
  49. assert(e.error['code']==-12)
  50. # put three new keys in the keypool
  51. nodes[0].walletpassphrase('test', 12000)
  52. nodes[0].keypoolrefill(3)
  53. nodes[0].walletlock()
  54. # drain the keys
  55. addr = set()
  56. addr.add(nodes[0].getrawchangeaddress())
  57. addr.add(nodes[0].getrawchangeaddress())
  58. addr.add(nodes[0].getrawchangeaddress())
  59. addr.add(nodes[0].getrawchangeaddress())
  60. # assert that four unique addresses were returned
  61. assert(len(addr) == 4)
  62. # the next one should fail
  63. try:
  64. addr = nodes[0].getrawchangeaddress()
  65. raise AssertionError('Keypool should be exhausted after three addresses')
  66. except JSONRPCException,e:
  67. assert(e.error['code']==-12)
  68. def main():
  69. import optparse
  70. parser = optparse.OptionParser(usage="%prog [options]")
  71. parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
  72. help="Leave bitcoinds and test.* datadir on exit or error")
  73. parser.add_option("--srcdir", dest="srcdir", default="../../src",
  74. help="Source directory containing bitcoind/bitcoin-cli (default: %default%)")
  75. parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
  76. help="Root directory for datadirs")
  77. (options, args) = parser.parse_args()
  78. os.environ['PATH'] = options.srcdir+":"+os.environ['PATH']
  79. check_json_precision()
  80. success = False
  81. nodes = []
  82. try:
  83. print("Initializing test directory "+options.tmpdir)
  84. if not os.path.isdir(options.tmpdir):
  85. os.makedirs(options.tmpdir)
  86. initialize_chain(options.tmpdir)
  87. nodes = start_nodes(1, options.tmpdir)
  88. run_test(nodes, options.tmpdir)
  89. success = True
  90. except AssertionError as e:
  91. print("Assertion failed: "+e.message)
  92. except JSONRPCException as e:
  93. print("JSONRPC error: "+e.error['message'])
  94. traceback.print_tb(sys.exc_info()[2])
  95. except Exception as e:
  96. print("Unexpected exception caught during testing: "+str(sys.exc_info()[0]))
  97. traceback.print_tb(sys.exc_info()[2])
  98. if not options.nocleanup:
  99. print("Cleaning up")
  100. stop_nodes(nodes)
  101. wait_bitcoinds()
  102. shutil.rmtree(options.tmpdir)
  103. if success:
  104. print("Tests successful")
  105. sys.exit(0)
  106. else:
  107. print("Failed")
  108. sys.exit(1)
  109. if __name__ == '__main__':
  110. main()