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.

bumpfee.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python3
  2. # Copyright (c) 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 bumpfee RPC.
  6. Verifies that the bumpfee RPC creates replacement transactions successfully when
  7. its preconditions are met, and returns appropriate errors in other cases.
  8. This module consists of around a dozen individual test cases implemented in the
  9. top-level functions named as test_<test_case_description>. The test functions
  10. can be disabled or reordered if needed for debugging. If new test cases are
  11. added in the future, they should try to follow the same convention and not
  12. make assumptions about execution order.
  13. """
  14. from segwit import send_to_witness
  15. from test_framework.test_framework import BitcoinTestFramework
  16. from test_framework import blocktools
  17. from test_framework.mininode import CTransaction
  18. from test_framework.util import *
  19. import io
  20. # Sequence number that is BIP 125 opt-in and BIP 68-compliant
  21. BIP125_SEQUENCE_NUMBER = 0xfffffffd
  22. WALLET_PASSPHRASE = "test"
  23. WALLET_PASSPHRASE_TIMEOUT = 3600
  24. class BumpFeeTest(BitcoinTestFramework):
  25. def set_test_params(self):
  26. self.num_nodes = 2
  27. self.setup_clean_chain = True
  28. self.extra_args = [["-prematurewitness", "-walletprematurewitness", "-walletrbf={}".format(i)]
  29. for i in range(self.num_nodes)]
  30. def run_test(self):
  31. # Encrypt wallet for test_locked_wallet_fails test
  32. self.nodes[1].node_encrypt_wallet(WALLET_PASSPHRASE)
  33. self.start_node(1)
  34. self.nodes[1].walletpassphrase(WALLET_PASSPHRASE, WALLET_PASSPHRASE_TIMEOUT)
  35. connect_nodes_bi(self.nodes, 0, 1)
  36. self.sync_all()
  37. peer_node, rbf_node = self.nodes
  38. rbf_node_address = rbf_node.getnewaddress()
  39. # fund rbf node with 10 coins of 0.001 btc (100,000 satoshis)
  40. self.log.info("Mining blocks...")
  41. peer_node.generate(110)
  42. self.sync_all()
  43. for i in range(25):
  44. peer_node.sendtoaddress(rbf_node_address, 0.001)
  45. self.sync_all()
  46. peer_node.generate(1)
  47. self.sync_all()
  48. assert_equal(rbf_node.getbalance(), Decimal("0.025"))
  49. self.log.info("Running tests")
  50. dest_address = peer_node.getnewaddress()
  51. test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address)
  52. test_segwit_bumpfee_succeeds(rbf_node, dest_address)
  53. test_nonrbf_bumpfee_fails(peer_node, dest_address)
  54. test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address)
  55. test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address)
  56. test_small_output_fails(rbf_node, dest_address)
  57. test_dust_to_fee(rbf_node, dest_address)
  58. test_settxfee(rbf_node, dest_address)
  59. test_rebumping(rbf_node, dest_address)
  60. test_rebumping_not_replaceable(rbf_node, dest_address)
  61. test_unconfirmed_not_spendable(rbf_node, rbf_node_address)
  62. test_bumpfee_metadata(rbf_node, dest_address)
  63. test_locked_wallet_fails(rbf_node, dest_address)
  64. self.log.info("Success")
  65. def test_simple_bumpfee_succeeds(rbf_node, peer_node, dest_address):
  66. rbfid = spend_one_input(rbf_node, dest_address)
  67. rbftx = rbf_node.gettransaction(rbfid)
  68. sync_mempools((rbf_node, peer_node))
  69. assert rbfid in rbf_node.getrawmempool() and rbfid in peer_node.getrawmempool()
  70. bumped_tx = rbf_node.bumpfee(rbfid)
  71. assert_equal(bumped_tx["errors"], [])
  72. assert bumped_tx["fee"] - abs(rbftx["fee"]) > 0
  73. # check that bumped_tx propogates, original tx was evicted and has a wallet conflict
  74. sync_mempools((rbf_node, peer_node))
  75. assert bumped_tx["txid"] in rbf_node.getrawmempool()
  76. assert bumped_tx["txid"] in peer_node.getrawmempool()
  77. assert rbfid not in rbf_node.getrawmempool()
  78. assert rbfid not in peer_node.getrawmempool()
  79. oldwtx = rbf_node.gettransaction(rbfid)
  80. assert len(oldwtx["walletconflicts"]) > 0
  81. # check wallet transaction replaces and replaced_by values
  82. bumpedwtx = rbf_node.gettransaction(bumped_tx["txid"])
  83. assert_equal(oldwtx["replaced_by_txid"], bumped_tx["txid"])
  84. assert_equal(bumpedwtx["replaces_txid"], rbfid)
  85. def test_segwit_bumpfee_succeeds(rbf_node, dest_address):
  86. # Create a transaction with segwit output, then create an RBF transaction
  87. # which spends it, and make sure bumpfee can be called on it.
  88. segwit_in = next(u for u in rbf_node.listunspent() if u["amount"] == Decimal("0.001"))
  89. segwit_out = rbf_node.validateaddress(rbf_node.getnewaddress())
  90. rbf_node.addwitnessaddress(segwit_out["address"])
  91. segwitid = send_to_witness(
  92. use_p2wsh=False,
  93. node=rbf_node,
  94. utxo=segwit_in,
  95. pubkey=segwit_out["pubkey"],
  96. encode_p2sh=False,
  97. amount=Decimal("0.0009"),
  98. sign=True)
  99. rbfraw = rbf_node.createrawtransaction([{
  100. 'txid': segwitid,
  101. 'vout': 0,
  102. "sequence": BIP125_SEQUENCE_NUMBER
  103. }], {dest_address: Decimal("0.0005"),
  104. rbf_node.getrawchangeaddress(): Decimal("0.0003")})
  105. rbfsigned = rbf_node.signrawtransaction(rbfraw)
  106. rbfid = rbf_node.sendrawtransaction(rbfsigned["hex"])
  107. assert rbfid in rbf_node.getrawmempool()
  108. bumped_tx = rbf_node.bumpfee(rbfid)
  109. assert bumped_tx["txid"] in rbf_node.getrawmempool()
  110. assert rbfid not in rbf_node.getrawmempool()
  111. def test_nonrbf_bumpfee_fails(peer_node, dest_address):
  112. # cannot replace a non RBF transaction (from node which did not enable RBF)
  113. not_rbfid = peer_node.sendtoaddress(dest_address, Decimal("0.00090000"))
  114. assert_raises_rpc_error(-4, "not BIP 125 replaceable", peer_node.bumpfee, not_rbfid)
  115. def test_notmine_bumpfee_fails(rbf_node, peer_node, dest_address):
  116. # cannot bump fee unless the tx has only inputs that we own.
  117. # here, the rbftx has a peer_node coin and then adds a rbf_node input
  118. # Note that this test depends upon the RPC code checking input ownership prior to change outputs
  119. # (since it can't use fundrawtransaction, it lacks a proper change output)
  120. utxos = [node.listunspent()[-1] for node in (rbf_node, peer_node)]
  121. inputs = [{
  122. "txid": utxo["txid"],
  123. "vout": utxo["vout"],
  124. "address": utxo["address"],
  125. "sequence": BIP125_SEQUENCE_NUMBER
  126. } for utxo in utxos]
  127. output_val = sum(utxo["amount"] for utxo in utxos) - Decimal("0.001")
  128. rawtx = rbf_node.createrawtransaction(inputs, {dest_address: output_val})
  129. signedtx = rbf_node.signrawtransaction(rawtx)
  130. signedtx = peer_node.signrawtransaction(signedtx["hex"])
  131. rbfid = rbf_node.sendrawtransaction(signedtx["hex"])
  132. assert_raises_rpc_error(-4, "Transaction contains inputs that don't belong to this wallet",
  133. rbf_node.bumpfee, rbfid)
  134. def test_bumpfee_with_descendant_fails(rbf_node, rbf_node_address, dest_address):
  135. # cannot bump fee if the transaction has a descendant
  136. # parent is send-to-self, so we don't have to check which output is change when creating the child tx
  137. parent_id = spend_one_input(rbf_node, rbf_node_address)
  138. tx = rbf_node.createrawtransaction([{"txid": parent_id, "vout": 0}], {dest_address: 0.00020000})
  139. tx = rbf_node.signrawtransaction(tx)
  140. txid = rbf_node.sendrawtransaction(tx["hex"])
  141. assert_raises_rpc_error(-8, "Transaction has descendants in the wallet", rbf_node.bumpfee, parent_id)
  142. def test_small_output_fails(rbf_node, dest_address):
  143. # cannot bump fee with a too-small output
  144. rbfid = spend_one_input(rbf_node, dest_address)
  145. rbf_node.bumpfee(rbfid, {"totalFee": 50000})
  146. rbfid = spend_one_input(rbf_node, dest_address)
  147. assert_raises_rpc_error(-4, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 50001})
  148. def test_dust_to_fee(rbf_node, dest_address):
  149. # check that if output is reduced to dust, it will be converted to fee
  150. # the bumped tx sets fee=49,900, but it converts to 50,000
  151. rbfid = spend_one_input(rbf_node, dest_address)
  152. fulltx = rbf_node.getrawtransaction(rbfid, 1)
  153. bumped_tx = rbf_node.bumpfee(rbfid, {"totalFee": 49900})
  154. full_bumped_tx = rbf_node.getrawtransaction(bumped_tx["txid"], 1)
  155. assert_equal(bumped_tx["fee"], Decimal("0.00050000"))
  156. assert_equal(len(fulltx["vout"]), 2)
  157. assert_equal(len(full_bumped_tx["vout"]), 1) #change output is eliminated
  158. def test_settxfee(rbf_node, dest_address):
  159. # check that bumpfee reacts correctly to the use of settxfee (paytxfee)
  160. rbfid = spend_one_input(rbf_node, dest_address)
  161. requested_feerate = Decimal("0.00025000")
  162. rbf_node.settxfee(requested_feerate)
  163. bumped_tx = rbf_node.bumpfee(rbfid)
  164. actual_feerate = bumped_tx["fee"] * 1000 / rbf_node.getrawtransaction(bumped_tx["txid"], True)["size"]
  165. # Assert that the difference between the requested feerate and the actual
  166. # feerate of the bumped transaction is small.
  167. assert_greater_than(Decimal("0.00001000"), abs(requested_feerate - actual_feerate))
  168. rbf_node.settxfee(Decimal("0.00000000")) # unset paytxfee
  169. def test_rebumping(rbf_node, dest_address):
  170. # check that re-bumping the original tx fails, but bumping the bumper succeeds
  171. rbfid = spend_one_input(rbf_node, dest_address)
  172. bumped = rbf_node.bumpfee(rbfid, {"totalFee": 2000})
  173. assert_raises_rpc_error(-4, "already bumped", rbf_node.bumpfee, rbfid, {"totalFee": 3000})
  174. rbf_node.bumpfee(bumped["txid"], {"totalFee": 3000})
  175. def test_rebumping_not_replaceable(rbf_node, dest_address):
  176. # check that re-bumping a non-replaceable bump tx fails
  177. rbfid = spend_one_input(rbf_node, dest_address)
  178. bumped = rbf_node.bumpfee(rbfid, {"totalFee": 10000, "replaceable": False})
  179. assert_raises_rpc_error(-4, "Transaction is not BIP 125 replaceable", rbf_node.bumpfee, bumped["txid"],
  180. {"totalFee": 20000})
  181. def test_unconfirmed_not_spendable(rbf_node, rbf_node_address):
  182. # check that unconfirmed outputs from bumped transactions are not spendable
  183. rbfid = spend_one_input(rbf_node, rbf_node_address)
  184. rbftx = rbf_node.gettransaction(rbfid)["hex"]
  185. assert rbfid in rbf_node.getrawmempool()
  186. bumpid = rbf_node.bumpfee(rbfid)["txid"]
  187. assert bumpid in rbf_node.getrawmempool()
  188. assert rbfid not in rbf_node.getrawmempool()
  189. # check that outputs from the bump transaction are not spendable
  190. # due to the replaces_txid check in CWallet::AvailableCoins
  191. assert_equal([t for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == bumpid], [])
  192. # submit a block with the rbf tx to clear the bump tx out of the mempool,
  193. # then call abandon to make sure the wallet doesn't attempt to resubmit the
  194. # bump tx, then invalidate the block so the rbf tx will be put back in the
  195. # mempool. this makes it possible to check whether the rbf tx outputs are
  196. # spendable before the rbf tx is confirmed.
  197. block = submit_block_with_tx(rbf_node, rbftx)
  198. rbf_node.abandontransaction(bumpid)
  199. rbf_node.invalidateblock(block.hash)
  200. assert bumpid not in rbf_node.getrawmempool()
  201. assert rbfid in rbf_node.getrawmempool()
  202. # check that outputs from the rbf tx are not spendable before the
  203. # transaction is confirmed, due to the replaced_by_txid check in
  204. # CWallet::AvailableCoins
  205. assert_equal([t for t in rbf_node.listunspent(minconf=0, include_unsafe=False) if t["txid"] == rbfid], [])
  206. # check that the main output from the rbf tx is spendable after confirmed
  207. rbf_node.generate(1)
  208. assert_equal(
  209. sum(1 for t in rbf_node.listunspent(minconf=0, include_unsafe=False)
  210. if t["txid"] == rbfid and t["address"] == rbf_node_address and t["spendable"]), 1)
  211. def test_bumpfee_metadata(rbf_node, dest_address):
  212. rbfid = rbf_node.sendtoaddress(dest_address, Decimal("0.00100000"), "comment value", "to value")
  213. bumped_tx = rbf_node.bumpfee(rbfid)
  214. bumped_wtx = rbf_node.gettransaction(bumped_tx["txid"])
  215. assert_equal(bumped_wtx["comment"], "comment value")
  216. assert_equal(bumped_wtx["to"], "to value")
  217. def test_locked_wallet_fails(rbf_node, dest_address):
  218. rbfid = spend_one_input(rbf_node, dest_address)
  219. rbf_node.walletlock()
  220. assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first.",
  221. rbf_node.bumpfee, rbfid)
  222. def spend_one_input(node, dest_address):
  223. tx_input = dict(
  224. sequence=BIP125_SEQUENCE_NUMBER, **next(u for u in node.listunspent() if u["amount"] == Decimal("0.00100000")))
  225. rawtx = node.createrawtransaction(
  226. [tx_input], {dest_address: Decimal("0.00050000"),
  227. node.getrawchangeaddress(): Decimal("0.00049000")})
  228. signedtx = node.signrawtransaction(rawtx)
  229. txid = node.sendrawtransaction(signedtx["hex"])
  230. return txid
  231. def submit_block_with_tx(node, tx):
  232. ctx = CTransaction()
  233. ctx.deserialize(io.BytesIO(hex_str_to_bytes(tx)))
  234. tip = node.getbestblockhash()
  235. height = node.getblockcount() + 1
  236. block_time = node.getblockheader(tip)["mediantime"] + 1
  237. block = blocktools.create_block(int(tip, 16), blocktools.create_coinbase(height), block_time)
  238. block.vtx.append(ctx)
  239. block.rehash()
  240. block.hashMerkleRoot = block.calc_merkle_root()
  241. block.solve()
  242. node.submitblock(bytes_to_hex_str(block.serialize(True)))
  243. return block
  244. if __name__ == "__main__":
  245. BumpFeeTest().main()