Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2015-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test transaction signing using the signrawtransactionwithwallet RPC."""7from test_framework.blocktools import (8COINBASE_MATURITY,9)10from test_framework.address import (11script_to_p2wsh,12)13from test_framework.test_framework import BitcoinTestFramework14from test_framework.util import (15assert_equal,16assert_raises_rpc_error,17)18from test_framework.messages import (19CTxInWitness,20tx_from_hex,21)22from test_framework.script import (23CScript,24OP_CHECKLOCKTIMEVERIFY,25OP_CHECKSEQUENCEVERIFY,26OP_DROP,27OP_TRUE,28)30from decimal import (31Decimal,32getcontext,33)36RAW_TX = '020000000156b958f78e3f24e0b2f4e4db1255426b0902027cb37e3ddadb52e37c3557dddb0000000000ffffffff01c0a6b929010000001600149a2ee8c77140a053f36018ac8124a6ececc1668a00000000'39class SignRawTransactionWithWalletTest(BitcoinTestFramework):40def set_test_params(self):41self.setup_clean_chain = True42self.num_nodes = 244def skip_test_if_missing_module(self):45self.skip_if_no_wallet()47def test_with_lock_outputs(self):48self.log.info("Test correct error reporting when trying to sign a locked output")49self.nodes[0].encryptwallet("password")50assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signrawtransactionwithwallet, RAW_TX)51self.nodes[0].walletpassphrase("password", 9999)53def test_with_invalid_sighashtype(self):54self.log.info("Test signrawtransactionwithwallet raises if an invalid sighashtype is passed")55assert_raises_rpc_error(-8, "'all' is not a valid sighash parameter.", self.nodes[0].signrawtransactionwithwallet, hexstring=RAW_TX, sighashtype="all")57def script_verification_error_test(self):58"""Create and sign a raw transaction with valid (vin 0), invalid (vin 1) and one missing (vin 2) input script.60Expected results:623) The transaction has no complete set of signatures634) Two script verification errors occurred645) Script verification errors have certain properties ("txid", "vout", "scriptSig", "sequence", "error")656) The verification errors refer to the invalid (vin 1) and missing input (vin 2)"""66self.log.info("Test script verification errors")67privKeys = ['cUeKHd5orzT3mz8P9pxyREHfsWtVfgsfDjiZZBcjUBAaGk1BTj7N']69inputs = [70# Valid pay-to-pubkey script71{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},72# Invalid script73{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},74# Missing scriptPubKey75{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},76]78scripts = [79# Valid pay-to-pubkey script80{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,81'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},82# Invalid script83{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7,84'scriptPubKey': 'badbadbadbad'}85]87outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}89rawTx = self.nodes[0].createrawtransaction(inputs, outputs)91# Make sure decoderawtransaction is at least marginally sane92decodedRawTx = self.nodes[0].decoderawtransaction(rawTx)93for i, inp in enumerate(inputs):94assert_equal(decodedRawTx["vin"][i]["txid"], inp["txid"])95assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"])97# Make sure decoderawtransaction throws if there is extra data98assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decoderawtransaction, rawTx + "00")100rawTxSigned = self.nodes[0].signrawtransactionwithkey(rawTx, privKeys, scripts)102# 3) The transaction has no complete set of signatures103assert not rawTxSigned['complete']105# 4) Two script verification errors occurred106assert 'errors' in rawTxSigned107assert_equal(len(rawTxSigned['errors']), 2)109# 5) Script verification errors have certain properties110assert 'txid' in rawTxSigned['errors'][0]111assert 'vout' in rawTxSigned['errors'][0]112assert 'witness' in rawTxSigned['errors'][0]113assert 'scriptSig' in rawTxSigned['errors'][0]114assert 'sequence' in rawTxSigned['errors'][0]115assert 'error' in rawTxSigned['errors'][0]117# 6) The verification errors refer to the invalid (vin 1) and missing input (vin 2)118assert_equal(rawTxSigned['errors'][0]['txid'], inputs[1]['txid'])119assert_equal(rawTxSigned['errors'][0]['vout'], inputs[1]['vout'])120assert_equal(rawTxSigned['errors'][1]['txid'], inputs[2]['txid'])121assert_equal(rawTxSigned['errors'][1]['vout'], inputs[2]['vout'])122assert not rawTxSigned['errors'][0]['witness']124# Now test signing failure for transaction with input witnesses125p2wpkh_raw_tx = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000"127rawTxSigned = self.nodes[0].signrawtransactionwithwallet(p2wpkh_raw_tx)129# 7) The transaction has no complete set of signatures130assert not rawTxSigned['complete']132# 8) Two script verification errors occurred133assert 'errors' in rawTxSigned134assert_equal(len(rawTxSigned['errors']), 2)136# 9) Script verification errors have certain properties137assert 'txid' in rawTxSigned['errors'][0]138assert 'vout' in rawTxSigned['errors'][0]139assert 'witness' in rawTxSigned['errors'][0]140assert 'scriptSig' in rawTxSigned['errors'][0]141assert 'sequence' in rawTxSigned['errors'][0]142assert 'error' in rawTxSigned['errors'][0]144# Non-empty witness checked here145assert_equal(rawTxSigned['errors'][1]['witness'], ["304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee01", "025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357"])146assert not rawTxSigned['errors'][0]['witness']148def test_fully_signed_tx(self):149self.log.info("Test signing a fully signed transaction does nothing")150self.nodes[0].walletpassphrase("password", 9999)151self.generate(self.nodes[0], COINBASE_MATURITY + 1)152rawtx = self.nodes[0].createrawtransaction([], [{self.nodes[0].getnewaddress(): 10}])153fundedtx = self.nodes[0].fundrawtransaction(rawtx)154signedtx = self.nodes[0].signrawtransactionwithwallet(fundedtx["hex"])155assert_equal(signedtx["complete"], True)156signedtx2 = self.nodes[0].signrawtransactionwithwallet(signedtx["hex"])157assert_equal(signedtx2["complete"], True)158assert_equal(signedtx["hex"], signedtx2["hex"])159self.nodes[0].walletlock()161def OP_1NEGATE_test(self):162self.log.info("Test OP_1NEGATE (0x4f) satisfies BIP62 minimal push standardness rule")163hex_str = (164"0200000001FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"165"FFFFFFFF00000000044F024F9CFDFFFFFF01F0B9F5050000000023210277777777"166"77777777777777777777777777777777777777777777777777777777AC66030000"167)168prev_txs = [169{170"txid": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",171"vout": 0,172"scriptPubKey": "A914AE44AB6E9AA0B71F1CD2B453B69340E9BFBAEF6087",173"redeemScript": "4F9C",174"amount": 1,175}176]177txn = self.nodes[0].signrawtransactionwithwallet(hex_str, prev_txs)178assert txn["complete"]180def test_signing_with_csv(self):181self.log.info("Test signing a transaction containing a fully signed CSV input")182self.nodes[0].walletpassphrase("password", 9999)183getcontext().prec = 8185# Make sure CSV is active186assert self.nodes[0].getdeploymentinfo()['deployments']['csv']['active']188# Create a P2WSH script with CSV189script = CScript([1, OP_CHECKSEQUENCEVERIFY, OP_DROP])190address = script_to_p2wsh(script)192# Fund that address and make the spend193utxo1 = self.create_outpoints(self.nodes[0], outputs=[{address: 1}])[0]194self.generate(self.nodes[0], 1)195utxo2 = self.nodes[0].listunspent()[0]196amt = Decimal(1) + utxo2["amount"] - Decimal(0.00001)197tx = self.nodes[0].createrawtransaction(198[{**utxo1, "sequence": 1},{"txid": utxo2["txid"], "vout": utxo2["vout"]}],199[{self.nodes[0].getnewaddress(): amt}],200self.nodes[0].getblockcount()201)203# Set the witness script204ctx = tx_from_hex(tx)205ctx.wit.vtxinwit.append(CTxInWitness())206ctx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE]), script]207tx = ctx.serialize_with_witness().hex()209# Sign and send the transaction210signed = self.nodes[0].signrawtransactionwithwallet(tx)211assert_equal(signed["complete"], True)212self.nodes[0].sendrawtransaction(signed["hex"])214def test_signing_with_cltv(self):215self.log.info("Test signing a transaction containing a fully signed CLTV input")216self.nodes[0].walletpassphrase("password", 9999)217getcontext().prec = 8219# Make sure CLTV is active220assert self.nodes[0].getdeploymentinfo()['deployments']['bip65']['active']222# Create a P2WSH script with CLTV223script = CScript([100, OP_CHECKLOCKTIMEVERIFY, OP_DROP])224address = script_to_p2wsh(script)226# Fund that address and make the spend227utxo1 = self.create_outpoints(self.nodes[0], outputs=[{address: 1}])[0]228self.generate(self.nodes[0], 1)229utxo2 = self.nodes[0].listunspent()[0]230amt = Decimal(1) + utxo2["amount"] - Decimal(0.00001)231tx = self.nodes[0].createrawtransaction(232[utxo1, {"txid": utxo2["txid"], "vout": utxo2["vout"]}],233[{self.nodes[0].getnewaddress(): amt}],234self.nodes[0].getblockcount()235)237# Set the witness script238ctx = tx_from_hex(tx)239ctx.wit.vtxinwit.append(CTxInWitness())240ctx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE]), script]241tx = ctx.serialize_with_witness().hex()243# Sign and send the transaction244signed = self.nodes[0].signrawtransactionwithwallet(tx)245assert_equal(signed["complete"], True)246self.nodes[0].sendrawtransaction(signed["hex"])248def test_signing_with_missing_prevtx_info(self):249txid = "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000"250for type in ["bech32", "p2sh-segwit", "legacy"]:
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.