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.
502elif opcode == OP_PUSHDATA1:503pushdata_type = 'PUSHDATA1'504if i >= len(self):505raise CScriptInvalidError('PUSHDATA1: missing data length')506datasize = self[i]507i += 1509elif opcode == OP_PUSHDATA2:510pushdata_type = 'PUSHDATA2'511if i + 1 >= len(self):512raise CScriptInvalidError('PUSHDATA2: missing data length')513datasize = self[i] + (self[i + 1] << 8)514i += 2516elif opcode == OP_PUSHDATA4:517pushdata_type = 'PUSHDATA4'518if i + 3 >= len(self):519raise CScriptInvalidError('PUSHDATA4: missing data length')520datasize = self[i] + (self[i + 1] << 8) + (self[i + 2] << 16) + (self[i + 3] << 24)521i += 4523else:524assert False # shouldn't happen526data = bytes(self[i:i + datasize])528# Check for truncation529if len(data) < datasize:530raise CScriptTruncatedPushDataError('%s: truncated data' % pushdata_type, data)532i += datasize534yield (opcode, data, sop_idx)536def __iter__(self):537"""'Cooked' iteration539Returns either a CScriptOP instance, an integer, or bytes, as540appropriate.542See raw_iter() if you need to distinguish the different possible543PUSHDATA encodings.544"""545for (opcode, data, sop_idx) in self.raw_iter():546if data is not None:547yield data548else:549opcode = CScriptOp(opcode)551if opcode.is_small_int():552yield opcode.decode_op_n()553else:554yield CScriptOp(opcode)556def __repr__(self):557def _repr(o):558if isinstance(o, bytes):559return "x('%s')" % o.hex()560else:561return repr(o)563ops = []564i = iter(self)565while True:566op = None567try:568op = _repr(next(i))569except CScriptTruncatedPushDataError as err:570op = '%s...<ERROR: %s>' % (_repr(err.data), err)571break572except CScriptInvalidError as err:573op = '<ERROR: %s>' % err574break575except StopIteration:576break577finally:578if op is not None:579ops.append(op)581return "CScript([%s])" % ', '.join(ops)583def GetSigOpCount(self, fAccurate):584"""Get the SigOp count.586fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.588Note that this is consensus-critical.589"""590n = 0591lastOpcode = OP_INVALIDOPCODE592for (opcode, data, sop_idx) in self.raw_iter():593if opcode in (OP_CHECKSIG, OP_CHECKSIGVERIFY):594n += 1595elif opcode in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):596if fAccurate and (OP_1 <= lastOpcode <= OP_16):597n += lastOpcode.decode_op_n()598else:599n += 20600lastOpcode = opcode601return n603def IsWitnessProgram(self):604"""A witness program is any valid CScript that consists of a 1-byte605push opcode followed by a data push between 2 and 40 bytes."""606return ((4 <= len(self) <= 42) and607(self[0] == OP_0 or (OP_1 <= self[0] <= OP_16)) and608(self[1] + 2 == len(self)))611SIGHASH_DEFAULT = 0 # Taproot-only default, semantics same as SIGHASH_ALL612SIGHASH_ALL = 1613SIGHASH_NONE = 2614SIGHASH_SINGLE = 3615SIGHASH_ANYONECANPAY = 0x80617def FindAndDelete(script, sig):618"""Consensus critical, see FindAndDelete() in Satoshi codebase"""619r = b''620last_sop_idx = sop_idx = 0621skip = True622for (opcode, data, sop_idx) in script.raw_iter():623if not skip:624r += script[last_sop_idx:sop_idx]625last_sop_idx = sop_idx626if script[sop_idx:sop_idx + len(sig)] == sig:627skip = True628else:629skip = False630if not skip:631r += script[last_sop_idx:]632return CScript(r)634def LegacySignatureMsg(script, txTo, inIdx, hashtype):635"""Preimage of the signature hash, if it exists.637Returns either (None, err) to indicate error (which translates to sighash 1),638or (msg, None).639"""641if inIdx >= len(txTo.vin):642return (None, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))643txtmp = CTransaction(txTo)645for txin in txtmp.vin:646txin.scriptSig = b''647txtmp.vin[inIdx].scriptSig = FindAndDelete(script, CScript([OP_CODESEPARATOR]))649if (hashtype & 0x1f) == SIGHASH_NONE:650txtmp.vout = []652for i in range(len(txtmp.vin)):653if i != inIdx:654txtmp.vin[i].nSequence = 0656elif (hashtype & 0x1f) == SIGHASH_SINGLE:657outIdx = inIdx658if outIdx >= len(txtmp.vout):659return (None, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))661tmp = txtmp.vout[outIdx]662txtmp.vout = []663for _ in range(outIdx):664txtmp.vout.append(CTxOut(-1))665txtmp.vout.append(tmp)667for i in range(len(txtmp.vin)):668if i != inIdx:669txtmp.vin[i].nSequence = 0671if hashtype & SIGHASH_ANYONECANPAY:672tmp = txtmp.vin[inIdx]673txtmp.vin = []674txtmp.vin.append(tmp)676s = txtmp.serialize_without_witness()677s += hashtype.to_bytes(4, "little")679return (s, None)681def LegacySignatureHash(*args, **kwargs):682"""Consensus-correct SignatureHash684Returns (hash, err) to precisely match the consensus-critical behavior of685the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)686"""688HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'689msg, err = LegacySignatureMsg(*args, **kwargs)690if msg is None:691return (HASH_ONE, err)692else:693return (hash256(msg), err)695def sign_input_legacy(tx, input_index, input_scriptpubkey, privkey, sighash_type=SIGHASH_ALL):696"""Add legacy ECDSA signature for a given transaction input. Note that the signature697is prepended to the scriptSig field, i.e. additional data pushes necessary for more698complex spends than P2PK (e.g. pubkey for P2PKH) can be already set before."""699(sighash, err) = LegacySignatureHash(input_scriptpubkey, tx, input_index, sighash_type)700assert err is None701der_sig = privkey.sign_ecdsa(sighash)702tx.vin[input_index].scriptSig = bytes(CScript([der_sig + bytes([sighash_type])])) + tx.vin[input_index].scriptSig704def sign_input_segwitv0(tx, input_index, input_scriptpubkey, input_amount, privkey, sighash_type=SIGHASH_ALL):705"""Add segwitv0 ECDSA signature for a given transaction input. Note that the signature706is inserted at the bottom of the witness stack, i.e. additional witness data707needed (e.g. pubkey for P2WPKH) can already be set before."""708sighash = SegwitV0SignatureHash(input_scriptpubkey, tx, input_index, sighash_type, input_amount)709der_sig = privkey.sign_ecdsa(sighash)710tx.wit.vtxinwit[input_index].scriptWitness.stack.insert(0, der_sig + bytes([sighash_type]))712# TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided.713# Performance optimization probably not necessary for python tests, however.714# Note that this corresponds to sigversion == 1 in EvalScript, which is used715# for version 0 witnesses.716def SegwitV0SignatureMsg(script, txTo, inIdx, hashtype, amount):717ZERO_HASH = bytes([0]*32)719hashPrevouts = ZERO_HASH720hashSequence = ZERO_HASH721hashOutputs = ZERO_HASH723if not (hashtype & SIGHASH_ANYONECANPAY):724serialize_prevouts = bytes()725for i in txTo.vin:726serialize_prevouts += i.prevout.serialize()727hashPrevouts = hash256(serialize_prevouts)729if (not (hashtype & SIGHASH_ANYONECANPAY) and (hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):730serialize_sequence = bytes()731for i in txTo.vin:732serialize_sequence += i.nSequence.to_bytes(4, "little")733hashSequence = hash256(serialize_sequence)735if ((hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):736serialize_outputs = bytes()737for o in txTo.vout:738serialize_outputs += o.serialize()739hashOutputs = hash256(serialize_outputs)740elif ((hashtype & 0x1f) == SIGHASH_SINGLE and inIdx < len(txTo.vout)):741serialize_outputs = txTo.vout[inIdx].serialize()742hashOutputs = hash256(serialize_outputs)744ss = bytes()745ss += txTo.version.to_bytes(4, "little")746ss += hashPrevouts747ss += hashSequence748ss += txTo.vin[inIdx].prevout.serialize()749ss += ser_string(script)750ss += amount.to_bytes(8, "little", signed=True)
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.