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.

wallet.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 the wallet."""
  6. from test_framework.test_framework import BitcoinTestFramework
  7. from test_framework.util import *
  8. class WalletTest(BitcoinTestFramework):
  9. def set_test_params(self):
  10. self.num_nodes = 4
  11. self.setup_clean_chain = True
  12. self.extra_args = [['-usehd={:d}'.format(i%2==0)] for i in range(4)]
  13. def setup_network(self):
  14. self.add_nodes(4, self.extra_args)
  15. self.start_node(0)
  16. self.start_node(1)
  17. self.start_node(2)
  18. connect_nodes_bi(self.nodes,0,1)
  19. connect_nodes_bi(self.nodes,1,2)
  20. connect_nodes_bi(self.nodes,0,2)
  21. self.sync_all([self.nodes[0:3]])
  22. def check_fee_amount(self, curr_balance, balance_with_fee, fee_per_byte, tx_size):
  23. """Return curr_balance after asserting the fee was in range"""
  24. fee = balance_with_fee - curr_balance
  25. assert_fee_amount(fee, tx_size, fee_per_byte * 1000)
  26. return curr_balance
  27. def run_test(self):
  28. # Check that there's no UTXO on none of the nodes
  29. assert_equal(len(self.nodes[0].listunspent()), 0)
  30. assert_equal(len(self.nodes[1].listunspent()), 0)
  31. assert_equal(len(self.nodes[2].listunspent()), 0)
  32. self.log.info("Mining blocks...")
  33. self.nodes[0].generate(1)
  34. walletinfo = self.nodes[0].getwalletinfo()
  35. assert_equal(walletinfo['immature_balance'], 50)
  36. assert_equal(walletinfo['balance'], 0)
  37. self.sync_all([self.nodes[0:3]])
  38. self.nodes[1].generate(101)
  39. self.sync_all([self.nodes[0:3]])
  40. assert_equal(self.nodes[0].getbalance(), 50)
  41. assert_equal(self.nodes[1].getbalance(), 50)
  42. assert_equal(self.nodes[2].getbalance(), 0)
  43. # Check that only first and second nodes have UTXOs
  44. utxos = self.nodes[0].listunspent()
  45. assert_equal(len(utxos), 1)
  46. assert_equal(len(self.nodes[1].listunspent()), 1)
  47. assert_equal(len(self.nodes[2].listunspent()), 0)
  48. self.log.info("test gettxout")
  49. confirmed_txid, confirmed_index = utxos[0]["txid"], utxos[0]["vout"]
  50. # First, outputs that are unspent both in the chain and in the
  51. # mempool should appear with or without include_mempool
  52. txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=False)
  53. assert_equal(txout['value'], 50)
  54. txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=True)
  55. assert_equal(txout['value'], 50)
  56. # Send 21 BTC from 0 to 2 using sendtoaddress call.
  57. # Locked memory should use at least 32 bytes to sign each transaction
  58. self.log.info("test getmemoryinfo")
  59. memory_before = self.nodes[0].getmemoryinfo()
  60. self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
  61. mempool_txid = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
  62. memory_after = self.nodes[0].getmemoryinfo()
  63. assert(memory_before['locked']['used'] + 64 <= memory_after['locked']['used'])
  64. self.log.info("test gettxout (second part)")
  65. # utxo spent in mempool should be visible if you exclude mempool
  66. # but invisible if you include mempool
  67. txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, False)
  68. assert_equal(txout['value'], 50)
  69. txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, True)
  70. assert txout is None
  71. # new utxo from mempool should be invisible if you exclude mempool
  72. # but visible if you include mempool
  73. txout = self.nodes[0].gettxout(mempool_txid, 0, False)
  74. assert txout is None
  75. txout1 = self.nodes[0].gettxout(mempool_txid, 0, True)
  76. txout2 = self.nodes[0].gettxout(mempool_txid, 1, True)
  77. # note the mempool tx will have randomly assigned indices
  78. # but 10 will go to node2 and the rest will go to node0
  79. balance = self.nodes[0].getbalance()
  80. assert_equal(set([txout1['value'], txout2['value']]), set([10, balance]))
  81. walletinfo = self.nodes[0].getwalletinfo()
  82. assert_equal(walletinfo['immature_balance'], 0)
  83. # Have node0 mine a block, thus it will collect its own fee.
  84. self.nodes[0].generate(1)
  85. self.sync_all([self.nodes[0:3]])
  86. # Exercise locking of unspent outputs
  87. unspent_0 = self.nodes[2].listunspent()[0]
  88. unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
  89. self.nodes[2].lockunspent(False, [unspent_0])
  90. assert_raises_rpc_error(-4, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
  91. assert_equal([unspent_0], self.nodes[2].listlockunspent())
  92. self.nodes[2].lockunspent(True, [unspent_0])
  93. assert_equal(len(self.nodes[2].listlockunspent()), 0)
  94. # Have node1 generate 100 blocks (so node0 can recover the fee)
  95. self.nodes[1].generate(100)
  96. self.sync_all([self.nodes[0:3]])
  97. # node0 should end up with 100 btc in block rewards plus fees, but
  98. # minus the 21 plus fees sent to node2
  99. assert_equal(self.nodes[0].getbalance(), 100-21)
  100. assert_equal(self.nodes[2].getbalance(), 21)
  101. # Node0 should have two unspent outputs.
  102. # Create a couple of transactions to send them to node2, submit them through
  103. # node1, and make sure both node0 and node2 pick them up properly:
  104. node0utxos = self.nodes[0].listunspent(1)
  105. assert_equal(len(node0utxos), 2)
  106. # create both transactions
  107. txns_to_send = []
  108. for utxo in node0utxos:
  109. inputs = []
  110. outputs = {}
  111. inputs.append({ "txid" : utxo["txid"], "vout" : utxo["vout"]})
  112. outputs[self.nodes[2].getnewaddress("from1")] = utxo["amount"] - 3
  113. raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
  114. txns_to_send.append(self.nodes[0].signrawtransaction(raw_tx))
  115. # Have node 1 (miner) send the transactions
  116. self.nodes[1].sendrawtransaction(txns_to_send[0]["hex"], True)
  117. self.nodes[1].sendrawtransaction(txns_to_send[1]["hex"], True)
  118. # Have node1 mine a block to confirm transactions:
  119. self.nodes[1].generate(1)
  120. self.sync_all([self.nodes[0:3]])
  121. assert_equal(self.nodes[0].getbalance(), 0)
  122. assert_equal(self.nodes[2].getbalance(), 94)
  123. assert_equal(self.nodes[2].getbalance("from1"), 94-21)
  124. # Send 10 BTC normal
  125. address = self.nodes[0].getnewaddress("test")
  126. fee_per_byte = Decimal('0.001') / 1000
  127. self.nodes[2].settxfee(fee_per_byte * 1000)
  128. txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
  129. self.nodes[2].generate(1)
  130. self.sync_all([self.nodes[0:3]])
  131. node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('84'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
  132. assert_equal(self.nodes[0].getbalance(), Decimal('10'))
  133. # Send 10 BTC with subtract fee from amount
  134. txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
  135. self.nodes[2].generate(1)
  136. self.sync_all([self.nodes[0:3]])
  137. node_2_bal -= Decimal('10')
  138. assert_equal(self.nodes[2].getbalance(), node_2_bal)
  139. node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), Decimal('20'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
  140. # Sendmany 10 BTC
  141. txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [])
  142. self.nodes[2].generate(1)
  143. self.sync_all([self.nodes[0:3]])
  144. node_0_bal += Decimal('10')
  145. node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), node_2_bal - Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
  146. assert_equal(self.nodes[0].getbalance(), node_0_bal)
  147. # Sendmany 10 BTC with subtract fee from amount
  148. txid = self.nodes[2].sendmany('from1', {address: 10}, 0, "", [address])
  149. self.nodes[2].generate(1)
  150. self.sync_all([self.nodes[0:3]])
  151. node_2_bal -= Decimal('10')
  152. assert_equal(self.nodes[2].getbalance(), node_2_bal)
  153. node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), node_0_bal + Decimal('10'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid)))
  154. # Test ResendWalletTransactions:
  155. # Create a couple of transactions, then start up a fourth
  156. # node (nodes[3]) and ask nodes[0] to rebroadcast.
  157. # EXPECT: nodes[3] should have those transactions in its mempool.
  158. txid1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1)
  159. txid2 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
  160. sync_mempools(self.nodes[0:2])
  161. self.start_node(3)
  162. connect_nodes_bi(self.nodes, 0, 3)
  163. sync_blocks(self.nodes)
  164. relayed = self.nodes[0].resendwallettransactions()
  165. assert_equal(set(relayed), {txid1, txid2})
  166. sync_mempools(self.nodes)
  167. assert(txid1 in self.nodes[3].getrawmempool())
  168. # Exercise balance rpcs
  169. assert_equal(self.nodes[0].getwalletinfo()["unconfirmed_balance"], 1)
  170. assert_equal(self.nodes[0].getunconfirmedbalance(), 1)
  171. #check if we can list zero value tx as available coins
  172. #1. create rawtx
  173. #2. hex-changed one output to 0.0
  174. #3. sign and send
  175. #4. check if recipient (node0) can list the zero value tx
  176. usp = self.nodes[1].listunspent()
  177. inputs = [{"txid":usp[0]['txid'], "vout":usp[0]['vout']}]
  178. outputs = {self.nodes[1].getnewaddress(): 49.998, self.nodes[0].getnewaddress(): 11.11}
  179. rawTx = self.nodes[1].createrawtransaction(inputs, outputs).replace("c0833842", "00000000") #replace 11.11 with 0.0 (int32)
  180. decRawTx = self.nodes[1].decoderawtransaction(rawTx)
  181. signedRawTx = self.nodes[1].signrawtransaction(rawTx)
  182. decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex'])
  183. zeroValueTxid= decRawTx['txid']
  184. sendResp = self.nodes[1].sendrawtransaction(signedRawTx['hex'])
  185. self.sync_all()
  186. self.nodes[1].generate(1) #mine a block
  187. self.sync_all()
  188. unspentTxs = self.nodes[0].listunspent() #zero value tx must be in listunspents output
  189. found = False
  190. for uTx in unspentTxs:
  191. if uTx['txid'] == zeroValueTxid:
  192. found = True
  193. assert_equal(uTx['amount'], Decimal('0'))
  194. assert(found)
  195. #do some -walletbroadcast tests
  196. self.stop_nodes()
  197. self.start_node(0, ["-walletbroadcast=0"])
  198. self.start_node(1, ["-walletbroadcast=0"])
  199. self.start_node(2, ["-walletbroadcast=0"])
  200. connect_nodes_bi(self.nodes,0,1)
  201. connect_nodes_bi(self.nodes,1,2)
  202. connect_nodes_bi(self.nodes,0,2)
  203. self.sync_all([self.nodes[0:3]])
  204. txIdNotBroadcasted = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
  205. txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
  206. self.nodes[1].generate(1) #mine a block, tx should not be in there
  207. self.sync_all([self.nodes[0:3]])
  208. assert_equal(self.nodes[2].getbalance(), node_2_bal) #should not be changed because tx was not broadcasted
  209. #now broadcast from another node, mine a block, sync, and check the balance
  210. self.nodes[1].sendrawtransaction(txObjNotBroadcasted['hex'])
  211. self.nodes[1].generate(1)
  212. self.sync_all([self.nodes[0:3]])
  213. node_2_bal += 2
  214. txObjNotBroadcasted = self.nodes[0].gettransaction(txIdNotBroadcasted)
  215. assert_equal(self.nodes[2].getbalance(), node_2_bal)
  216. #create another tx
  217. txIdNotBroadcasted = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
  218. #restart the nodes with -walletbroadcast=1
  219. self.stop_nodes()
  220. self.start_node(0)
  221. self.start_node(1)
  222. self.start_node(2)
  223. connect_nodes_bi(self.nodes,0,1)
  224. connect_nodes_bi(self.nodes,1,2)
  225. connect_nodes_bi(self.nodes,0,2)
  226. sync_blocks(self.nodes[0:3])
  227. self.nodes[0].generate(1)
  228. sync_blocks(self.nodes[0:3])
  229. node_2_bal += 2
  230. #tx should be added to balance because after restarting the nodes tx should be broadcastet
  231. assert_equal(self.nodes[2].getbalance(), node_2_bal)
  232. #send a tx with value in a string (PR#6380 +)
  233. txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "2")
  234. txObj = self.nodes[0].gettransaction(txId)
  235. assert_equal(txObj['amount'], Decimal('-2'))
  236. txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "0.0001")
  237. txObj = self.nodes[0].gettransaction(txId)
  238. assert_equal(txObj['amount'], Decimal('-0.0001'))
  239. #check if JSON parser can handle scientific notation in strings
  240. txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1e-4")
  241. txObj = self.nodes[0].gettransaction(txId)
  242. assert_equal(txObj['amount'], Decimal('-0.0001'))
  243. # This will raise an exception because the amount type is wrong
  244. assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")
  245. # This will raise an exception since generate does not accept a string
  246. assert_raises_rpc_error(-1, "not an integer", self.nodes[0].generate, "2")
  247. # Import address and private key to check correct behavior of spendable unspents
  248. # 1. Send some coins to generate new UTXO
  249. address_to_import = self.nodes[2].getnewaddress()
  250. txid = self.nodes[0].sendtoaddress(address_to_import, 1)
  251. self.nodes[0].generate(1)
  252. self.sync_all([self.nodes[0:3]])
  253. # 2. Import address from node2 to node1
  254. self.nodes[1].importaddress(address_to_import)
  255. # 3. Validate that the imported address is watch-only on node1
  256. assert(self.nodes[1].validateaddress(address_to_import)["iswatchonly"])
  257. # 4. Check that the unspents after import are not spendable
  258. assert_array_result(self.nodes[1].listunspent(),
  259. {"address": address_to_import},
  260. {"spendable": False})
  261. # 5. Import private key of the previously imported address on node1
  262. priv_key = self.nodes[2].dumpprivkey(address_to_import)
  263. self.nodes[1].importprivkey(priv_key)
  264. # 6. Check that the unspents are now spendable on node1
  265. assert_array_result(self.nodes[1].listunspent(),
  266. {"address": address_to_import},
  267. {"spendable": True})
  268. # Mine a block from node0 to an address from node1
  269. cbAddr = self.nodes[1].getnewaddress()
  270. blkHash = self.nodes[0].generatetoaddress(1, cbAddr)[0]
  271. cbTxId = self.nodes[0].getblock(blkHash)['tx'][0]
  272. self.sync_all([self.nodes[0:3]])
  273. # Check that the txid and balance is found by node1
  274. self.nodes[1].gettransaction(cbTxId)
  275. # check if wallet or blockchain maintenance changes the balance
  276. self.sync_all([self.nodes[0:3]])
  277. blocks = self.nodes[0].generate(2)
  278. self.sync_all([self.nodes[0:3]])
  279. balance_nodes = [self.nodes[i].getbalance() for i in range(3)]
  280. block_count = self.nodes[0].getblockcount()
  281. # Check modes:
  282. # - True: unicode escaped as \u....
  283. # - False: unicode directly as UTF-8
  284. for mode in [True, False]:
  285. self.nodes[0].ensure_ascii = mode
  286. # unicode check: Basic Multilingual Plane, Supplementary Plane respectively
  287. for s in [u'рыба', u'𝅘𝅥𝅯']:
  288. addr = self.nodes[0].getaccountaddress(s)
  289. label = self.nodes[0].getaccount(addr)
  290. assert_equal(label, s)
  291. assert(s in self.nodes[0].listaccounts().keys())
  292. self.nodes[0].ensure_ascii = True # restore to default
  293. # maintenance tests
  294. maintenance = [
  295. '-rescan',
  296. '-reindex',
  297. '-zapwallettxes=1',
  298. '-zapwallettxes=2',
  299. # disabled until issue is fixed: https://github.com/bitcoin/bitcoin/issues/7463
  300. # '-salvagewallet',
  301. ]
  302. chainlimit = 6
  303. for m in maintenance:
  304. self.log.info("check " + m)
  305. self.stop_nodes()
  306. # set lower ancestor limit for later
  307. self.start_node(0, [m, "-limitancestorcount="+str(chainlimit)])
  308. self.start_node(1, [m, "-limitancestorcount="+str(chainlimit)])
  309. self.start_node(2, [m, "-limitancestorcount="+str(chainlimit)])
  310. while m == '-reindex' and [block_count] * 3 != [self.nodes[i].getblockcount() for i in range(3)]:
  311. # reindex will leave rpc warm up "early"; Wait for it to finish
  312. time.sleep(0.1)
  313. assert_equal(balance_nodes, [self.nodes[i].getbalance() for i in range(3)])
  314. # Exercise listsinceblock with the last two blocks
  315. coinbase_tx_1 = self.nodes[0].listsinceblock(blocks[0])
  316. assert_equal(coinbase_tx_1["lastblock"], blocks[1])
  317. assert_equal(len(coinbase_tx_1["transactions"]), 1)
  318. assert_equal(coinbase_tx_1["transactions"][0]["blockhash"], blocks[1])
  319. assert_equal(len(self.nodes[0].listsinceblock(blocks[1])["transactions"]), 0)
  320. # ==Check that wallet prefers to use coins that don't exceed mempool limits =====
  321. # Get all non-zero utxos together
  322. chain_addrs = [self.nodes[0].getnewaddress(), self.nodes[0].getnewaddress()]
  323. singletxid = self.nodes[0].sendtoaddress(chain_addrs[0], self.nodes[0].getbalance(), "", "", True)
  324. self.nodes[0].generate(1)
  325. node0_balance = self.nodes[0].getbalance()
  326. # Split into two chains
  327. rawtx = self.nodes[0].createrawtransaction([{"txid":singletxid, "vout":0}], {chain_addrs[0]:node0_balance/2-Decimal('0.01'), chain_addrs[1]:node0_balance/2-Decimal('0.01')})
  328. signedtx = self.nodes[0].signrawtransaction(rawtx)
  329. singletxid = self.nodes[0].sendrawtransaction(signedtx["hex"])
  330. self.nodes[0].generate(1)
  331. # Make a long chain of unconfirmed payments without hitting mempool limit
  332. # Each tx we make leaves only one output of change on a chain 1 longer
  333. # Since the amount to send is always much less than the outputs, we only ever need one output
  334. # So we should be able to generate exactly chainlimit txs for each original output
  335. sending_addr = self.nodes[1].getnewaddress()
  336. txid_list = []
  337. for i in range(chainlimit*2):
  338. txid_list.append(self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001')))
  339. assert_equal(self.nodes[0].getmempoolinfo()['size'], chainlimit*2)
  340. assert_equal(len(txid_list), chainlimit*2)
  341. # Without walletrejectlongchains, we will still generate a txid
  342. # The tx will be stored in the wallet but not accepted to the mempool
  343. extra_txid = self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001'))
  344. assert(extra_txid not in self.nodes[0].getrawmempool())
  345. assert(extra_txid in [tx["txid"] for tx in self.nodes[0].listtransactions()])
  346. self.nodes[0].abandontransaction(extra_txid)
  347. total_txs = len(self.nodes[0].listtransactions("*",99999))
  348. # Try with walletrejectlongchains
  349. # Double chain limit but require combining inputs, so we pass SelectCoinsMinConf
  350. self.stop_node(0)
  351. self.start_node(0, extra_args=["-walletrejectlongchains", "-limitancestorcount="+str(2*chainlimit)])
  352. # wait for loadmempool
  353. timeout = 10
  354. while (timeout > 0 and len(self.nodes[0].getrawmempool()) < chainlimit*2):
  355. time.sleep(0.5)
  356. timeout -= 0.5
  357. assert_equal(len(self.nodes[0].getrawmempool()), chainlimit*2)
  358. node0_balance = self.nodes[0].getbalance()
  359. # With walletrejectlongchains we will not create the tx and store it in our wallet.
  360. assert_raises_rpc_error(-4, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
  361. # Verify nothing new in wallet
  362. assert_equal(total_txs, len(self.nodes[0].listtransactions("*",99999)))
  363. if __name__ == '__main__':
  364. WalletTest().main()