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) 2018-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"""Useful util functions for testing the wallet"""6from collections import namedtuple7import unittest9from test_framework.address import (10byte_to_base58,11key_to_p2pkh,12key_to_p2sh_p2wpkh,13key_to_p2wpkh,14)15from test_framework.key import ECKey16from test_framework.messages import (17CTxIn,18CTxInWitness,19WITNESS_SCALE_FACTOR,20)21from test_framework.script_util import (22key_to_p2pkh_script,23key_to_p2wpkh_script,24script_to_p2sh_script,25)28Key = namedtuple('Key', ['privkey',29'pubkey',30'p2pkh_script',31'p2pkh_addr',32'p2wpkh_script',33'p2wpkh_addr',34'p2sh_p2wpkh_script',35'p2sh_p2wpkh_redeem_script',36'p2sh_p2wpkh_addr'])39def get_generate_key():40"""Generate a fresh key42Returns a named tuple of privkey, pubkey and all address and scripts."""43privkey, pubkey = generate_keypair(wif=True)44return Key(privkey=privkey,45pubkey=pubkey.hex(),46p2pkh_script=key_to_p2pkh_script(pubkey).hex(),47p2pkh_addr=key_to_p2pkh(pubkey),48p2wpkh_script=key_to_p2wpkh_script(pubkey).hex(),49p2wpkh_addr=key_to_p2wpkh(pubkey),50p2sh_p2wpkh_script=script_to_p2sh_script(key_to_p2wpkh_script(pubkey)).hex(),51p2sh_p2wpkh_redeem_script=key_to_p2wpkh_script(pubkey).hex(),52p2sh_p2wpkh_addr=key_to_p2sh_p2wpkh(pubkey))55def test_address(node, address, **kwargs):56"""Get address info for `address` and test whether the returned values are as expected."""57addr_info = node.getaddressinfo(address)58for key, value in kwargs.items():59if value is None:60if key in addr_info.keys():61raise AssertionError("key {} unexpectedly returned in getaddressinfo.".format(key))62elif addr_info[key] != value:63raise AssertionError("key {} value {} did not match expected value {}".format(key, addr_info[key], value))65def bytes_to_wif(b, compressed=True):66if compressed:67b += b'\x01'68return byte_to_base58(b, 239)70def generate_keypair(compressed=True, wif=False):71"""Generate a new random keypair and return the corresponding ECKey /72bytes objects. The private key can also be provided as WIF (wallet73import format) string instead, which is often useful for wallet RPC74interaction."""75privkey = ECKey()76privkey.generate(compressed)77pubkey = privkey.get_pubkey().get_bytes()78if wif:79privkey = bytes_to_wif(privkey.get_bytes(), compressed)80return privkey, pubkey82def calculate_input_weight(scriptsig_hex, witness_stack_hex=None):83"""Given a scriptSig and a list of witness stack items for an input in hex format,84calculate the total input weight. If the input has no witness data,85`witness_stack_hex` can be set to None."""86tx_in = CTxIn(scriptSig=bytes.fromhex(scriptsig_hex))87witness_size = 088if witness_stack_hex is not None:89tx_inwit = CTxInWitness()90for witness_item_hex in witness_stack_hex:91tx_inwit.scriptWitness.stack.append(bytes.fromhex(witness_item_hex))92witness_size = len(tx_inwit.serialize())93return len(tx_in.serialize()) * WITNESS_SCALE_FACTOR + witness_size95class WalletUnlock():96"""97A context manager for unlocking a wallet with a passphrase and automatically locking it afterward.98"""100MAXIMUM_TIMEOUT = 999000102def __init__(self, wallet, passphrase, timeout=MAXIMUM_TIMEOUT):103self.wallet = wallet104self.passphrase = passphrase105self.timeout = timeout107def __enter__(self):108self.wallet.walletpassphrase(self.passphrase, self.timeout)110def __exit__(self, *args):111_ = args112self.wallet.walletlock()115class TestFrameworkWalletUtil(unittest.TestCase):116def test_calculate_input_weight(self):117SKELETON_BYTES = 32 + 4 + 4 # prevout-txid, prevout-index, sequence118SMALL_LEN_BYTES = 1 # bytes needed for encoding scriptSig / witness item lengths < 253119LARGE_LEN_BYTES = 3 # bytes needed for encoding scriptSig / witness item lengths >= 253121# empty scriptSig, no witness122self.assertEqual(calculate_input_weight(""),123(SKELETON_BYTES + SMALL_LEN_BYTES) * WITNESS_SCALE_FACTOR)124self.assertEqual(calculate_input_weight("", None),125(SKELETON_BYTES + SMALL_LEN_BYTES) * WITNESS_SCALE_FACTOR)126# small scriptSig, no witness127scriptSig_small = "00"*252128self.assertEqual(calculate_input_weight(scriptSig_small, None),129(SKELETON_BYTES + SMALL_LEN_BYTES + 252) * WITNESS_SCALE_FACTOR)130# small scriptSig, empty witness stack131self.assertEqual(calculate_input_weight(scriptSig_small, []),132(SKELETON_BYTES + SMALL_LEN_BYTES + 252) * WITNESS_SCALE_FACTOR + SMALL_LEN_BYTES)133# large scriptSig, no witness134scriptSig_large = "00"*253135self.assertEqual(calculate_input_weight(scriptSig_large, None),136(SKELETON_BYTES + LARGE_LEN_BYTES + 253) * WITNESS_SCALE_FACTOR)137# large scriptSig, empty witness stack138self.assertEqual(calculate_input_weight(scriptSig_large, []),139(SKELETON_BYTES + LARGE_LEN_BYTES + 253) * WITNESS_SCALE_FACTOR + SMALL_LEN_BYTES)140# empty scriptSig, 5 small witness stack items141self.assertEqual(calculate_input_weight("", ["00", "11", "22", "33", "44"]),142((SKELETON_BYTES + SMALL_LEN_BYTES) * WITNESS_SCALE_FACTOR) + SMALL_LEN_BYTES + 5 * SMALL_LEN_BYTES + 5)143# empty scriptSig, 253 small witness stack items144self.assertEqual(calculate_input_weight("", ["00"]*253),145((SKELETON_BYTES + SMALL_LEN_BYTES) * WITNESS_SCALE_FACTOR) + LARGE_LEN_BYTES + 253 * SMALL_LEN_BYTES + 253)146# small scriptSig, 3 large witness stack items147self.assertEqual(calculate_input_weight(scriptSig_small, ["00"*253]*3),148((SKELETON_BYTES + SMALL_LEN_BYTES + 252) * WITNESS_SCALE_FACTOR) + SMALL_LEN_BYTES + 3 * LARGE_LEN_BYTES + 3*253)149# large scriptSig, 3 large witness stack items150self.assertEqual(calculate_input_weight(scriptSig_large, ["00"*253]*3),151((SKELETON_BYTES + LARGE_LEN_BYTES + 253) * WITNESS_SCALE_FACTOR) + SMALL_LEN_BYTES + 3 * LARGE_LEN_BYTES + 3*253)
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.