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"""Utilities for manipulating blocks and transactions."""7import struct8import time9import unittest11from .address import (12address_to_scriptpubkey,13key_to_p2sh_p2wpkh,14key_to_p2wpkh,15script_to_p2sh_p2wsh,16script_to_p2wsh,17)18from .messages import (19CBlock,20COIN,21COutPoint,22CTransaction,23CTxIn,24CTxInWitness,25CTxOut,26SEQUENCE_FINAL,27hash256,28ser_uint256,29tx_from_hex,30uint256_from_compact,31WITNESS_SCALE_FACTOR,32MAX_SEQUENCE_NONFINAL,33)34from .script import (35CScript,36CScriptNum,37CScriptOp,38OP_0,39OP_RETURN,40OP_TRUE,41)42from .script_util import (43key_to_p2pk_script,44key_to_p2wpkh_script,45keys_to_multisig_script,46script_to_p2wsh_script,47)48from .util import assert_equal50MAX_BLOCK_SIGOPS = 2000051MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR52MAX_STANDARD_TX_SIGOPS = 400053MAX_STANDARD_TX_WEIGHT = 40000055# Genesis block time (regtest)56TIME_GENESIS_BLOCK = 129668860258MAX_FUTURE_BLOCK_TIME = 2 * 60 * 6060# Coinbase transaction outputs can only be spent after this number of new blocks (network rule)61COINBASE_MATURITY = 10063# From BIP14164WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed"66NULL_OUTPOINT = COutPoint(0, 0xffffffff)68NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]}69VERSIONBITS_LAST_OLD_BLOCK_VERSION = 470MIN_BLOCKS_TO_KEEP = 28872REGTEST_RETARGET_PERIOD = 15074REGTEST_N_BITS = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams"75REGTEST_TARGET = 0x7fffff000000000000000000000000000000000000000000000000000000000076assert_equal(uint256_from_compact(REGTEST_N_BITS), REGTEST_TARGET)78DIFF_1_N_BITS = 0x1d00ffff79DIFF_1_TARGET = 0x00000000ffff000000000000000000000000000000000000000000000000000080assert_equal(uint256_from_compact(DIFF_1_N_BITS), DIFF_1_TARGET)82DIFF_4_N_BITS = 0x1c3fffc083DIFF_4_TARGET = int(DIFF_1_TARGET / 4)84assert_equal(uint256_from_compact(DIFF_4_N_BITS), DIFF_4_TARGET)86# From BIP32587SIGNET_HEADER = b"\xec\xc7\xda\xa2"89# Number of blocks to create in temporary blockchain branch for reorg testing90FORK_LENGTH = 1092def nbits_str(nbits):93return f"{nbits:08x}"95def target_str(target):96return f"{target:064x}"98def create_block(hashprev=None, coinbase=None, *, ntime=None, height=None, version=None, tmpl=None, txlist=None):99"""Create a block (with regtest difficulty)."""100block = CBlock()101if tmpl is None:102tmpl = {}103block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION104block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600)105block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10)106if tmpl and tmpl.get('bits') is not None:107block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0]108else:109block.nBits = REGTEST_N_BITS110if coinbase is None:111coinbase = create_coinbase(height=height or tmpl["height"])112block.vtx.append(coinbase)113if txlist:114for tx in txlist:115if type(tx) is str:116tx = tx_from_hex(tx)117block.vtx.append(tx)118block.hashMerkleRoot = block.calc_merkle_root()119return block121def create_empty_fork(node, fork_length=FORK_LENGTH):122'''123Creates a fork using node's chaintip as the starting point.124Returns a list of blocks to submit in order.125'''126tip = int(node.getbestblockhash(), 16)127height = node.getblockcount()128block_time = node.getblock(node.getbestblockhash())['time'] + 1130blocks = []131for _ in range(fork_length):132block = create_block(tip, height=height + 1, ntime=block_time)133block.solve()134blocks.append(block)135tip = block.hash_int136block_time += 1137height += 1139return blocks141def get_witness_script(witness_root, witness_nonce):142witness_commitment = hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce))143output_data = WITNESS_COMMITMENT_HEADER + witness_commitment144return CScript([OP_RETURN, output_data])146def add_witness_commitment(block, nonce=0):147"""Add a witness commitment to the block's coinbase transaction.149According to BIP141, blocks with witness rules active must commit to the150hash of all in-block transactions including witness."""151# First calculate the merkle root of the block's152# transactions, with witnesses.153witness_nonce = nonce154witness_root = block.calc_witness_merkle_root()155# witness_nonce should go to coinbase witness.156block.vtx[0].wit.vtxinwit = [CTxInWitness()]157block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)]159# witness commitment is the last OP_RETURN output in coinbase160block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce)))161block.hashMerkleRoot = block.calc_merkle_root()164def script_BIP34_coinbase_height(height, *, padding=True):165if height <= 16:166res = CScriptOp.encode_op_n(height)167if padding:168# Append dummy extraNonce to increase scriptSig size to 2 (see bad-cb-length consensus rule)169return CScript([res, OP_0])170return CScript([res])171return CScript([CScriptNum(height)])174def create_coinbase(height, pubkey=None, *, script_pubkey=None, extra_output_script=None, fees=0, nValue=50, halving_period=REGTEST_RETARGET_PERIOD):175"""Create a coinbase transaction.177If pubkey is passed in, the coinbase output will be a P2PK output;178otherwise an anyone-can-spend output.180If extra_output_script is given, make a 0-value output to that181script. This is useful to pad block weight/sigops as needed. """182coinbase = CTransaction()183coinbase.nLockTime = height - 1184coinbase.vin.append(CTxIn(NULL_OUTPOINT, script_BIP34_coinbase_height(height), MAX_SEQUENCE_NONFINAL))185coinbaseoutput = CTxOut()186coinbaseoutput.nValue = nValue * COIN187if nValue == 50:188halvings = int(height / halving_period)189coinbaseoutput.nValue >>= halvings190coinbaseoutput.nValue += fees191if pubkey is not None:192coinbaseoutput.scriptPubKey = key_to_p2pk_script(pubkey)193elif script_pubkey is not None:194coinbaseoutput.scriptPubKey = script_pubkey195else:196coinbaseoutput.scriptPubKey = CScript([OP_TRUE])197coinbase.vout = [coinbaseoutput]198if extra_output_script is not None:199coinbaseoutput2 = CTxOut()200coinbaseoutput2.nValue = 0201coinbaseoutput2.scriptPubKey = extra_output_script202coinbase.vout.append(coinbaseoutput2)203return coinbase205def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, output_script=None):206"""Return one-input, one-output transaction object207spending the prevtx's n-th output with the given amount.209Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output.210"""211if output_script is None:212output_script = CScript()213tx = CTransaction()214assert n < len(prevtx.vout)215tx.vin.append(CTxIn(COutPoint(prevtx.txid_int, n), script_sig, SEQUENCE_FINAL))216tx.vout.append(CTxOut(amount, output_script))217return tx219def get_legacy_sigopcount_block(block, accurate=True):220count = 0221for tx in block.vtx:222count += get_legacy_sigopcount_tx(tx, accurate)223return count225def get_legacy_sigopcount_tx(tx, accurate=True):226count = 0227for i in tx.vout:228count += i.scriptPubKey.GetSigOpCount(accurate)229for j in tx.vin:230# scriptSig might be of type bytes, so convert to CScript for the moment231count += CScript(j.scriptSig).GetSigOpCount(accurate)232return count234def witness_script(use_p2wsh, pubkey):235"""Create a scriptPubKey for a pay-to-witness TxOut.237This is either a P2WPKH output for the given pubkey, or a P2WSH output of a2381-of-1 multisig for the given pubkey. Returns the hex encoding of the239scriptPubKey."""240if not use_p2wsh:241# P2WPKH instead242pkscript = key_to_p2wpkh_script(pubkey)243else:244# 1-of-1 multisig245witness_script = keys_to_multisig_script([pubkey])246pkscript = script_to_p2wsh_script(witness_script)247return pkscript.hex()249def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount):250"""Return a transaction (in hex) that spends the given utxo to a segwit output.
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.