1#!/usr/bin/env python3
2# Copyright (c) 2014-2018 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 wallet accounts properly when there is a double-spend conflict."""
6from decimal import Decimal
7
8from test_framework.test_framework import BitcoinTestFramework
9from test_framework.util import (
10    assert_equal,
11    connect_nodes,
12    disconnect_nodes,
13    find_output,
14    sync_blocks,
15)
16
17class TxnMallTest(BitcoinTestFramework):
18    def set_test_params(self):
19        self.num_nodes = 4
20
21    def skip_test_if_missing_module(self):
22        self.skip_if_no_wallet()
23
24    def add_options(self, parser):
25        parser.add_argument("--mineblock", dest="mine_block", default=False, action="store_true",
26                            help="Test double-spend of 1-confirmed transaction")
27
28    def setup_network(self):
29        # Start with split network:
30        super().setup_network()
31        disconnect_nodes(self.nodes[1], 2)
32        disconnect_nodes(self.nodes[2], 1)
33
34    def run_test(self):
35        # All nodes should start with 1,250 BTC:
36        starting_balance = 1250
37
38        # All nodes should be out of IBD.
39        # If the nodes are not all out of IBD, that can interfere with
40        # blockchain sync later in the test when nodes are connected, due to
41        # timing issues.
42        for n in self.nodes:
43            assert n.getblockchaininfo()["initialblockdownload"] == False
44
45        for i in range(4):
46            assert_equal(self.nodes[i].getbalance(), starting_balance)
47            self.nodes[i].getnewaddress("")  # bug workaround, coins generated assigned to first getnewaddress!
48
49        # Assign coins to foo and bar addresses:
50        node0_address_foo = self.nodes[0].getnewaddress()
51        fund_foo_txid = self.nodes[0].sendtoaddress(node0_address_foo, 1219)
52        fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid)
53
54        node0_address_bar = self.nodes[0].getnewaddress()
55        fund_bar_txid = self.nodes[0].sendtoaddress(node0_address_bar, 29)
56        fund_bar_tx = self.nodes[0].gettransaction(fund_bar_txid)
57
58        assert_equal(self.nodes[0].getbalance(),
59                     starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"])
60
61        # Coins are sent to node1_address
62        node1_address = self.nodes[1].getnewaddress()
63
64        # First: use raw transaction API to send 1240 BTC to node1_address,
65        # but don't broadcast:
66        doublespend_fee = Decimal('-.02')
67        rawtx_input_0 = {}
68        rawtx_input_0["txid"] = fund_foo_txid
69        rawtx_input_0["vout"] = find_output(self.nodes[0], fund_foo_txid, 1219)
70        rawtx_input_1 = {}
71        rawtx_input_1["txid"] = fund_bar_txid
72        rawtx_input_1["vout"] = find_output(self.nodes[0], fund_bar_txid, 29)
73        inputs = [rawtx_input_0, rawtx_input_1]
74        change_address = self.nodes[0].getnewaddress()
75        outputs = {}
76        outputs[node1_address] = 1240
77        outputs[change_address] = 1248 - 1240 + doublespend_fee
78        rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
79        doublespend = self.nodes[0].signrawtransactionwithwallet(rawtx)
80        assert_equal(doublespend["complete"], True)
81
82        # Create two spends using 1 50 BTC coin each
83        txid1 = self.nodes[0].sendtoaddress(node1_address, 40)
84        txid2 = self.nodes[0].sendtoaddress(node1_address, 20)
85
86        # Have node0 mine a block:
87        if (self.options.mine_block):
88            self.nodes[0].generate(1)
89            sync_blocks(self.nodes[0:2])
90
91        tx1 = self.nodes[0].gettransaction(txid1)
92        tx2 = self.nodes[0].gettransaction(txid2)
93
94        # Node0's balance should be starting balance, plus 50BTC for another
95        # matured block, minus 40, minus 20, and minus transaction fees:
96        expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"]
97        if self.options.mine_block:
98            expected += 50
99        expected += tx1["amount"] + tx1["fee"]
100        expected += tx2["amount"] + tx2["fee"]
101        assert_equal(self.nodes[0].getbalance(), expected)
102
103        if self.options.mine_block:
104            assert_equal(tx1["confirmations"], 1)
105            assert_equal(tx2["confirmations"], 1)
106            # Node1's balance should be both transaction amounts:
107            assert_equal(self.nodes[1].getbalance(), starting_balance - tx1["amount"] - tx2["amount"])
108        else:
109            assert_equal(tx1["confirmations"], 0)
110            assert_equal(tx2["confirmations"], 0)
111
112        # Now give doublespend and its parents to miner:
113        self.nodes[2].sendrawtransaction(fund_foo_tx["hex"])
114        self.nodes[2].sendrawtransaction(fund_bar_tx["hex"])
115        doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"])
116        # ... mine a block...
117        self.nodes[2].generate(1)
118
119        # Reconnect the split network, and sync chain:
120        connect_nodes(self.nodes[1], 2)
121        self.nodes[2].generate(1)  # Mine another block to make sure we sync
122        sync_blocks(self.nodes)
123        assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2)
124
125        # Re-fetch transaction info:
126        tx1 = self.nodes[0].gettransaction(txid1)
127        tx2 = self.nodes[0].gettransaction(txid2)
128
129        # Both transactions should be conflicted
130        assert_equal(tx1["confirmations"], -2)
131        assert_equal(tx2["confirmations"], -2)
132
133        # Node0's total balance should be starting balance, plus 100BTC for
134        # two more matured blocks, minus 1240 for the double-spend, plus fees (which are
135        # negative):
136        expected = starting_balance + 100 - 1240 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee
137        assert_equal(self.nodes[0].getbalance(), expected)
138
139        # Node1's balance should be its initial balance (1250 for 25 block rewards) plus the doublespend:
140        assert_equal(self.nodes[1].getbalance(), 1250 + 1240)
141
142if __name__ == '__main__':
143    TxnMallTest().main()
144