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 18KB

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