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
6#
7# Test spending coinbase transactions.
8# The coinbase transaction in block N can appear in block
9# N+100... so is valid in the mempool when the best block
10# height is N+99.
11# This test makes sure coinbase spends that will be mature
12# in the next block are accepted into the memory pool,
13# but less mature coinbase spends are NOT.
14#
15
16from test_framework.test_framework import BitcoinTestFramework
17from test_framework.util import *
18
19# Create one-input, one-output, no-fee transaction:
20class MempoolSpendCoinbaseTest(BitcoinTestFramework):
21
22    def __init__(self):
23        super().__init__()
24        self.num_nodes = 1
25        self.setup_clean_chain = False
26
27    def setup_network(self):
28        # Just need one node for this test
29        args = ["-checkmempool", "-debug=mempool"]
30        self.nodes = []
31        self.nodes.append(start_node(0, self.options.tmpdir, args))
32        self.is_network_split = False
33
34    def run_test(self):
35        chain_height = self.nodes[0].getblockcount()
36        assert_equal(chain_height, 200)
37        node0_address = self.nodes[0].getnewaddress()
38
39        # Coinbase at height chain_height-100+1 ok in mempool, should
40        # get mined. Coinbase at height chain_height-100+2 is
41        # is too immature to spend.
42        b = [ self.nodes[0].getblockhash(n) for n in range(101, 103) ]
43        coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ]
44        spends_raw = [ create_tx(self.nodes[0], txid, node0_address, 49.99) for txid in coinbase_txids ]
45
46        spend_101_id = self.nodes[0].sendrawtransaction(spends_raw[0])
47
48        # coinbase at height 102 should be too immature to spend
49        assert_raises(JSONRPCException, self.nodes[0].sendrawtransaction, spends_raw[1])
50
51        # mempool should have just spend_101:
52        assert_equal(self.nodes[0].getrawmempool(), [ spend_101_id ])
53
54        # mine a block, spend_101 should get confirmed
55        self.nodes[0].generate(1)
56        assert_equal(set(self.nodes[0].getrawmempool()), set())
57
58        # ... and now height 102 can be spent:
59        spend_102_id = self.nodes[0].sendrawtransaction(spends_raw[1])
60        assert_equal(self.nodes[0].getrawmempool(), [ spend_102_id ])
61
62if __name__ == '__main__':
63    MempoolSpendCoinbaseTest().main()
64