1 #!/usr/bin/env python3
2 # Copyright (c) 2014-present 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 resurrection of mined transactions when the blockchain is re-organized."""
6 7 from test_framework.test_framework import BitcoinTestFramework
8 from test_framework.util import assert_equal
9 from test_framework.wallet import MiniWallet
10 from test_framework.blocktools import create_empty_fork
11 12 class MempoolCoinbaseTest(BitcoinTestFramework):
13 def set_test_params(self):
14 self.num_nodes = 1
15 16 def trigger_reorg(self, fork_blocks):
17 """Trigger reorg of the fork blocks."""
18 for block in fork_blocks:
19 self.nodes[0].submitblock(block.serialize().hex())
20 assert_equal(self.nodes[0].getbestblockhash(), fork_blocks[-1].hash_hex)
21 22 def run_test(self):
23 node = self.nodes[0]
24 wallet = MiniWallet(node)
25 26 # Spend block 1/2/3's coinbase transactions
27 # Mine a block
28 # Create three more transactions, spending the spends
29 # Mine another block
30 # ... make sure all the transactions are confirmed
31 # Invalidate both blocks
32 # ... make sure all the transactions are put back in the mempool
33 # Mine a new block
34 # ... make sure all the transactions are confirmed again
35 36 # Prep for fork
37 fork_blocks = create_empty_fork(self.nodes[0])
38 blocks = []
39 spends1_ids = [wallet.send_self_transfer(from_node=node)['txid'] for _ in range(3)]
40 blocks.extend(self.generate(node, 1))
41 spends2_ids = [wallet.send_self_transfer(from_node=node)['txid'] for _ in range(3)]
42 blocks.extend(self.generate(node, 1))
43 44 spends_ids = set(spends1_ids + spends2_ids)
45 46 # mempool should be empty, all txns confirmed
47 assert_equal(set(node.getrawmempool()), set())
48 confirmed_txns = set(node.getblock(blocks[0])['tx'] + node.getblock(blocks[1])['tx'])
49 # Checks that all spend txns are contained in the mined blocks
50 assert spends_ids < confirmed_txns
51 52 # Trigger reorg
53 self.trigger_reorg(fork_blocks)
54 55 # All txns should be back in mempool with 0 confirmations
56 assert_equal(set(node.getrawmempool()), spends_ids)
57 58 # Generate another block, they should all get mined
59 blocks = self.generate(node, 1)
60 # mempool should be empty, all txns confirmed
61 assert_equal(set(node.getrawmempool()), set())
62 confirmed_txns = set(node.getblock(blocks[0])['tx'])
63 assert spends_ids < confirmed_txns
64 65 66 if __name__ == '__main__':
67 MempoolCoinbaseTest(__file__).main()
68