1#!/usr/bin/env python3
2# Copyright (c) 2015-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 prioritisetransaction mining RPC."""
6
7import time
8
9from test_framework.messages import COIN, MAX_BLOCK_BASE_SIZE
10from test_framework.test_framework import BitcoinTestFramework
11from test_framework.util import assert_equal, assert_raises_rpc_error, create_confirmed_utxos, create_lots_of_big_transactions, gen_return_txouts
12
13class PrioritiseTransactionTest(BitcoinTestFramework):
14    def set_test_params(self):
15        self.setup_clean_chain = True
16        self.num_nodes = 2
17        self.extra_args = [["-printpriority=1"], ["-printpriority=1"]]
18
19    def skip_test_if_missing_module(self):
20        self.skip_if_no_wallet()
21
22    def run_test(self):
23        # Test `prioritisetransaction` required parameters
24        assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction)
25        assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '')
26        assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0)
27
28        # Test `prioritisetransaction` invalid extra parameters
29        assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0, 0, 0)
30
31        # Test `prioritisetransaction` invalid `txid`
32        assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].prioritisetransaction, txid='foo', fee_delta=0)
33        assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000')", self.nodes[0].prioritisetransaction, txid='Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000', fee_delta=0)
34
35        # Test `prioritisetransaction` invalid `dummy`
36        txid = '1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000'
37        assert_raises_rpc_error(-1, "JSON value is not a number as expected", self.nodes[0].prioritisetransaction, txid, 'foo', 0)
38        assert_raises_rpc_error(-8, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.", self.nodes[0].prioritisetransaction, txid, 1, 0)
39
40        # Test `prioritisetransaction` invalid `fee_delta`
41        assert_raises_rpc_error(-1, "JSON value is not an integer as expected", self.nodes[0].prioritisetransaction, txid=txid, fee_delta='foo')
42
43        self.txouts = gen_return_txouts()
44        self.relayfee = self.nodes[0].getnetworkinfo()['relayfee']
45
46        utxo_count = 90
47        utxos = create_confirmed_utxos(self.relayfee, self.nodes[0], utxo_count)
48        base_fee = self.relayfee*100 # our transactions are smaller than 100kb
49        txids = []
50
51        # Create 3 batches of transactions at 3 different fee rate levels
52        range_size = utxo_count // 3
53        for i in range(3):
54            txids.append([])
55            start_range = i * range_size
56            end_range = start_range + range_size
57            txids[i] = create_lots_of_big_transactions(self.nodes[0], self.txouts, utxos[start_range:end_range], end_range - start_range, (i+1)*base_fee)
58
59        # Make sure that the size of each group of transactions exceeds
60        # MAX_BLOCK_BASE_SIZE -- otherwise the test needs to be revised to create
61        # more transactions.
62        mempool = self.nodes[0].getrawmempool(True)
63        sizes = [0, 0, 0]
64        for i in range(3):
65            for j in txids[i]:
66                assert(j in mempool)
67                sizes[i] += mempool[j]['size']
68            assert(sizes[i] > MAX_BLOCK_BASE_SIZE) # Fail => raise utxo_count
69
70        # add a fee delta to something in the cheapest bucket and make sure it gets mined
71        # also check that a different entry in the cheapest bucket is NOT mined
72        self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(3*base_fee*COIN))
73
74        self.nodes[0].generate(1)
75
76        mempool = self.nodes[0].getrawmempool()
77        self.log.info("Assert that prioritised transaction was mined")
78        assert(txids[0][0] not in mempool)
79        assert(txids[0][1] in mempool)
80
81        high_fee_tx = None
82        for x in txids[2]:
83            if x not in mempool:
84                high_fee_tx = x
85
86        # Something high-fee should have been mined!
87        assert(high_fee_tx is not None)
88
89        # Add a prioritisation before a tx is in the mempool (de-prioritising a
90        # high-fee transaction so that it's now low fee).
91        self.nodes[0].prioritisetransaction(txid=high_fee_tx, fee_delta=-int(2*base_fee*COIN))
92
93        # Add everything back to mempool
94        self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
95
96        # Check to make sure our high fee rate tx is back in the mempool
97        mempool = self.nodes[0].getrawmempool()
98        assert(high_fee_tx in mempool)
99
100        # Now verify the modified-high feerate transaction isn't mined before
101        # the other high fee transactions. Keep mining until our mempool has
102        # decreased by all the high fee size that we calculated above.
103        while (self.nodes[0].getmempoolinfo()['bytes'] > sizes[0] + sizes[1]):
104            self.nodes[0].generate(1)
105
106        # High fee transaction should not have been mined, but other high fee rate
107        # transactions should have been.
108        mempool = self.nodes[0].getrawmempool()
109        self.log.info("Assert that de-prioritised transaction is still in mempool")
110        assert(high_fee_tx in mempool)
111        for x in txids[2]:
112            if (x != high_fee_tx):
113                assert(x not in mempool)
114
115        # Create a free transaction.  Should be rejected.
116        utxo_list = self.nodes[0].listunspent()
117        assert(len(utxo_list) > 0)
118        utxo = utxo_list[0]
119
120        inputs = []
121        outputs = {}
122        inputs.append({"txid" : utxo["txid"], "vout" : utxo["vout"]})
123        outputs[self.nodes[0].getnewaddress()] = utxo["amount"]
124        raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
125        tx_hex = self.nodes[0].signrawtransactionwithwallet(raw_tx)["hex"]
126        tx_id = self.nodes[0].decoderawtransaction(tx_hex)["txid"]
127
128        # This will raise an exception due to min relay fee not being met
129        assert_raises_rpc_error(-26, "min relay fee not met", self.nodes[0].sendrawtransaction, tx_hex)
130        assert(tx_id not in self.nodes[0].getrawmempool())
131
132        # This is a less than 1000-byte transaction, so just set the fee
133        # to be the minimum for a 1000-byte transaction and check that it is
134        # accepted.
135        self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=int(self.relayfee*COIN))
136
137        self.log.info("Assert that prioritised free transaction is accepted to mempool")
138        assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id)
139        assert(tx_id in self.nodes[0].getrawmempool())
140
141        # Test that calling prioritisetransaction is sufficient to trigger
142        # getblocktemplate to (eventually) return a new block.
143        mock_time = int(time.time())
144        self.nodes[0].setmocktime(mock_time)
145        template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
146        self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=-int(self.relayfee*COIN))
147        self.nodes[0].setmocktime(mock_time+10)
148        new_template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
149
150        assert(template != new_template)
151
152if __name__ == '__main__':
153    PrioritiseTransactionTest().main()
154