1#!/usr/bin/env python3
2# Copyright (c) 2014-2019 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 gettxoutproof and verifytxoutproof RPCs."""
6
7from test_framework.messages import CMerkleBlock, FromHex, ToHex
8from test_framework.test_framework import BitcoinTestFramework
9from test_framework.util import assert_equal, assert_raises_rpc_error
10from test_framework.wallet import MiniWallet
11
12
13class MerkleBlockTest(BitcoinTestFramework):
14    def set_test_params(self):
15        self.num_nodes = 2
16        self.setup_clean_chain = True
17        self.extra_args = [
18            [],
19            ["-txindex"],
20        ]
21
22    def run_test(self):
23        miniwallet = MiniWallet(self.nodes[0])
24        # Add enough mature utxos to the wallet, so that all txs spend confirmed coins
25        miniwallet.generate(5)
26        self.nodes[0].generate(100)
27        self.sync_all()
28
29        chain_height = self.nodes[1].getblockcount()
30        assert_equal(chain_height, 105)
31
32        txid1 = miniwallet.send_self_transfer(from_node=self.nodes[0])['txid']
33        txid2 = miniwallet.send_self_transfer(from_node=self.nodes[0])['txid']
34        # This will raise an exception because the transaction is not yet in a block
35        assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid1])
36
37        self.nodes[0].generate(1)
38        blockhash = self.nodes[0].getblockhash(chain_height + 1)
39        self.sync_all()
40
41        txlist = []
42        blocktxn = self.nodes[0].getblock(blockhash, True)["tx"]
43        txlist.append(blocktxn[1])
44        txlist.append(blocktxn[2])
45
46        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1])), [txid1])
47        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1, txid2])), txlist)
48        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1, txid2], blockhash)), txlist)
49
50        txin_spent = miniwallet.get_utxo()  # Get the change from txid2
51        tx3 = miniwallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=txin_spent)
52        txid3 = tx3['txid']
53        self.nodes[0].generate(1)
54        self.sync_all()
55
56        txid_spent = txin_spent["txid"]
57        txid_unspent = txid1  # Input was change from txid2, so txid1 should be unspent
58
59        # Invalid txids
60        assert_raises_rpc_error(-8, "txid must be of length 64 (not 32, for '00000000000000000000000000000000')", self.nodes[0].gettxoutproof, ["00000000000000000000000000000000"], blockhash)
61        assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[0].gettxoutproof, ["ZZZ0000000000000000000000000000000000000000000000000000000000000"], blockhash)
62        # Invalid blockhashes
63        assert_raises_rpc_error(-8, "blockhash must be of length 64 (not 32, for '00000000000000000000000000000000')", self.nodes[0].gettxoutproof, [txid_spent], "00000000000000000000000000000000")
64        assert_raises_rpc_error(-8, "blockhash must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[0].gettxoutproof, [txid_spent], "ZZZ0000000000000000000000000000000000000000000000000000000000000")
65        # We can't find the block from a fully-spent tx
66        assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [txid_spent])
67        # We can get the proof if we specify the block
68        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid_spent], blockhash)), [txid_spent])
69        # We can't get the proof if we specify a non-existent block
70        assert_raises_rpc_error(-5, "Block not found", self.nodes[0].gettxoutproof, [txid_spent], "0000000000000000000000000000000000000000000000000000000000000000")
71        # We can get the proof if the transaction is unspent
72        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid_unspent])), [txid_unspent])
73        # We can get the proof if we provide a list of transactions and one of them is unspent. The ordering of the list should not matter.
74        assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid1, txid2]))), sorted(txlist))
75        assert_equal(sorted(self.nodes[0].verifytxoutproof(self.nodes[0].gettxoutproof([txid2, txid1]))), sorted(txlist))
76        # We can always get a proof if we have a -txindex
77        assert_equal(self.nodes[0].verifytxoutproof(self.nodes[1].gettxoutproof([txid_spent])), [txid_spent])
78        # We can't get a proof if we specify transactions from different blocks
79        assert_raises_rpc_error(-5, "Not all transactions found in specified or retrieved block", self.nodes[0].gettxoutproof, [txid1, txid3])
80        # Test empty list
81        assert_raises_rpc_error(-5, "Transaction not yet in block", self.nodes[0].gettxoutproof, [])
82        # Test duplicate txid
83        assert_raises_rpc_error(-8, 'Invalid parameter, duplicated txid', self.nodes[0].gettxoutproof, [txid1, txid1])
84
85        # Now we'll try tweaking a proof.
86        proof = self.nodes[1].gettxoutproof([txid1, txid2])
87        assert txid1 in self.nodes[0].verifytxoutproof(proof)
88        assert txid2 in self.nodes[1].verifytxoutproof(proof)
89
90        tweaked_proof = FromHex(CMerkleBlock(), proof)
91
92        # Make sure that our serialization/deserialization is working
93        assert txid1 in self.nodes[0].verifytxoutproof(ToHex(tweaked_proof))
94
95        # Check to see if we can go up the merkle tree and pass this off as a
96        # single-transaction block
97        tweaked_proof.txn.nTransactions = 1
98        tweaked_proof.txn.vHash = [tweaked_proof.header.hashMerkleRoot]
99        tweaked_proof.txn.vBits = [True] + [False]*7
100
101        for n in self.nodes:
102            assert not n.verifytxoutproof(ToHex(tweaked_proof))
103
104        # TODO: try more variants, eg transactions at different depths, and
105        # verify that the proofs are invalid
106
107if __name__ == '__main__':
108    MerkleBlockTest().main()
109