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.
251script = get(ctx, "script_taproot")252return TaprootSignatureMsg(tx, utxos, hashtype, idx, scriptpath=True, leaf_script=script, leaf_ver=leaf_ver, codeseparator_pos=codeseppos, annex=annex)253else:254return TaprootSignatureMsg(tx, utxos, hashtype, idx, scriptpath=False, annex=annex)255elif mode == "witv0":256# BIP143 signature hash257scriptcode = get(ctx, "scriptcode_suffix")258utxos = get(ctx, "utxos")259return SegwitV0SignatureMsg(scriptcode, tx, idx, hashtype, utxos[idx].nValue)260else:261# Pre-segwit signature hash262scriptcode = get(ctx, "scriptcode_suffix")263return LegacySignatureMsg(scriptcode, tx, idx, hashtype)[0]265def default_sighash(ctx):266"""Default expression for "sighash": depending on mode, compute tagged hash or dsha256 of sigmsg."""267msg = get(ctx, "sigmsg")268mode = get(ctx, "mode")269if mode == "taproot":270return TaggedHash("TapSighash", msg)271else:272if msg is None:273return (1).to_bytes(32, 'little')274else:275return hash256(msg)277def default_tweak(ctx):278"""Default expression for "tweak": None if a leaf is specified, tap[0] otherwise."""279if get(ctx, "leaf") is None:280return get(ctx, "tap").tweak281return None283def default_key_tweaked(ctx):284"""Default expression for "key_tweaked": key if tweak is None, tweaked with it otherwise."""285key = get(ctx, "key")286tweak = get(ctx, "tweak")287if tweak is None:288return key289else:290return tweak_add_privkey(key, tweak)292def default_signature(ctx):293"""Default expression for "signature": BIP340 signature or ECDSA signature depending on mode."""294sighash = get(ctx, "sighash")295deterministic = get(ctx, "deterministic")296if get(ctx, "mode") == "taproot":297key = get(ctx, "key_tweaked")298flip_r = get(ctx, "flag_flip_r")299flip_p = get(ctx, "flag_flip_p")300aux = bytes([0] * 32)301if not deterministic:302aux = random.getrandbits(256).to_bytes(32, 'big')303return sign_schnorr(key, sighash, flip_r=flip_r, flip_p=flip_p, aux=aux)304else:305key = get(ctx, "key")306return key.sign_ecdsa(sighash, rfc6979=deterministic)308def default_hashtype_actual(ctx):309"""Default expression for "hashtype_actual": hashtype, unless mismatching SIGHASH_SINGLE in taproot."""310hashtype = get(ctx, "hashtype")311mode = get(ctx, "mode")312if mode != "taproot":313return hashtype314idx = get(ctx, "idx")315tx = get(ctx, "tx")316if hashtype & 3 == SIGHASH_SINGLE and idx >= len(tx.vout):317return (hashtype & ~3) | SIGHASH_NONE318return hashtype320def default_bytes_hashtype(ctx):321"""Default expression for "bytes_hashtype": bytes([hashtype_actual]) if not 0, b"" otherwise."""322mode = get(ctx, "mode")323hashtype_actual = get(ctx, "hashtype_actual")324if mode != "taproot" or hashtype_actual != 0:325return bytes([hashtype_actual])326else:327return bytes()329def default_sign(ctx):330"""Default expression for "sign": concatenation of signature and bytes_hashtype."""331return get(ctx, "signature") + get(ctx, "bytes_hashtype")333def default_inputs_keypath(ctx):334"""Default expression for "inputs_keypath": a signature."""335return [get(ctx, "sign")]337def default_witness_taproot(ctx):338"""Default expression for "witness_taproot", consisting of inputs, script, control block, and annex as needed."""339annex = get(ctx, "annex")340suffix_annex = []341if annex is not None:342suffix_annex = [annex]343if get(ctx, "leaf") is None:344return get(ctx, "inputs_keypath") + suffix_annex345else:346return get(ctx, "inputs") + [bytes(get(ctx, "script_taproot")), get(ctx, "controlblock")] + suffix_annex348def default_witness_witv0(ctx):349"""Default expression for "witness_witv0", consisting of inputs and witness script, as needed."""350script = get(ctx, "script_witv0")351inputs = get(ctx, "inputs")352if script is None:353return inputs354else:355return inputs + [script]357def default_witness(ctx):358"""Default expression for "witness", delegating to "witness_taproot" or "witness_witv0" as needed."""359mode = get(ctx, "mode")360if mode == "taproot":361return get(ctx, "witness_taproot")362elif mode == "witv0":363return get(ctx, "witness_witv0")364else:365return []367def default_scriptsig(ctx):368"""Default expression for "scriptsig", consisting of inputs and redeemscript, as needed."""369scriptsig = []370mode = get(ctx, "mode")371if mode == "legacy":372scriptsig = get(ctx, "inputs")373redeemscript = get(ctx, "script_p2sh")374if redeemscript is not None:375scriptsig += [bytes(redeemscript)]376return scriptsig378# The default context object.379DEFAULT_CONTEXT = {380# == The main expressions to evaluate. Only override these for unusual or invalid spends. ==381# The overall witness stack, as a list of bytes objects.382"witness": default_witness,383# The overall scriptsig, as a list of CScript objects (to be concatenated) and bytes objects (to be pushed)384"scriptsig": default_scriptsig,386# == Expressions you'll generally only override for intentionally invalid spends. ==387# The witness stack for spending a taproot output.388"witness_taproot": default_witness_taproot,389# The witness stack for spending a P2WPKH/P2WSH output.390"witness_witv0": default_witness_witv0,391# The script inputs for a taproot key path spend.392"inputs_keypath": default_inputs_keypath,393# The actual hashtype to use (usually equal to hashtype, but in taproot SIGHASH_SINGLE is not always allowed).394"hashtype_actual": default_hashtype_actual,395# The bytes object for a full signature (including hashtype byte, if needed).396"bytes_hashtype": default_bytes_hashtype,397# A full script signature (bytes including hashtype, if needed)398"sign": default_sign,399# An ECDSA or Schnorr signature (excluding hashtype byte).400"signature": default_signature,401# The 32-byte tweaked key (equal to key for script path spends, or key+tweak for key path spends).402"key_tweaked": default_key_tweaked,403# The tweak to use (None for script path spends, the actual tweak for key path spends).404"tweak": default_tweak,405# The part of the scriptcode after the last executed OP_CODESEPARATOR.406"scriptcode_suffix": default_scriptcode_suffix,407# The sigmsg value (preimage of sighash)408"sigmsg": default_sigmsg,409# The sighash value (32 bytes)410"sighash": default_sighash,411# The information about the chosen script path spend (TaprootLeafInfo object).412"tapleaf": default_tapleaf,413# The script to push, and include in the sighash, for a taproot script path spend.414"script_taproot": default_script_taproot,415# The internal pubkey for a taproot script path spend (32 bytes).416"pubkey_internal": default_pubkey_internal,417# The negation flag of the internal pubkey for a taproot script path spend.418"negflag": default_negflag,419# The leaf version to include in the sighash (this does not affect the one in the control block).420"leafversion": default_leafversion,421# The Merkle path to include in the control block for a script path spend.422"merklebranch": default_merklebranch,423# The control block to push for a taproot script path spend.424"controlblock": default_controlblock,425# Whether to produce signatures with invalid P sign (Schnorr signatures only).426"flag_flip_p": False,427# Whether to produce signatures with invalid R sign (Schnorr signatures only).428"flag_flip_r": False,430# == Parameters that can be changed without invalidating, but do have a default: ==431# The hashtype (as an integer).432"hashtype": default_hashtype,433# The annex (only when mode=="taproot").434"annex": None,435# The codeseparator position (only when mode=="taproot").436"codeseppos": 0xffffffff,437# Which OP_CODESEPARATOR is the last executed one in the script (in legacy/P2SH/P2WSH).438"codesepnum": -1,439# The redeemscript to add to the scriptSig (if P2SH; None implies not P2SH).440"script_p2sh": None,441# The script to add to the witness in (if P2WSH; None implies P2WPKH)442"script_witv0": None,443# The leaf to use in taproot spends (if script path spend; None implies key path spend).444"leaf": None,445# The input arguments to provide to the executed script446"inputs": [],447# Use deterministic signing nonces448"deterministic": False,450# == Parameters to be set before evaluation: ==451# - mode: what spending style to use ("taproot", "witv0", or "legacy").452# - key: the (untweaked) private key to sign with (ECKey object for ECDSA, 32 bytes for Schnorr).453# - tap: the TaprootInfo object (see taproot_construct; needed in mode=="taproot").454# - tx: the transaction to sign.455# - utxos: the UTXOs being spent (needed in mode=="witv0" and mode=="taproot").456# - idx: the input position being signed.457# - scriptcode: the scriptcode to include in legacy and witv0 sighashes.458}460def flatten(lst):461ret = []462for elem in lst:463if isinstance(elem, list):464ret += flatten(elem)465else:466ret.append(elem)467return ret470def spend(tx, idx, utxos, **kwargs):471"""Sign transaction input idx of tx, provided utxos is the list of outputs being spent.473Additional arguments may be provided that override any aspect of the signing process.474See DEFAULT_CONTEXT above for what can be overridden, and what must be provided.475"""477ctx = {**DEFAULT_CONTEXT, "tx":tx, "idx":idx, "utxos":utxos, **kwargs}479def to_script(elem):480"""If fed a CScript, return it; if fed bytes, return a CScript that pushes it."""481if isinstance(elem, CScript):482return elem483else:484return CScript([elem])486scriptsig_list = flatten(get(ctx, "scriptsig"))487scriptsig = CScript(b"".join(bytes(to_script(elem)) for elem in scriptsig_list))488witness_stack = flatten(get(ctx, "witness"))489return (scriptsig, witness_stack)492# === Spender objects ===493#494# Each spender is a tuple of:495# - A scriptPubKey which is to be spent from (CScript)496# - A comment describing the test (string)497# - Whether the spending (on itself) is expected to be standard (bool)498# - A tx-signing lambda returning (scriptsig, witness_stack), taking as inputs:499# - A transaction to sign (CTransaction)500# - An input position (int)
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.