/ test / functional / mempool_spend_coinbase.py
mempool_spend_coinbase.py
 1  #!/usr/bin/env python3
 2  # Copyright (c) 2014-2022 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 spending coinbase transactions.
 6  
 7  The coinbase transaction in block N can appear in block
 8  N+100... so is valid in the mempool when the best block
 9  height is N+99.
10  This test makes sure coinbase spends that will be mature
11  in the next block are accepted into the memory pool,
12  but less mature coinbase spends are NOT.
13  """
14  
15  from test_framework.test_framework import BitcoinTestFramework
16  from test_framework.util import assert_equal, assert_raises_rpc_error
17  from test_framework.wallet import MiniWallet
18  
19  
20  class MempoolSpendCoinbaseTest(BitcoinTestFramework):
21      def set_test_params(self):
22          self.num_nodes = 1
23  
24      def run_test(self):
25          wallet = MiniWallet(self.nodes[0])
26  
27          # Invalidate two blocks, so that miniwallet has access to a coin that will mature in the next block
28          chain_height = 198
29          self.nodes[0].invalidateblock(self.nodes[0].getblockhash(chain_height + 1))
30          assert_equal(chain_height, self.nodes[0].getblockcount())
31  
32          # Coinbase at height chain_height-100+1 ok in mempool, should
33          # get mined. Coinbase at height chain_height-100+2 is
34          # too immature to spend.
35          coinbase_txid = lambda h: self.nodes[0].getblock(self.nodes[0].getblockhash(h))['tx'][0]
36          utxo_mature = wallet.get_utxo(txid=coinbase_txid(chain_height - 100 + 1))
37          utxo_immature = wallet.get_utxo(txid=coinbase_txid(chain_height - 100 + 2))
38  
39          spend_mature_id = wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_mature)["txid"]
40  
41          # other coinbase should be too immature to spend
42          immature_tx = wallet.create_self_transfer(utxo_to_spend=utxo_immature)
43          assert_raises_rpc_error(-26,
44                                  "bad-txns-premature-spend-of-coinbase",
45                                  lambda: self.nodes[0].sendrawtransaction(immature_tx['hex']))
46  
47          # mempool should have just the mature one
48          assert_equal(self.nodes[0].getrawmempool(), [spend_mature_id])
49  
50          # mine a block, mature one should get confirmed
51          self.generate(self.nodes[0], 1)
52          assert_equal(set(self.nodes[0].getrawmempool()), set())
53  
54          # ... and now previously immature can be spent:
55          spend_new_id = self.nodes[0].sendrawtransaction(immature_tx['hex'])
56          assert_equal(self.nodes[0].getrawmempool(), [spend_new_id])
57  
58  
59  if __name__ == '__main__':
60      MempoolSpendCoinbaseTest().main()