rpc_rawtransaction.py raw
1 #!/usr/bin/env python3
2 # Copyright (c) 2014-2022 The Limenka 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
7 Test the following RPCs:
8 - getrawtransaction
9 - createrawtransaction
10 - signrawtransactionwithwallet
11 - sendrawtransaction
12 - decoderawtransaction
13 """
14
15 from collections import OrderedDict
16 from decimal import Decimal
17 from itertools import product
18
19 from test_framework.messages import (
20 MAX_BIP125_RBF_SEQUENCE,
21 COIN,
22 CTransaction,
23 CTxOut,
24 tx_from_hex,
25 )
26 from test_framework.script import (
27 CScript,
28 OP_FALSE,
29 OP_INVALIDOPCODE,
30 OP_RETURN,
31 )
32 from test_framework.test_framework import LimenkaTestFramework
33 from test_framework.util import (
34 assert_equal,
35 assert_greater_than,
36 assert_raises_rpc_error,
37 )
38 from test_framework.wallet import (
39 getnewdestination,
40 MiniWallet,
41 )
42
43
44 TXID = "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000"
45
46
47 class multidict(dict):
48 """Dictionary that allows duplicate keys.
49
50 Constructed with a list of (key, value) tuples. When dumped by the json module,
51 will output invalid json with repeated keys, eg:
52 >>> json.dumps(multidict([(1,2),(1,2)])
53 '{"1": 2, "1": 2}'
54
55 Used to test calls to rpc methods with repeated keys in the json object."""
56
57 def __init__(self, x):
58 dict.__init__(self, x)
59 self.x = x
60
61 def items(self):
62 return self.x
63
64
65 class RawTransactionsTest(LimenkaTestFramework):
66 def add_options(self, parser):
67 self.add_wallet_options(parser, descriptors=False)
68
69 def set_test_params(self):
70 self.num_nodes = 3
71 self.extra_args = [
72 ["-txindex"],
73 ["-txindex"],
74 ["-fastprune", "-prune=1"],
75 ]
76 # whitelist peers to speed up tx relay / mempool sync
77 self.noban_tx_relay = True
78 self.supports_cli = False
79
80 def setup_network(self):
81 super().setup_network()
82 self.connect_nodes(0, 2)
83
84 def run_test(self):
85 self.wallet = MiniWallet(self.nodes[0])
86
87 self.getrawtransaction_tests()
88 self.createrawtransaction_tests()
89 self.sendrawtransaction_tests()
90 self.sendrawtransaction_testmempoolaccept_tests()
91 self.decoderawtransaction_tests()
92 self.transaction_version_number_tests()
93 if self.is_specified_wallet_compiled() and not self.options.descriptors:
94 self.import_deterministic_coinbase_privkeys()
95 self.raw_multisig_transaction_legacy_tests()
96 self.getrawtransaction_verbosity_tests()
97
98
99 def getrawtransaction_tests(self):
100 tx = self.wallet.send_self_transfer(from_node=self.nodes[0])
101 self.generate(self.nodes[0], 1)
102 txId = tx['txid']
103 err_msg = (
104 "No such mempool transaction. Use -txindex or provide a block hash to enable"
105 " blockchain transaction queries. Use gettransaction for wallet transactions."
106 )
107
108 for n in [0, 2]:
109 self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex")
110
111 if n == 0:
112 # With -txindex.
113 # 1. valid parameters - only supply txid
114 assert_equal(self.nodes[n].getrawtransaction(txId), tx['hex'])
115
116 # 2. valid parameters - supply txid and 0 for non-verbose
117 assert_equal(self.nodes[n].getrawtransaction(txId, 0), tx['hex'])
118
119 # 3. valid parameters - supply txid and False for non-verbose
120 assert_equal(self.nodes[n].getrawtransaction(txId, False), tx['hex'])
121
122 # 4. valid parameters - supply txid and 1 for verbose.
123 # We only check the "hex" field of the output so we don't need to update this test every time the output format changes.
124 assert_equal(self.nodes[n].getrawtransaction(txId, 1)["hex"], tx['hex'])
125 assert_equal(self.nodes[n].getrawtransaction(txId, 2)["hex"], tx['hex'])
126
127 # 5. valid parameters - supply txid and True for non-verbose
128 assert_equal(self.nodes[n].getrawtransaction(txId, True)["hex"], tx['hex'])
129 else:
130 # Without -txindex, expect to raise.
131 for verbose in [None, 0, False, 1, True]:
132 assert_raises_rpc_error(-5, err_msg, self.nodes[n].getrawtransaction, txId, verbose)
133
134 # 6. invalid parameters - supply txid and invalid boolean values (strings) for verbose
135 for value in ["True", "False"]:
136 assert_raises_rpc_error(-3, "not of expected type number", self.nodes[n].getrawtransaction, txid=txId, verbose=value)
137 assert_raises_rpc_error(-3, "not of expected type number", self.nodes[n].getrawtransaction, txid=txId, verbosity=value)
138
139 # 7. invalid parameters - supply txid and empty array
140 assert_raises_rpc_error(-3, "not of expected type number", self.nodes[n].getrawtransaction, txId, [])
141
142 # 8. invalid parameters - supply txid and empty dict
143 assert_raises_rpc_error(-3, "not of expected type number", self.nodes[n].getrawtransaction, txId, {})
144
145 # Make a tx by sending, then generate 2 blocks; block1 has the tx in it
146 tx = self.wallet.send_self_transfer(from_node=self.nodes[2])['txid']
147 block1, block2 = self.generate(self.nodes[2], 2)
148 for n in [0, 2]:
149 self.log.info(f"Test getrawtransaction {'with' if n == 0 else 'without'} -txindex, with blockhash")
150 # We should be able to get the raw transaction by providing the correct block
151 gottx = self.nodes[n].getrawtransaction(txid=tx, verbose=True, blockhash=block1)
152 assert_equal(gottx['txid'], tx)
153 assert_equal(gottx['in_active_chain'], True)
154 if n == 0:
155 self.log.info("Test getrawtransaction with -txindex, without blockhash: 'in_active_chain' should be absent")
156 for v in [1,2]:
157 gottx = self.nodes[n].getrawtransaction(txid=tx, verbosity=v)
158 assert_equal(gottx['txid'], tx)
159 assert 'in_active_chain' not in gottx
160 else:
161 self.log.info("Test getrawtransaction without -txindex, without blockhash: expect the call to raise")
162 assert_raises_rpc_error(-5, err_msg, self.nodes[n].getrawtransaction, txid=tx, verbose=True)
163 # We should not get the tx if we provide an unrelated block
164 assert_raises_rpc_error(-5, "No such transaction found", self.nodes[n].getrawtransaction, txid=tx, blockhash=block2)
165 # An invalid block hash should raise the correct errors
166 assert_raises_rpc_error(-3, "JSON value of type bool is not of expected type string", self.nodes[n].getrawtransaction, txid=tx, blockhash=True)
167 assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 6, for 'foobar')", self.nodes[n].getrawtransaction, txid=tx, blockhash="foobar")
168 assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 8, for 'abcd1234')", self.nodes[n].getrawtransaction, txid=tx, blockhash="abcd1234")
169 foo = "ZZZ0000000000000000000000000000000000000000000000000000000000000"
170 assert_raises_rpc_error(-8, f"parameter 3 must be hexadecimal string (not '{foo}')", self.nodes[n].getrawtransaction, txid=tx, blockhash=foo)
171 bar = "0000000000000000000000000000000000000000000000000000000000000000"
172 assert_raises_rpc_error(-5, "Block hash not found", self.nodes[n].getrawtransaction, txid=tx, blockhash=bar)
173 # Undo the blocks and verify that "in_active_chain" is false.
174 self.nodes[n].invalidateblock(block1)
175 gottx = self.nodes[n].getrawtransaction(txid=tx, verbose=True, blockhash=block1)
176 assert_equal(gottx['in_active_chain'], False)
177 self.nodes[n].reconsiderblock(block1)
178 assert_equal(self.nodes[n].getbestblockhash(), block2)
179
180 self.log.info("Test getrawtransaction on genesis block coinbase returns an error")
181 block = self.nodes[0].getblock(self.nodes[0].getblockhash(0))
182 assert_raises_rpc_error(-5, "The genesis block coinbase is not considered an ordinary transaction", self.nodes[0].getrawtransaction, block['merkleroot'])
183
184 def getrawtransaction_verbosity_tests(self):
185 tx = self.wallet.send_self_transfer(from_node=self.nodes[1])['txid']
186 [block1] = self.generate(self.nodes[1], 1)
187 fields = [
188 'blockhash',
189 'blocktime',
190 'confirmations',
191 'hash',
192 'hex',
193 'in_active_chain',
194 'locktime',
195 'size',
196 'time',
197 'txid',
198 'vin',
199 'vout',
200 'vsize',
201 'weight',
202 ]
203 prevout_fields = [
204 'generated',
205 'height',
206 'value',
207 'scriptPubKey',
208 ]
209 script_pub_key_fields = [
210 'address',
211 'asm',
212 'hex',
213 'type',
214 ]
215 # node 0 & 2 with verbosity 1 & 2
216 for n, v in product([0, 2], [1, 2]):
217 self.log.info(f"Test getrawtransaction_verbosity {v} {'with' if n == 0 else 'without'} -txindex, with blockhash")
218 gottx = self.nodes[n].getrawtransaction(txid=tx, verbosity=v, blockhash=block1)
219 missing_fields = set(fields).difference(gottx.keys())
220 if missing_fields:
221 raise AssertionError(f"fields {', '.join(missing_fields)} are not in transaction")
222
223 assert len(gottx['vin']) > 0
224 if v == 1:
225 assert 'fee' not in gottx
226 assert 'prevout' not in gottx['vin'][0]
227 if v == 2:
228 assert isinstance(gottx['fee'], Decimal)
229 assert 'prevout' in gottx['vin'][0]
230 prevout = gottx['vin'][0]['prevout']
231 script_pub_key = prevout['scriptPubKey']
232
233 missing_fields = set(prevout_fields).difference(prevout.keys())
234 if missing_fields:
235 raise AssertionError(f"fields {', '.join(missing_fields)} are not in transaction")
236
237 missing_fields = set(script_pub_key_fields).difference(script_pub_key.keys())
238 if missing_fields:
239 raise AssertionError(f"fields {', '.join(missing_fields)} are not in transaction")
240
241 # check verbosity 2 without blockhash but with txindex
242 assert 'fee' in self.nodes[0].getrawtransaction(txid=tx, verbosity=2)
243 # check that coinbase has no fee or does not throw any errors for verbosity 2
244 coin_base = self.nodes[1].getblock(block1)['tx'][0]
245 gottx = self.nodes[1].getrawtransaction(txid=coin_base, verbosity=2, blockhash=block1)
246 assert 'fee' not in gottx
247 # check that verbosity 2 for a mempool tx will fallback to verbosity 1
248 # Do this with a pruned chain, as a regression test for https://github.com/limenka/limenka/pull/29003
249 self.generate(self.nodes[2], 400)
250 assert_greater_than(self.nodes[2].pruneblockchain(250), 0)
251 mempool_tx = self.wallet.send_self_transfer(from_node=self.nodes[2])['txid']
252 gottx = self.nodes[2].getrawtransaction(txid=mempool_tx, verbosity=2)
253 assert 'fee' not in gottx
254
255 def createrawtransaction_tests(self):
256 self.log.info("Test createrawtransaction")
257 # Test `createrawtransaction` required parameters
258 assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction)
259 assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [])
260
261 # Test `createrawtransaction` invalid extra parameters
262 assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [], {}, 0, False, 'foo')
263
264 # Test `createrawtransaction` invalid `inputs`
265 assert_raises_rpc_error(-3, "JSON value of type string is not of expected type array", self.nodes[0].createrawtransaction, 'foo', {})
266 assert_raises_rpc_error(-3, "JSON value of type string is not of expected type object", self.nodes[0].createrawtransaction, ['foo'], {})
267 assert_raises_rpc_error(-3, "JSON value of type null is not of expected type string", self.nodes[0].createrawtransaction, [{}], {})
268 assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].createrawtransaction, [{'txid': 'foo'}], {})
269 txid = "ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844"
270 assert_raises_rpc_error(-8, f"txid must be hexadecimal string (not '{txid}')", self.nodes[0].createrawtransaction, [{'txid': txid}], {})
271 assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': TXID}], {})
272 assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': TXID, 'vout': 'foo'}], {})
273 assert_raises_rpc_error(-8, "Invalid parameter, vout cannot be negative", self.nodes[0].createrawtransaction, [{'txid': TXID, 'vout': -1}], {})
274 # sequence number out of range
275 for invalid_seq in [-1, 4294967296]:
276 inputs = [{'txid': TXID, 'vout': 1, 'sequence': invalid_seq}]
277 address = getnewdestination()[2]
278 outputs = {address: 1}
279 assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range',
280 self.nodes[0].createrawtransaction, inputs, outputs)
281 # with valid sequence number
282 for valid_seq in [1000, 4294967294]:
283 inputs = [{'txid': TXID, 'vout': 1, 'sequence': valid_seq}]
284 address = getnewdestination()[2]
285 outputs = {address: 1}
286 rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
287 decrawtx = self.nodes[0].decoderawtransaction(rawtx)
288 assert_equal(decrawtx['vin'][0]['sequence'], valid_seq)
289
290 # Test `createrawtransaction` invalid `outputs`
291 address = getnewdestination()[2]
292 assert_raises_rpc_error(-3, "JSON value of type string is not of expected type array", self.nodes[0].createrawtransaction, [], 'foo')
293 self.nodes[0].createrawtransaction(inputs=[], outputs={}) # Should not throw for backwards compatibility
294 self.nodes[0].createrawtransaction(inputs=[], outputs=[])
295 assert_raises_rpc_error(-8, "Data must be hexadecimal string", self.nodes[0].createrawtransaction, [], {'data': 'foo'})
296 assert_raises_rpc_error(-5, "Invalid Limenka address", self.nodes[0].createrawtransaction, [], {'foo': 0})
297 assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].createrawtransaction, [], {address: 'foo'})
298 assert_raises_rpc_error(-3, "Amount out of range", self.nodes[0].createrawtransaction, [], {address: -1})
299 assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], multidict([(address, 1), (address, 1)]))
300 assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], [{address: 1}, {address: 1}])
301 assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], [{"data": 'aa'}, {"data": "bb"}])
302 assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], multidict([("data", 'aa'), ("data", "bb")]))
303 assert_raises_rpc_error(-8, "Invalid parameter, key-value pair must contain exactly one key", self.nodes[0].createrawtransaction, [], [{'a': 1, 'b': 2}])
304 assert_raises_rpc_error(-8, "Invalid parameter, key-value pair not an object as expected", self.nodes[0].createrawtransaction, [], [['key-value pair1'], ['2']])
305
306 # Test `createrawtransaction` mismatch between sequence number(s) and `replaceable` option
307 assert_raises_rpc_error(-8, "Invalid parameter combination: Sequence number(s) contradict replaceable option",
308 self.nodes[0].createrawtransaction, [{'txid': TXID, 'vout': 0, 'sequence': MAX_BIP125_RBF_SEQUENCE+1}], {}, 0, True)
309
310 # Test `createrawtransaction` invalid `locktime`
311 assert_raises_rpc_error(-3, "JSON value of type string is not of expected type number", self.nodes[0].createrawtransaction, [], {}, 'foo')
312 assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, -1)
313 assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, 4294967296)
314
315 # Test `createrawtransaction` invalid `replaceable`
316 assert_raises_rpc_error(-3, "JSON value of type string is not of expected type bool", self.nodes[0].createrawtransaction, [], {}, 0, 'foo')
317
318 # Test that createrawtransaction accepts an array and object as outputs
319 # One output
320 tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs={address: 99}))
321 assert_equal(len(tx.vout), 1)
322 assert_equal(
323 tx.serialize().hex(),
324 self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=[{address: 99}]),
325 )
326 # Two outputs
327 address2 = getnewdestination()[2]
328 tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)])))
329 assert_equal(len(tx.vout), 2)
330 assert_equal(
331 tx.serialize().hex(),
332 self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=[{address: 99}, {address2: 99}]),
333 )
334 # Multiple mixed outputs
335 tx = tx_from_hex(self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=multidict([(address, 99), (address2, 99), ('data', '99')])))
336 assert_equal(len(tx.vout), 3)
337 assert_equal(
338 tx.serialize().hex(),
339 self.nodes[2].createrawtransaction(inputs=[{'txid': TXID, 'vout': 9}], outputs=[{address: 99}, {address2: 99}, {'data': '99'}]),
340 )
341
342 def sendrawtransaction_tests(self):
343 self.log.info("Test sendrawtransaction with missing input")
344 inputs = [{'txid': TXID, 'vout': 1}] # won't exist
345 address = getnewdestination()[2]
346 outputs = {address: 4.998}
347 rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
348 assert_raises_rpc_error(-25, "bad-txns-inputs-missingorspent", self.nodes[2].sendrawtransaction, rawtx)
349
350 self.log.info("Test sendrawtransaction exceeding, falling short of, and equaling maxburnamount")
351 max_burn_exceeded = "Unspendable output exceeds maximum configured by user (maxburnamount)"
352
353
354 # Test that spendable transaction with default maxburnamount (0) gets sent
355 tx = self.wallet.create_self_transfer()['tx']
356 tx_hex = tx.serialize().hex()
357 self.nodes[2].sendrawtransaction(hexstring=tx_hex)
358
359 # Test that datacarrier transaction with default maxburnamount (0) does not get sent
360 tx = self.wallet.create_self_transfer()['tx']
361 tx_val = 0.001
362 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_RETURN] + [OP_FALSE] * 30))]
363 tx_hex = tx.serialize().hex()
364 assert_raises_rpc_error(-25, max_burn_exceeded, self.nodes[2].sendrawtransaction, tx_hex)
365
366 # Test that oversized script gets rejected by sendrawtransaction
367 tx = self.wallet.create_self_transfer()['tx']
368 tx_val = 0.001
369 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_FALSE] * 10001))]
370 tx_hex = tx.serialize().hex()
371 assert_raises_rpc_error(-25, max_burn_exceeded, self.nodes[2].sendrawtransaction, tx_hex)
372
373 # Test that script containing invalid opcode gets rejected by sendrawtransaction
374 tx = self.wallet.create_self_transfer()['tx']
375 tx_val = 0.01
376 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_INVALIDOPCODE]))]
377 tx_hex = tx.serialize().hex()
378 assert_raises_rpc_error(-25, max_burn_exceeded, self.nodes[2].sendrawtransaction, tx_hex)
379
380 # Test a transaction where our burn exceeds maxburnamount
381 tx = self.wallet.create_self_transfer()['tx']
382 tx_val = 0.001
383 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_RETURN] + [OP_FALSE] * 30))]
384 tx_hex = tx.serialize().hex()
385 assert_raises_rpc_error(-25, max_burn_exceeded, self.nodes[2].sendrawtransaction, tx_hex, 0, 0.0009)
386
387 # Test a transaction where our burn falls short of maxburnamount
388 tx = self.wallet.create_self_transfer()['tx']
389 tx_val = 0.001
390 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_RETURN] + [OP_FALSE] * 30))]
391 tx_hex = tx.serialize().hex()
392 self.nodes[2].sendrawtransaction(hexstring=tx_hex, maxfeerate='0', maxburnamount='0.0011')
393
394 # Test a transaction where our burn equals maxburnamount
395 tx = self.wallet.create_self_transfer()['tx']
396 tx_val = 0.001
397 tx.vout = [CTxOut(int(Decimal(tx_val) * COIN), CScript([OP_RETURN] + [OP_FALSE] * 30))]
398 tx_hex = tx.serialize().hex()
399 self.nodes[2].sendrawtransaction(hexstring=tx_hex, maxfeerate='0', maxburnamount='0.001')
400
401 def sendrawtransaction_testmempoolaccept_tests(self):
402 self.log.info("Test sendrawtransaction/testmempoolaccept with maxfeerate")
403 fee_exceeds_max = "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)"
404
405 # Test a transaction with a small fee.
406 # Fee rate is 0.00100000 BTC/kvB
407 tx = self.wallet.create_self_transfer(fee_rate=Decimal('0.00100000'))
408 # Thus, testmempoolaccept should reject
409 testres = self.nodes[2].testmempoolaccept([tx['hex']], 0.00001000)[0]
410 assert_equal(testres['allowed'], False)
411 assert_equal(testres['reject-reason'], 'max-fee-exceeded')
412 testres = self.nodes[2].testmempoolaccept([tx['hex']], 0.00001000, ['foobar'])[0]
413 assert_equal(testres['allowed'], False)
414 assert_equal(testres['reject-reason'], 'max-fee-exceeded')
415 # unless ignored explicitly
416 testres = self.nodes[2].testmempoolaccept([tx['hex']], 0.00001000, ['max-fee-exceeded'])[0]
417 assert_equal(testres['allowed'], True)
418 assert('reject-reason' not in testres)
419 testres = self.nodes[2].testmempoolaccept([tx['hex']], 0.00001000, ['absurdly-high-fee'])[0]
420 assert_equal(testres['allowed'], True)
421 assert('reject-reason' not in testres)
422 # and sendrawtransaction should throw
423 assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, tx['hex'], 0.00001000)
424 # and the following calls should both succeed
425 testres = self.nodes[2].testmempoolaccept(rawtxs=[tx['hex']])[0]
426 assert_equal(testres['allowed'], True)
427 self.nodes[2].sendrawtransaction(hexstring=tx['hex'], maxfeerate=0.00001000, ignore_rejects=['max-fee-exceeded'])
428
429 # Test a transaction with a large fee.
430 # Fee rate is 0.20000000 BTC/kvB
431 tx = self.wallet.create_self_transfer(fee_rate=Decimal("0.20000000"))
432 # Thus, testmempoolaccept should reject
433 testres = self.nodes[2].testmempoolaccept([tx['hex']])[0]
434 assert_equal(testres['allowed'], False)
435 assert_equal(testres['reject-reason'], 'max-fee-exceeded')
436 # and sendrawtransaction should throw
437 assert_raises_rpc_error(-25, fee_exceeds_max, self.nodes[2].sendrawtransaction, tx['hex'])
438 # and the following calls should both succeed
439 testres = self.nodes[2].testmempoolaccept(rawtxs=[tx['hex']], maxfeerate='0.20000000')[0]
440 assert_equal(testres['allowed'], True)
441 self.nodes[2].sendrawtransaction(hexstring=tx['hex'], maxfeerate='0.20000000')
442
443 self.log.info("Test sendrawtransaction/testmempoolaccept with tx outputs already in the utxo set")
444 self.generate(self.nodes[2], 1)
445 for node in self.nodes:
446 testres = node.testmempoolaccept([tx['hex']])[0]
447 assert_equal(testres['allowed'], False)
448 assert_equal(testres['reject-reason'], 'txn-already-known')
449 assert_raises_rpc_error(-27, 'Transaction outputs already in utxo set', node.sendrawtransaction, tx['hex'])
450
451 def decoderawtransaction_tests(self):
452 self.log.info("Test decoderawtransaction")
453 # witness transaction
454 encrawtx = "010000000001010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f50500000000000102616100000000"
455 decrawtx = self.nodes[0].decoderawtransaction(encrawtx, True) # decode as witness transaction
456 assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
457 assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # force decode as non-witness transaction
458 # non-witness transaction
459 encrawtx = "01000000010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f505000000000000000000"
460 decrawtx = self.nodes[0].decoderawtransaction(encrawtx, False) # decode as non-witness transaction
461 assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
462 # known ambiguous transaction in the chain (see https://github.com/limenka/limenka/issues/20579)
463 coinbase = "03c68708046ff8415c622f4254432e434f4d2ffabe6d6de1965d02c68f928e5b244ab1965115a36f56eb997633c7f690124bbf43644e23080000000ca3d3af6d005a65ff0200fd00000000"
464 encrawtx = f"020000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff4b{coinbase}" \
465 "ffffffff03f4c1fb4b0000000016001497cfc76442fe717f2a3f0cc9c175f7561b6619970000000000000000266a24aa21a9ed957d1036a80343e0d1b659497e1b48a38ebe876a056d45965fac4a85cda84e1900000000000000002952534b424c4f434b3a8e092581ab01986cbadc84f4b43f4fa4bb9e7a2e2a0caf9b7cf64d939028e22c0120000000000000000000000000000000000000000000000000000000000000000000000000"
466 decrawtx = self.nodes[0].decoderawtransaction(encrawtx)
467 decrawtx_wit = self.nodes[0].decoderawtransaction(encrawtx, True)
468 assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # fails to decode as non-witness transaction
469 assert_equal(decrawtx, decrawtx_wit) # the witness interpretation should be chosen
470 assert_equal(decrawtx['vin'][0]['coinbase'], coinbase)
471
472 def transaction_version_number_tests(self):
473 self.log.info("Test transaction version numbers")
474
475 # Test the minimum transaction version number that fits in a signed 32-bit integer.
476 # As transaction version is serialized unsigned, this should convert to its unsigned equivalent.
477 tx = CTransaction()
478 tx.version = 0x80000000
479 rawtx = tx.serialize().hex()
480 decrawtx = self.nodes[0].decoderawtransaction(rawtx)
481 assert_equal(decrawtx['version'], 0x80000000)
482
483 # Test the maximum transaction version number that fits in a signed 32-bit integer.
484 tx = CTransaction()
485 tx.version = 0x7fffffff
486 rawtx = tx.serialize().hex()
487 decrawtx = self.nodes[0].decoderawtransaction(rawtx)
488 assert_equal(decrawtx['version'], 0x7fffffff)
489
490 # Test the minimum transaction version number that fits in an unsigned 32-bit integer.
491 tx = CTransaction()
492 tx.version = 0
493 rawtx = tx.serialize().hex()
494 decrawtx = self.nodes[0].decoderawtransaction(rawtx)
495 assert_equal(decrawtx['version'], 0)
496
497 # Test the maximum transaction version number that fits in an unsigned 32-bit integer.
498 tx = CTransaction()
499 tx.version = 0xffffffff
500 rawtx = tx.serialize().hex()
501 decrawtx = self.nodes[0].decoderawtransaction(rawtx)
502 assert_equal(decrawtx['version'], 0xffffffff)
503
504 def raw_multisig_transaction_legacy_tests(self):
505 self.log.info("Test raw multisig transactions (legacy)")
506 # The traditional multisig workflow does not work with descriptor wallets so these are legacy only.
507 # The multisig workflow with descriptor wallets uses PSBTs and is tested elsewhere, no need to do them here.
508
509 # 2of2 test
510 addr1 = self.nodes[2].getnewaddress()
511 addr2 = self.nodes[2].getnewaddress()
512
513 addr1Obj = self.nodes[2].getaddressinfo(addr1)
514 addr2Obj = self.nodes[2].getaddressinfo(addr2)
515
516 # Tests for createmultisig and addmultisigaddress
517 assert_raises_rpc_error(-5, 'Pubkey "01020304" must have a length of either 33 or 65 bytes', self.nodes[0].createmultisig, 1, ["01020304"])
518 # createmultisig can only take public keys
519 self.nodes[0].createmultisig(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
520 # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here
521 assert_raises_rpc_error(-5, f'Pubkey "{addr1}" must be a hex string', self.nodes[0].createmultisig, 2, [addr1Obj['pubkey'], addr1])
522
523 mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr1])['address']
524
525 # use balance deltas instead of absolute values
526 bal = self.nodes[2].getbalance()
527
528 # send 1.2 BTC to msig adr
529 txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
530 self.sync_all()
531 self.generate(self.nodes[0], 1)
532 # node2 has both keys of the 2of2 ms addr, tx should affect the balance
533 assert_equal(self.nodes[2].getbalance(), bal + Decimal('1.20000000'))
534
535
536 # 2of3 test from different nodes
537 bal = self.nodes[2].getbalance()
538 addr1 = self.nodes[1].getnewaddress()
539 addr2 = self.nodes[2].getnewaddress()
540 addr3 = self.nodes[2].getnewaddress()
541
542 addr1Obj = self.nodes[1].getaddressinfo(addr1)
543 addr2Obj = self.nodes[2].getaddressinfo(addr2)
544 addr3Obj = self.nodes[2].getaddressinfo(addr3)
545
546 mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])['address']
547
548 txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
549 decTx = self.nodes[0].gettransaction(txId)
550 rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
551 self.sync_all()
552 self.generate(self.nodes[0], 1)
553
554 # THIS IS AN INCOMPLETE FEATURE
555 # NODE2 HAS TWO OF THREE KEYS AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
556 assert_equal(self.nodes[2].getbalance(), bal) # for now, assume the funds of a 2of3 multisig tx are not marked as spendable
557
558 txDetails = self.nodes[0].gettransaction(txId, True)
559 rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
560 vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('2.20000000'))
561
562 bal = self.nodes[0].getbalance()
563 inputs = [{"txid": txId, "vout": vout['n'], "scriptPubKey": vout['scriptPubKey']['hex'], "amount": vout['value']}]
564 outputs = {self.nodes[0].getnewaddress(): 2.19}
565 rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
566 rawTxPartialSigned = self.nodes[1].signrawtransactionwithwallet(rawTx, inputs)
567 assert_equal(rawTxPartialSigned['complete'], False) # node1 only has one key, can't comp. sign the tx
568
569 rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx, inputs)
570 assert_equal(rawTxSigned['complete'], True) # node2 can sign the tx compl., own two of three keys
571 self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
572 rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
573 self.sync_all()
574 self.generate(self.nodes[0], 1)
575 assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx
576
577 # 2of2 test for combining transactions
578 bal = self.nodes[2].getbalance()
579 addr1 = self.nodes[1].getnewaddress()
580 addr2 = self.nodes[2].getnewaddress()
581
582 addr1Obj = self.nodes[1].getaddressinfo(addr1)
583 addr2Obj = self.nodes[2].getaddressinfo(addr2)
584
585 self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
586 mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
587 mSigObjValid = self.nodes[2].getaddressinfo(mSigObj)
588
589 txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
590 decTx = self.nodes[0].gettransaction(txId)
591 rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
592 self.sync_all()
593 self.generate(self.nodes[0], 1)
594
595 assert_equal(self.nodes[2].getbalance(), bal) # the funds of a 2of2 multisig tx should not be marked as spendable
596
597 txDetails = self.nodes[0].gettransaction(txId, True)
598 rawTx2 = self.nodes[0].decoderawtransaction(txDetails['hex'])
599 vout = next(o for o in rawTx2['vout'] if o['value'] == Decimal('2.20000000'))
600
601 bal = self.nodes[0].getbalance()
602 inputs = [{"txid": txId, "vout": vout['n'], "scriptPubKey": vout['scriptPubKey']['hex'], "redeemScript": mSigObjValid['hex'], "amount": vout['value']}]
603 outputs = {self.nodes[0].getnewaddress(): 2.19}
604 rawTx2 = self.nodes[2].createrawtransaction(inputs, outputs)
605 rawTxPartialSigned1 = self.nodes[1].signrawtransactionwithwallet(rawTx2, inputs)
606 self.log.debug(rawTxPartialSigned1)
607 assert_equal(rawTxPartialSigned1['complete'], False) # node1 only has one key, can't comp. sign the tx
608
609 rawTxPartialSigned2 = self.nodes[2].signrawtransactionwithwallet(rawTx2, inputs)
610 self.log.debug(rawTxPartialSigned2)
611 assert_equal(rawTxPartialSigned2['complete'], False) # node2 only has one key, can't comp. sign the tx
612 assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].combinerawtransaction, [rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex'] + "00"])
613 assert_raises_rpc_error(-22, "Missing transactions", self.nodes[0].combinerawtransaction, [])
614 rawTxComb = self.nodes[2].combinerawtransaction([rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex']])
615 self.log.debug(rawTxComb)
616 self.nodes[2].sendrawtransaction(rawTxComb)
617 rawTx2 = self.nodes[0].decoderawtransaction(rawTxComb)
618 self.sync_all()
619 self.generate(self.nodes[0], 1)
620 assert_equal(self.nodes[0].getbalance(), bal + Decimal('50.00000000') + Decimal('2.19000000')) # block reward + tx
621 assert_raises_rpc_error(-25, "Input not found or already spent", self.nodes[0].combinerawtransaction, [rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex']])
622
623
624 if __name__ == '__main__':
625 RawTransactionsTest(__file__).main()
626