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.

import-rescan.py 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-2016 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 wallet import RPCs.
  6. Test rescan behavior of importaddress, importpubkey, importprivkey, and
  7. importmulti RPCs with different types of keys and rescan options.
  8. In the first part of the test, node 0 creates an address for each type of
  9. import RPC call and sends BTC to it. Then other nodes import the addresses,
  10. and the test makes listtransactions and getbalance calls to confirm that the
  11. importing node either did or did not execute rescans picking up the send
  12. transactions.
  13. In the second part of the test, node 0 sends more BTC to each address, and the
  14. test makes more listtransactions and getbalance calls to confirm that the
  15. importing nodes pick up the new transactions regardless of whether rescans
  16. happened previously.
  17. """
  18. from test_framework.authproxy import JSONRPCException
  19. from test_framework.test_framework import BitcoinTestFramework
  20. from test_framework.util import (start_nodes, connect_nodes, sync_blocks, assert_equal, set_node_times)
  21. from decimal import Decimal
  22. import collections
  23. import enum
  24. import itertools
  25. Call = enum.Enum("Call", "single multi")
  26. Data = enum.Enum("Data", "address pub priv")
  27. Rescan = enum.Enum("Rescan", "no yes late_timestamp")
  28. class Variant(collections.namedtuple("Variant", "call data rescan prune")):
  29. """Helper for importing one key and verifying scanned transactions."""
  30. def do_import(self, timestamp):
  31. """Call one key import RPC."""
  32. if self.call == Call.single:
  33. if self.data == Data.address:
  34. response, error = try_rpc(self.node.importaddress, self.address["address"], self.label,
  35. self.rescan == Rescan.yes)
  36. elif self.data == Data.pub:
  37. response, error = try_rpc(self.node.importpubkey, self.address["pubkey"], self.label,
  38. self.rescan == Rescan.yes)
  39. elif self.data == Data.priv:
  40. response, error = try_rpc(self.node.importprivkey, self.key, self.label, self.rescan == Rescan.yes)
  41. assert_equal(response, None)
  42. assert_equal(error, {'message': 'Rescan is disabled in pruned mode',
  43. 'code': -4} if self.expect_disabled else None)
  44. elif self.call == Call.multi:
  45. response = self.node.importmulti([{
  46. "scriptPubKey": {
  47. "address": self.address["address"]
  48. },
  49. "timestamp": timestamp + TIMESTAMP_WINDOW + (1 if self.rescan == Rescan.late_timestamp else 0),
  50. "pubkeys": [self.address["pubkey"]] if self.data == Data.pub else [],
  51. "keys": [self.key] if self.data == Data.priv else [],
  52. "label": self.label,
  53. "watchonly": self.data != Data.priv
  54. }], {"rescan": self.rescan in (Rescan.yes, Rescan.late_timestamp)})
  55. assert_equal(response, [{"success": True}])
  56. def check(self, txid=None, amount=None, confirmations=None):
  57. """Verify that getbalance/listtransactions return expected values."""
  58. balance = self.node.getbalance(self.label, 0, True)
  59. assert_equal(balance, self.expected_balance)
  60. txs = self.node.listtransactions(self.label, 10000, 0, True)
  61. assert_equal(len(txs), self.expected_txs)
  62. if txid is not None:
  63. tx, = [tx for tx in txs if tx["txid"] == txid]
  64. assert_equal(tx["account"], self.label)
  65. assert_equal(tx["address"], self.address["address"])
  66. assert_equal(tx["amount"], amount)
  67. assert_equal(tx["category"], "receive")
  68. assert_equal(tx["label"], self.label)
  69. assert_equal(tx["txid"], txid)
  70. assert_equal(tx["confirmations"], confirmations)
  71. assert_equal("trusted" not in tx, True)
  72. # Verify the transaction is correctly marked watchonly depending on
  73. # whether the transaction pays to an imported public key or
  74. # imported private key. The test setup ensures that transaction
  75. # inputs will not be from watchonly keys (important because
  76. # involvesWatchonly will be true if either the transaction output
  77. # or inputs are watchonly).
  78. if self.data != Data.priv:
  79. assert_equal(tx["involvesWatchonly"], True)
  80. else:
  81. assert_equal("involvesWatchonly" not in tx, True)
  82. # List of Variants for each way a key or address could be imported.
  83. IMPORT_VARIANTS = [Variant(*variants) for variants in itertools.product(Call, Data, Rescan, (False, True))]
  84. # List of nodes to import keys to. Half the nodes will have pruning disabled,
  85. # half will have it enabled. Different nodes will be used for imports that are
  86. # expected to cause rescans, and imports that are not expected to cause
  87. # rescans, in order to prevent rescans during later imports picking up
  88. # transactions associated with earlier imports. This makes it easier to keep
  89. # track of expected balances and transactions.
  90. ImportNode = collections.namedtuple("ImportNode", "prune rescan")
  91. IMPORT_NODES = [ImportNode(*fields) for fields in itertools.product((False, True), repeat=2)]
  92. # Rescans start at the earliest block up to 2 hours before the key timestamp.
  93. TIMESTAMP_WINDOW = 2 * 60 * 60
  94. class ImportRescanTest(BitcoinTestFramework):
  95. def __init__(self):
  96. super().__init__()
  97. self.num_nodes = 2 + len(IMPORT_NODES)
  98. def setup_network(self):
  99. extra_args = [[] for _ in range(self.num_nodes)]
  100. for i, import_node in enumerate(IMPORT_NODES, 2):
  101. if import_node.prune:
  102. extra_args[i] += ["-prune=1"]
  103. self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, extra_args)
  104. for i in range(1, self.num_nodes):
  105. connect_nodes(self.nodes[i], 0)
  106. def run_test(self):
  107. # Create one transaction on node 0 with a unique amount and label for
  108. # each possible type of wallet import RPC.
  109. for i, variant in enumerate(IMPORT_VARIANTS):
  110. variant.label = "label {} {}".format(i, variant)
  111. variant.address = self.nodes[1].validateaddress(self.nodes[1].getnewaddress(variant.label))
  112. variant.key = self.nodes[1].dumpprivkey(variant.address["address"])
  113. variant.initial_amount = 10 - (i + 1) / 4.0
  114. variant.initial_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.initial_amount)
  115. # Generate a block containing the initial transactions, then another
  116. # block further in the future (past the rescan window).
  117. self.nodes[0].generate(1)
  118. assert_equal(self.nodes[0].getrawmempool(), [])
  119. timestamp = self.nodes[0].getblockheader(self.nodes[0].getbestblockhash())["time"]
  120. set_node_times(self.nodes, timestamp + TIMESTAMP_WINDOW + 1)
  121. self.nodes[0].generate(1)
  122. sync_blocks(self.nodes)
  123. # For each variation of wallet key import, invoke the import RPC and
  124. # check the results from getbalance and listtransactions.
  125. for variant in IMPORT_VARIANTS:
  126. variant.expect_disabled = variant.rescan == Rescan.yes and variant.prune and variant.call == Call.single
  127. expect_rescan = variant.rescan == Rescan.yes and not variant.expect_disabled
  128. variant.node = self.nodes[2 + IMPORT_NODES.index(ImportNode(variant.prune, expect_rescan))]
  129. variant.do_import(timestamp)
  130. if expect_rescan:
  131. variant.expected_balance = variant.initial_amount
  132. variant.expected_txs = 1
  133. variant.check(variant.initial_txid, variant.initial_amount, 2)
  134. else:
  135. variant.expected_balance = 0
  136. variant.expected_txs = 0
  137. variant.check()
  138. # Create new transactions sending to each address.
  139. fee = self.nodes[0].getnetworkinfo()["relayfee"]
  140. for i, variant in enumerate(IMPORT_VARIANTS):
  141. variant.sent_amount = 10 - (2 * i + 1) / 8.0
  142. variant.sent_txid = self.nodes[0].sendtoaddress(variant.address["address"], variant.sent_amount)
  143. # Generate a block containing the new transactions.
  144. self.nodes[0].generate(1)
  145. assert_equal(self.nodes[0].getrawmempool(), [])
  146. sync_blocks(self.nodes)
  147. # Check the latest results from getbalance and listtransactions.
  148. for variant in IMPORT_VARIANTS:
  149. if not variant.expect_disabled:
  150. variant.expected_balance += variant.sent_amount
  151. variant.expected_txs += 1
  152. variant.check(variant.sent_txid, variant.sent_amount, 1)
  153. else:
  154. variant.check()
  155. def try_rpc(func, *args, **kwargs):
  156. try:
  157. return func(*args, **kwargs), None
  158. except JSONRPCException as e:
  159. return None, e.error
  160. if __name__ == "__main__":
  161. ImportRescanTest().main()