1#!/usr/bin/env python3
2# Copyright (c) 2014-2020 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 rawtransaction RPCs.
6
7Test the following RPCs:
8   - createrawtransaction
9   - signrawtransactionwithwallet
10   - sendrawtransaction
11   - decoderawtransaction
12   - getrawtransaction
13"""
14
15from collections import OrderedDict
16from decimal import Decimal
17
18from test_framework.blocktools import COINBASE_MATURITY
19from test_framework.messages import (
20    CTransaction,
21    tx_from_hex,
22)
23from test_framework.test_framework import BitcoinTestFramework
24from test_framework.util import (
25    assert_equal,
26    assert_raises_rpc_error,
27    find_vout_for_address,
28)
29
30
31class multidict(dict):
32    """Dictionary that allows duplicate keys.
33
34    Constructed with a list of (key, value) tuples. When dumped by the json module,
35    will output invalid json with repeated keys, eg:
36    >>> json.dumps(multidict([(1,2),(1,2)])
37    '{"1": 2, "1": 2}'
38
39    Used to test calls to rpc methods with repeated keys in the json object."""
40
41    def __init__(self, x):
42        dict.__init__(self, x)
43        self.x = x
44
45    def items(self):
46        return self.x
47
48
49# Create one-input, one-output, no-fee transaction:
50class RawTransactionsTest(BitcoinTestFramework):
51    def set_test_params(self):
52        self.setup_clean_chain = True
53        self.num_nodes = 3
54        self.extra_args = [
55            ["-txindex"],
56            ["-txindex"],
57            ["-txindex"],
58        ]
59        # whitelist all peers to speed up tx relay / mempool sync
60        for args in self.extra_args:
61            args.append("-whitelist=noban@127.0.0.1")
62
63        self.supports_cli = False
64
65    def skip_test_if_missing_module(self):
66        self.skip_if_no_wallet()
67
68    def setup_network(self):
69        super().setup_network()
70        self.connect_nodes(0, 2)
71
72    def run_test(self):
73        self.log.info('prepare some coins for multiple *rawtransaction commands')
74        self.nodes[2].generate(1)
75        self.sync_all()
76        self.nodes[0].generate(COINBASE_MATURITY + 1)
77        self.sync_all()
78        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.5)
79        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.0)
80        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),5.0)
81        self.sync_all()
82        self.nodes[0].generate(5)
83        self.sync_all()
84
85        self.log.info('Test getrawtransaction on genesis block coinbase returns an error')
86        block = self.nodes[0].getblock(self.nodes[0].getblockhash(0))
87        assert_raises_rpc_error(-5, "The genesis block coinbase is not considered an ordinary transaction", self.nodes[0].getrawtransaction, block['merkleroot'])
88
89        self.log.info('Check parameter types and required parameters of createrawtransaction')
90        # Test `createrawtransaction` required parameters
91        assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction)
92        assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [])
93
94        # Test `createrawtransaction` invalid extra parameters
95        assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [], {}, 0, False, 'foo')
96
97        # Test `createrawtransaction` invalid `inputs`
98        txid = '1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000'
99        assert_raises_rpc_error(-3, "Expected type array", self.nodes[0].createrawtransaction, 'foo', {})
100        assert_raises_rpc_error(-1, "JSON value is not an object as expected", self.nodes[0].createrawtransaction, ['foo'], {})
101        assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].createrawtransaction, [{}], {})
102        assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].createrawtransaction, [{'txid': 'foo'}], {})
103        assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844')", self.nodes[0].createrawtransaction, [{'txid': 'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844'}], {})
104        assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': txid}], {})
105        assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': 'foo'}], {})
106        assert_raises_rpc_error(-8, "Invalid parameter, vout cannot be negative", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': -1}], {})
107        assert_raises_rpc_error(-8, "Invalid parameter, sequence number is out of range", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': 0, 'sequence': -1}], {})
108
109        # Test `createrawtransaction` invalid `outputs`
110        address = self.nodes[0].getnewaddress()
111        address2 = self.nodes[0].getnewaddress()
112        assert_raises_rpc_error(-1, "JSON value is not an array as expected", self.nodes[0].createrawtransaction, [], 'foo')
113        self.nodes[0].createrawtransaction(inputs=[], outputs={})  # Should not throw for backwards compatibility
114        self.nodes[0].createrawtransaction(inputs=[], outputs=[])
115        assert_raises_rpc_error(-8, "Data must be hexadecimal string", self.nodes[0].createrawtransaction, [], {'data': 'foo'})
116        assert_raises_rpc_error(-5, "Invalid Bitcoin address", self.nodes[0].createrawtransaction, [], {'foo': 0})
117        assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].createrawtransaction, [], {address: 'foo'})
118        assert_raises_rpc_error(-3, "Amount out of range", self.nodes[0].createrawtransaction, [], {address: -1})
119        assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], multidict([(address, 1), (address, 1)]))
120        assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], [{address: 1}, {address: 1}])
121        assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], [{"data": 'aa'}, {"data": "bb"}])
122        assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], multidict([("data", 'aa'), ("data", "bb")]))
123        assert_raises_rpc_error(-8, "Invalid parameter, key-value pair must contain exactly one key", self.nodes[0].createrawtransaction, [], [{'a': 1, 'b': 2}])
124        assert_raises_rpc_error(-8, "Invalid parameter, key-value pair not an object as expected", self.nodes[0].createrawtransaction, [], [['key-value pair1'], ['2']])
125
126        # Test `createrawtransaction` invalid `locktime`
127        assert_raises_rpc_error(-3, "Expected type number", self.nodes[0].createrawtransaction, [], {}, 'foo')
128        assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, -1)
129        assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, 4294967296)
130
131        # Test `createrawtransaction` invalid `replaceable`
132        assert_raises_rpc_error(-3, "Expected type bool", self.nodes[0].createrawtransaction, [], {}, 0, 'foo')
133
134        self.log.info('Check that createrawtransaction accepts an array and object as outputs')
135        # One output
136        tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs={address: 99}))
137        assert_equal(len(tx.vout), 1)
138        assert_equal(
139            tx.serialize().hex(),
140            self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]),
141        )
142        # Two outputs
143        tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)])))
144        assert_equal(len(tx.vout), 2)
145        assert_equal(
146            tx.serialize().hex(),
147            self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}]),
148        )
149        # Multiple mixed outputs
150        tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=multidict([(address, 99), (address2, 99), ('data', '99')])))
151        assert_equal(len(tx.vout), 3)
152        assert_equal(
153            tx.serialize().hex(),
154            self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}, {'data': '99'}]),
155        )
156
157        for type in ["bech32", "p2sh-segwit", "legacy"]:
158            addr = self.nodes[0].getnewaddress("", type)
159            addrinfo = self.nodes[0].getaddressinfo(addr)
160            pubkey = addrinfo["scriptPubKey"]
161
162            self.log.info('sendrawtransaction with missing prevtx info (%s)' %(type))
163
164            # Test `signrawtransactionwithwallet` invalid `prevtxs`
165            inputs  = [ {'txid' : txid, 'vout' : 3, 'sequence' : 1000}]
166            outputs = { self.nodes[0].getnewaddress() : 1 }
167            rawtx   = self.nodes[0].createrawtransaction(inputs, outputs)
168
169            prevtx = dict(txid=txid, scriptPubKey=pubkey, vout=3, amount=1)
170            succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
171            assert succ["complete"]
172            if type == "legacy":
173                del prevtx["amount"]
174                succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
175                assert succ["complete"]
176
177            if type != "legacy":
178                assert_raises_rpc_error(-3, "Missing amount", self.nodes[0].signrawtransactionwithwallet, rawtx, [
179                    {
180                        "txid": txid,
181                        "scriptPubKey": pubkey,
182                        "vout": 3,
183                    }
184                ])
185
186            assert_raises_rpc_error(-3, "Missing vout", self.nodes[0].signrawtransactionwithwallet, rawtx, [
187                {
188                    "txid": txid,
189                    "scriptPubKey": pubkey,
190                    "amount": 1,
191                }
192            ])
193            assert_raises_rpc_error(-3, "Missing txid", self.nodes[0].signrawtransactionwithwallet, rawtx, [
194                {
195                    "scriptPubKey": pubkey,
196                    "vout": 3,
197                    "amount": 1,
198                }
199            ])
200            assert_raises_rpc_error(-3, "Missing scriptPubKey", self.nodes[0].signrawtransactionwithwallet, rawtx, [
201                {
202                    "txid": txid,
203                    "vout": 3,
204                    "amount": 1
205                }
206            ])
207
208        #########################################
209        # sendrawtransaction with missing input #
210        #########################################
211
212        self.log.info('sendrawtransaction with missing input')
213        inputs  = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1}] #won't exists
214        outputs = { self.nodes[0].getnewaddress() : 4.998 }
215        rawtx   = self.nodes[2].createrawtransaction(inputs, outputs)
216        rawtx   = self.nodes[2].signrawtransactionwithwallet(rawtx)
217
218        # This will raise an exception since there are missing inputs
219        assert_raises_rpc_error(-25, "bad-txns-inputs-missingorspent", self.nodes[2].sendrawtransaction, rawtx['hex'])
220
221        #####################################
222        # getrawtransaction with block hash #
223        #####################################
224
225        # make a tx by sending then generate 2 blocks; block1 has the tx in it
226        tx = self.nodes[2].sendtoaddress(self.nodes[1].getnewaddress(), 1)
227        block1, block2 = self.nodes[2].generate(2)
228        self.sync_all()
229        # We should be able to get the raw transaction by providing the correct block
230        gottx = self.nodes[0].getrawtransaction(tx, True, block1)
231        assert_equal(gottx['txid'], tx)
232        assert_equal(gottx['in_active_chain'], True)
233        # We should not have the 'in_active_chain' flag when we don't provide a block
234        gottx = self.nodes[0].getrawtransaction(tx, True)
235        assert_equal(gottx['txid'], tx)
236        assert 'in_active_chain' not in gottx
237        # We should not get the tx if we provide an unrelated block
238        assert_raises_rpc_error(-5, "No such transaction found", self.nodes[0].getrawtransaction, tx, True, block2)
239        # An invalid block hash should raise the correct errors
240        assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].getrawtransaction, tx, True, True)
241        assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 6, for 'foobar')", self.nodes[0].getrawtransaction, tx, True, "foobar")
242        assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 8, for 'abcd1234')", self.nodes[0].getrawtransaction, tx, True, "abcd1234")
243        assert_raises_rpc_error(-8, "parameter 3 must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[0].getrawtransaction, tx, True, "ZZZ0000000000000000000000000000000000000000000000000000000000000")
244        assert_raises_rpc_error(-5, "Block hash not found", self.nodes[0].getrawtransaction, tx, True, "0000000000000000000000000000000000000000000000000000000000000000")
245        # Undo the blocks and check in_active_chain
246        self.nodes[0].invalidateblock(block1)
247        gottx = self.nodes[0].getrawtransaction(txid=tx, verbose=True, blockhash=block1)
248        assert_equal(gottx['in_active_chain'], False)
249        self.nodes[0].reconsiderblock(block1)
250        assert_equal(self.nodes[0].getbestblockhash(), block2)
251
252        if not self.options.descriptors:
253            # The traditional multisig workflow does not work with descriptor wallets so these are legacy only.
254            # The multisig workflow with descriptor wallets uses PSBTs and is tested elsewhere, no need to do them here.
255            #########################
256            # RAW TX MULTISIG TESTS #
257            #########################
258            # 2of2 test
259            addr1 = self.nodes[2].getnewaddress()
260            addr2 = self.nodes[2].getnewaddress()
261
262            addr1Obj = self.nodes[2].getaddressinfo(addr1)
263            addr2Obj = self.nodes[2].getaddressinfo(addr2)
264
265            # Tests for createmultisig and addmultisigaddress
266            assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, ["01020304"])
267            self.nodes[0].createmultisig(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # createmultisig can only take public keys
268            assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 2, [addr1Obj['pubkey'], addr1]) # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here.
269
270            mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr1])['address']
271
272            #use balance deltas instead of absolute values
273            bal = self.nodes[2].getbalance()
274
275            # send 1.2 BTC to msig adr
276            txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
277            self.sync_all()
278            self.nodes[0].generate(1)
279            self.sync_all()
280            assert_equal(self.nodes[2].getbalance(), bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance
281
282
283            # 2of3 test from different nodes
284            bal = self.nodes[2].getbalance()
285            addr1 = self.nodes[1].getnewaddress()
286            addr2 = self.nodes[2].getnewaddress()
287            addr3 = self.nodes[2].getnewaddress()
288
289            addr1Obj = self.nodes[1].getaddressinfo(addr1)
290            addr2Obj = self.nodes[2].getaddressinfo(addr2)
291            addr3Obj = self.nodes[2].getaddressinfo(addr3)
292
293            mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])['address']
294
295            txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
296            decTx = self.nodes[0].gettransaction(txId)
297            rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
298            self.sync_all()
299            self.nodes[0].generate(1)
300            self.sync_all()
301
302            #THIS IS AN INCOMPLETE FEATURE
303            #NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
304            assert_equal(self.nodes[2].getbalance(), bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable
305
306            txDetails = self.nodes[0].gettransaction(txId, True)
307            rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
308            vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('2.20000000'))
309
310            bal = self.nodes[0].getbalance()
311            inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "amount" : vout['value']}]
312            outputs = { self.nodes[0].getnewaddress() : 2.19 }
313            rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
314            rawTxPartialSigned = self.nodes[1].signrawtransactionwithwallet(rawTx, inputs)
315            assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx
316
317            rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx, inputs)
318            assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys
319            self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
320            rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
321            self.sync_all()
322            self.nodes[0].generate(1)
323            self.sync_all()
324            assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
325
326            # 2of2 test for combining transactions
327            bal = self.nodes[2].getbalance()
328            addr1 = self.nodes[1].getnewaddress()
329            addr2 = self.nodes[2].getnewaddress()
330
331            addr1Obj = self.nodes[1].getaddressinfo(addr1)
332            addr2Obj = self.nodes[2].getaddressinfo(addr2)
333
334            self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
335            mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
336            mSigObjValid = self.nodes[2].getaddressinfo(mSigObj)
337
338            txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
339            decTx = self.nodes[0].gettransaction(txId)
340            rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
341            self.sync_all()
342            self.nodes[0].generate(1)
343            self.sync_all()
344
345            assert_equal(self.nodes[2].getbalance(), bal) # the funds of a 2of2 multisig tx should not be marked as spendable
346
347            txDetails = self.nodes[0].gettransaction(txId, True)
348            rawTx2 = self.nodes[0].decoderawtransaction(txDetails['hex'])
349            vout = next(o for o in rawTx2['vout'] if o['value'] == Decimal('2.20000000'))
350
351            bal = self.nodes[0].getbalance()
352            inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "redeemScript" : mSigObjValid['hex'], "amount" : vout['value']}]
353            outputs = { self.nodes[0].getnewaddress() : 2.19 }
354            rawTx2 = self.nodes[2].createrawtransaction(inputs, outputs)
355            rawTxPartialSigned1 = self.nodes[1].signrawtransactionwithwallet(rawTx2, inputs)
356            self.log.debug(rawTxPartialSigned1)
357            assert_equal(rawTxPartialSigned1['complete'], False) #node1 only has one key, can't comp. sign the tx
358
359            rawTxPartialSigned2 = self.nodes[2].signrawtransactionwithwallet(rawTx2, inputs)
360            self.log.debug(rawTxPartialSigned2)
361            assert_equal(rawTxPartialSigned2['complete'], False) #node2 only has one key, can't comp. sign the tx
362            rawTxComb = self.nodes[2].combinerawtransaction([rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex']])
363            self.log.debug(rawTxComb)
364            self.nodes[2].sendrawtransaction(rawTxComb)
365            rawTx2 = self.nodes[0].decoderawtransaction(rawTxComb)
366            self.sync_all()
367            self.nodes[0].generate(1)
368            self.sync_all()
369            assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
370
371        # decoderawtransaction tests
372        # witness transaction
373        encrawtx = "010000000001010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f50500000000000102616100000000"
374        decrawtx = self.nodes[0].decoderawtransaction(encrawtx, True) # decode as witness transaction
375        assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
376        assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # force decode as non-witness transaction
377        # non-witness transaction
378        encrawtx = "01000000010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f505000000000000000000"
379        decrawtx = self.nodes[0].decoderawtransaction(encrawtx, False) # decode as non-witness transaction
380        assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
381        # known ambiguous transaction in the chain (see https://github.com/bitcoin/bitcoin/issues/20579)
382        encrawtx = "020000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff4b03c68708046ff8415c622f4254432e434f4d2ffabe6d6de1965d02c68f928e5b244ab1965115a36f56eb997633c7f690124bbf43644e23080000000ca3d3af6d005a65ff0200fd00000000ffffffff03f4c1fb4b0000000016001497cfc76442fe717f2a3f0cc9c175f7561b6619970000000000000000266a24aa21a9ed957d1036a80343e0d1b659497e1b48a38ebe876a056d45965fac4a85cda84e1900000000000000002952534b424c4f434b3a8e092581ab01986cbadc84f4b43f4fa4bb9e7a2e2a0caf9b7cf64d939028e22c0120000000000000000000000000000000000000000000000000000000000000000000000000"
383        decrawtx = self.nodes[0].decoderawtransaction(encrawtx)
384        decrawtx_wit = self.nodes[0].decoderawtransaction(encrawtx, True)
385        assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # fails to decode as non-witness transaction
386        assert_equal(decrawtx, decrawtx_wit) # the witness interpretation should be chosen
387        assert_equal(decrawtx['vin'][0]['coinbase'], "03c68708046ff8415c622f4254432e434f4d2ffabe6d6de1965d02c68f928e5b244ab1965115a36f56eb997633c7f690124bbf43644e23080000000ca3d3af6d005a65ff0200fd00000000")
388
389        # Basic signrawtransaction test
390        addr = self.nodes[1].getnewaddress()
391        txid = self.nodes[0].sendtoaddress(addr, 10)
392        self.nodes[0].generate(1)
393        self.sync_all()
394        vout = find_vout_for_address(self.nodes[1], txid, addr)
395        rawTx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {self.nodes[1].getnewaddress(): 9.999})
396        rawTxSigned = self.nodes[1].signrawtransactionwithwallet(rawTx)
397        txId = self.nodes[1].sendrawtransaction(rawTxSigned['hex'])
398        self.nodes[0].generate(1)
399        self.sync_all()
400
401        # getrawtransaction tests
402        # 1. valid parameters - only supply txid
403        assert_equal(self.nodes[0].getrawtransaction(txId), rawTxSigned['hex'])
404
405        # 2. valid parameters - supply txid and 0 for non-verbose
406        assert_equal(self.nodes[0].getrawtransaction(txId, 0), rawTxSigned['hex'])
407
408        # 3. valid parameters - supply txid and False for non-verbose
409        assert_equal(self.nodes[0].getrawtransaction(txId, False), rawTxSigned['hex'])
410
411        # 4. valid parameters - supply txid and 1 for verbose.
412        # We only check the "hex" field of the output so we don't need to update this test every time the output format changes.
413        assert_equal(self.nodes[0].getrawtransaction(txId, 1)["hex"], rawTxSigned['hex'])
414
415        # 5. valid parameters - supply txid and True for non-verbose
416        assert_equal(self.nodes[0].getrawtransaction(txId, True)["hex"], rawTxSigned['hex'])
417
418        # 6. invalid parameters - supply txid and string "Flase"
419        assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, "Flase")
420
421        # 7. invalid parameters - supply txid and empty array
422        assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, [])
423
424        # 8. invalid parameters - supply txid and empty dict
425        assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, {})
426
427        inputs  = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 1000}]
428        outputs = { self.nodes[0].getnewaddress() : 1 }
429        rawtx   = self.nodes[0].createrawtransaction(inputs, outputs)
430        decrawtx= self.nodes[0].decoderawtransaction(rawtx)
431        assert_equal(decrawtx['vin'][0]['sequence'], 1000)
432
433        # 9. invalid parameters - sequence number out of range
434        inputs  = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : -1}]
435        outputs = { self.nodes[0].getnewaddress() : 1 }
436        assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
437
438        # 10. invalid parameters - sequence number out of range
439        inputs  = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967296}]
440        outputs = { self.nodes[0].getnewaddress() : 1 }
441        assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
442
443        inputs  = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967294}]
444        outputs = { self.nodes[0].getnewaddress() : 1 }
445        rawtx   = self.nodes[0].createrawtransaction(inputs, outputs)
446        decrawtx= self.nodes[0].decoderawtransaction(rawtx)
447        assert_equal(decrawtx['vin'][0]['sequence'], 4294967294)
448
449        ####################################
450        # TRANSACTION VERSION NUMBER TESTS #
451        ####################################
452
453        # Test the minimum transaction version number that fits in a signed 32-bit integer.
454        # As transaction version is unsigned, this should convert to its unsigned equivalent.
455        tx = CTransaction()
456        tx.nVersion = -0x80000000
457        rawtx = tx.serialize().hex()
458        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
459        assert_equal(decrawtx['version'], 0x80000000)
460
461        # Test the maximum transaction version number that fits in a signed 32-bit integer.
462        tx = CTransaction()
463        tx.nVersion = 0x7fffffff
464        rawtx = tx.serialize().hex()
465        decrawtx = self.nodes[0].decoderawtransaction(rawtx)
466        assert_equal(decrawtx['version'], 0x7fffffff)
467
468        self.log.info('sendrawtransaction/testmempoolaccept with maxfeerate')
469
470        # Test a transaction with a small fee.
471        txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
472        rawTx = self.nodes[0].getrawtransaction(txId, True)
473        vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
474
475        self.sync_all()
476        inputs = [{ "txid" : txId, "vout" : vout['n'] }]
477        # Fee 10,000 satoshis, (1 - (10000 sat * 0.00000001 BTC/sat)) = 0.9999
478        outputs = { self.nodes[0].getnewaddress() : Decimal("0.99990000") }
479        rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
480        rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
481        assert_equal(rawTxSigned['complete'], True)
482        # Fee 10,000 satoshis, ~100 b transaction, fee rate should land around 100 sat/byte = 0.00100000 BTC/kB
483        # Thus, testmempoolaccept should reject
484        testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']], 0.00001000)[0]
485        assert_equal(testres['allowed'], False)
486        assert_equal(testres['reject-reason'], 'max-fee-exceeded')
487        # and sendrawtransaction should throw
488        assert_raises_rpc_error(-25, 'Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)', self.nodes[2].sendrawtransaction, rawTxSigned['hex'], 0.00001000)
489        # and the following calls should both succeed
490        testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']])[0]
491        assert_equal(testres['allowed'], True)
492        self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'])
493
494        # Test a transaction with a large fee.
495        txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
496        rawTx = self.nodes[0].getrawtransaction(txId, True)
497        vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
498
499        self.sync_all()
500        inputs = [{ "txid" : txId, "vout" : vout['n'] }]
501        # Fee 2,000,000 satoshis, (1 - (2000000 sat * 0.00000001 BTC/sat)) = 0.98
502        outputs = { self.nodes[0].getnewaddress() : Decimal("0.98000000") }
503        rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
504        rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
505        assert_equal(rawTxSigned['complete'], True)
506        # Fee 2,000,000 satoshis, ~100 b transaction, fee rate should land around 20,000 sat/byte = 0.20000000 BTC/kB
507        # Thus, testmempoolaccept should reject
508        testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']])[0]
509        assert_equal(testres['allowed'], False)
510        assert_equal(testres['reject-reason'], 'max-fee-exceeded')
511        # and sendrawtransaction should throw
512        assert_raises_rpc_error(-25, 'Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)', self.nodes[2].sendrawtransaction, rawTxSigned['hex'])
513        # and the following calls should both succeed
514        testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']], maxfeerate='0.20000000')[0]
515        assert_equal(testres['allowed'], True)
516        self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'], maxfeerate='0.20000000')
517
518
519if __name__ == '__main__':
520    RawTransactionsTest().main()
521