Signature encodings, signature hashes, secp256k1 ECDSA and Schnorr verification, and the transaction signature checker
DefinitionBitcoinSigsecp256k1. , the order , the generator ; powMod is square-and-multiply with explicit fuel, finv/ninv are Fermat inverses; a Point is an affine pair or infinity; padd is affine addition with the doubling and inverse cases; pmul is double-and-add. liftXParity is secp256k1_ge_set_xo_var (square root by , parity selection); parsePubkey is secp256k1_eckey_pubkey_parse (33-byte 02/03, 65-byte 04/06/07 with coordinates below , on-curve and, for hybrid, parity check); pubkeyValid is CPubKey::IsValid (the header byte announces the length). isHighS is , normalizeS replaces a high by .
Signatures. parseDerLax is ecdsa_signature_parse_der_lax with its exact control flow: none where it returns (missing tags, length overruns, a long-form length of 4 or more significant bytes), some (0,0) where an integer has more than 32 significant bytes or a value at or above (the "correctly parsed but invalid" signature), trailing bytes ignored. ecdsaVerifyRaw is secp256k1_ecdsa_sig_verify: , , , and . pubkeyVerify is CPubKey::Verify: valid and parsable key, lax-parsed signature, normalized, message reduced modulo . checkLowS is CPubKey::CheckLowS. schnorrVerify is BIP340 / secp256k1_schnorrsig_verify with taggedHash.
Byte-level scripts. getOp is GetScriptOp (direct pushes, PUSHDATA1/2/4, none on a truncated push); parseScript parses a whole script; pushBytes is CScript() << vch; findAndDelete is FindAndDelete (occurrences removed at instruction boundaries, count returned); serScriptCode is SerializeScriptCode (OP_CODESEPARATORs dropped, length-prefixed).
Signature hashes. serSigTx is CTransactionSignatureSerializer (ANYONECANPAY keeps only the signed input, other inputs' scripts blanked, their sequences zeroed under SINGLE/NONE, outputs truncated under SINGLE, dropped under NONE); sigHashLegacy is SignatureHash for SigVersion::BASE with the SIGHASH_SINGLE bug returning uint256::ONE; sigHashWitnessV0 is the BIP143 algorithm (hashPrevouts, hashSequence, hashOutputs under the same flags, the amount, the script code).
Encoding checks and the checker. isValidSignatureEncoding is the strict-DER test (BIP66) byte for byte; isLowDERSignature, isCompressedOrUncompressedPubKey, isCompressedPubKey, isDefinedHashtypeSignature, checkSignatureEncoding, checkPubKeyEncoding under SigFlags (dersig is the only mainnet consensus flag; lowS, strictenc, witnessPubkeyType are policy and carried for fidelity). checkECDSASignature is the checker's method (hash type = last byte, witness v0 needs a non-negative amount); checkSigPreTapscript is EvalChecksigPreTapscript (FindAndDelete of the signature push for legacy scripts, encoding checks as none, verdict as some). checkLockTime/checkSequence are the checker's lock-time methods (LOCKTIME_THRESHOLD, SEQUENCE_FINAL, BIP68 masks). legacyOracle assembles Core's hashes, the checker and the lock-time checks into the BitcoinScript.Oracle of the legacy interpreter for a given script code.
Auxiliary. p2pkhBytes is the P2PKH output script as bytes; sameSkeleton relates transactions differing only in scriptSigs and witnesses; minimalInt and derEncode describe the DER layout.
Formalization Note. The script code handed to the oracle is the executed script, which is exact for scripts without OP_CODESEPARATOR. Field and scalar arithmetic are on Nat modulo and ; no claim about libsecp256k1's constant-time implementation is made, only about its mathematical semantics. Only Std is imported.
import Std
import Definitions.Def_BitcoinSer
import Definitions.Def_BitcoinScript
namespace BitcoinSig
/-! Transcription of Bitcoin Core's signature layer at revision
`a773e1e33b349dc819b5a0edc1c7a4839dc73b48`: `GetScriptOp` (`script/script.cpp`), `FindAndDelete`,
`IsValidSignatureEncoding`, `IsLowDERSignature`, `IsCompressedOrUncompressedPubKey`,
`IsCompressedPubKey`, `IsDefinedHashtypeSignature`, `CheckSignatureEncoding`, `CheckPubKeyEncoding`,
`CTransactionSignatureSerializer`, `SignatureHash` (legacy and BIP143), `EvalChecksigPreTapscript`,
`GenericTransactionSignatureChecker::{CheckECDSASignature, CheckLockTime, CheckSequence}`
(`script/interpreter.cpp`); `CPubKey::{IsValid, Verify, CheckLowS}` and `ecdsa_signature_parse_der_lax`
(`pubkey.cpp`); and the secp256k1 semantics of `secp256k1_eckey_pubkey_parse`, `secp256k1_ecdsa_verify`
with signature normalization, and `secp256k1_schnorrsig_verify` (BIP340). -/
open BitcoinSer (Byte Bytes Tx TxIn TxOut OutPoint)
/-! ### secp256k1 -/
/-- The field prime `p = 2^256 - 2^32 - 977`. -/
def p : Nat := 2 ^ 256 - 2 ^ 32 - 977
/-- The group order `n`. -/
def n : Nat := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
def Gx : Nat := 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
def Gy : Nat := 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
/-- Square-and-multiply modular exponentiation with explicit fuel. -/
def powModAux (m : Nat) : Nat → Nat → Nat → Nat → Nat
| 0, _, _, acc => acc
| fuel + 1, b, e, acc =>
if e = 0 then acc
else powModAux m fuel (b * b % m) (e / 2) (if e % 2 = 1 then acc * b % m else acc)
def powMod (b e m : Nat) : Nat := powModAux m (e + 1) (b % m) e (1 % m)
/-- Field inverse by Fermat (`0` maps to `0`). -/
def finv (a : Nat) : Nat := powMod a (p - 2) p
/-- Scalar inverse modulo the group order. -/
def ninv (a : Nat) : Nat := powMod a (n - 2) n
/-- An affine point, or the point at infinity. -/
abbrev Point := Option (Nat × Nat)
def onCurve (P : Nat × Nat) : Bool := (P.2 * P.2) % p = (P.1 * P.1 * P.1 + 7) % p
/-- Affine addition on secp256k1 (`y^2 = x^3 + 7`). -/
def padd (P Q : Point) : Point :=
match P, Q with
| none, q => q
| q, none => q
| some (x1, y1), some (x2, y2) =>
if x1 % p = x2 % p then
if (y1 + y2) % p = 0 then none
else
-- doubling
let l := (3 * x1 * x1) * finv (2 * y1 % p) % p
let x3 := (l * l + 2 * (p - x1 % p)) % p
let y3 := (l * ((x1 + p - x3) % p) + (p - y1 % p)) % p
some (x3, y3)
else
let l := ((y2 + p - y1 % p) % p) * finv ((x2 + p - x1 % p) % p) % p
let x3 := (l * l + (p - x1 % p) + (p - x2 % p)) % p
let y3 := (l * ((x1 + p - x3) % p) + (p - y1 % p)) % p
some (x3, y3)
/-- Double-and-add scalar multiplication with explicit fuel. -/
def pmulAux : Nat → Nat → Point → Point → Point
| 0, _, _, acc => acc
| fuel + 1, k, P, acc =>
if k = 0 then acc
else pmulAux fuel (k / 2) (padd P P) (if k % 2 = 1 then padd acc P else acc)
def pmul (k : Nat) (P : Point) : Point := pmulAux 257 k P none
def G : Point := some (Gx, Gy)
def beVal (b : Bytes) : Nat := b.foldl (fun acc x => acc * 256 + x.toNat) 0
/-- `secp256k1_ge_set_xo_var`: the point with abscissa `x` and the given parity of `y`, if any. -/
def liftXParity (x : Nat) (odd : Bool) : Point :=
let y := powMod (x * x * x + 7) ((p + 1) / 4) p
if y * y % p = (x * x * x + 7) % p then
some (x, if (y % 2 = 1) = odd then y else (p - y) % p)
else none
/-- `secp256k1_eckey_pubkey_parse`: compressed (`02`/`03`, 33 bytes), uncompressed (`04`) and hybrid
(`06`/`07`, 65 bytes, parity of `y` must match). Coordinates must be below `p` and on the curve. -/
def parsePubkey (pk : Bytes) : Point :=
match pk with
| tag :: rest =>
if pk.length = 33 ∧ (tag.toNat = 2 ∨ tag.toNat = 3) then
let x := beVal rest
if x < p then liftXParity x (tag.toNat = 3) else none
else if pk.length = 65 ∧ (tag.toNat = 4 ∨ tag.toNat = 6 ∨ tag.toNat = 7) then
let x := beVal (rest.take 32); let y := beVal (rest.drop 32)
if x < p ∧ y < p ∧ ((tag.toNat = 6 ∨ tag.toNat = 7) → ((y % 2 = 1) = (tag.toNat = 7))) ∧ onCurve (x, y) = true
then some (x, y) else none
else none
| [] => none
/-- `CPubKey::GetLen` and `CPubKey::IsValid`: the header byte announces the length. -/
def pubkeyLen (header : Nat) : Nat :=
if header = 2 ∨ header = 3 then 33 else if header = 4 ∨ header = 6 ∨ header = 7 then 65 else 0
def pubkeyValid (pk : Bytes) : Bool :=
match pk with
| [] => false
| h :: _ => decide (pubkeyLen h.toNat = pk.length)
/-- `secp256k1_scalar_is_high`: `s > n/2`. -/
def isHighS (s : Nat) : Bool := decide (n / 2 < s)
/-- `secp256k1_ecdsa_signature_normalize`: replace a high `s` by `n - s`. -/
def normalizeS (s : Nat) : Nat := if isHighS s then n - s else s
/-- The scalar read of a big-endian value (`secp256k1_scalar_set_b32`, overflow flagged). -/
def scalarOf (b : Bytes) : Option Nat := let v := beVal b; if v < n then some v else none
/-- `ecdsa_signature_parse_der_lax`: `none` where the parser returns `0`; `some (0, 0)` where an
integer overflows (the "correctly-parsed but invalid" signature); trailing bytes are ignored. -/
def parseDerLax (input : Bytes) : Option (Nat × Nat) :=
let len := input.length
let at_ (i : Nat) : Nat := (input.getD i 0).toNat
-- sequence tag
if len = 0 ∨ at_ 0 ≠ 0x30 then none else
let pos := 1
if pos = len then none else
let lenbyte := at_ pos
let pos := pos + 1
-- sequence length (long form: skip the length bytes)
let pos? : Option Nat :=
if 0x80 ≤ lenbyte then
let lb := lenbyte - 0x80
if len - pos < lb then none else some (pos + lb)
else some pos
match pos? with
| none => none
| some pos =>
-- an integer: tag, length (short or long form with leading zeros stripped, at most 3 bytes)
let readInt (pos : Nat) : Option (Nat × Nat × Nat) := -- (start, length, position after)
if pos = len ∨ at_ pos ≠ 0x02 then none else
let pos := pos + 1
if pos = len then none else
let lenbyte := at_ pos
let pos := pos + 1
if 0x80 ≤ lenbyte then
let lb := lenbyte - 0x80
if len - pos < lb then none else
-- skip leading zero length bytes
let rec skipZeros (pos lb : Nat) (fuel : Nat) : Nat × Nat :=
match fuel with
| 0 => (pos, lb)
| f + 1 => if 0 < lb ∧ at_ pos = 0 then skipZeros (pos + 1) (lb - 1) f else (pos, lb)
let (pos, lb) := skipZeros pos lb lb
if 4 ≤ lb then none else
let rlen := (List.range lb).foldl (fun acc i => acc * 256 + at_ (pos + i)) 0
let pos := pos + lb
if len - pos < rlen then none else some (pos, rlen, pos + rlen)
else
if len - pos < lenbyte then none else some (pos, lenbyte, pos + lenbyte)
match readInt pos with
| none => none
| some (rpos, rlen, pos) =>
match readInt pos with
| none => none
| some (spos, slen, _) =>
-- strip leading zeros, reject more than 32 significant bytes
let strip (pos len : Nat) : Nat × Nat :=
let rec go (pos len : Nat) (fuel : Nat) : Nat × Nat :=
match fuel with
| 0 => (pos, len)
| f + 1 => if 0 < len ∧ at_ pos = 0 then go (pos + 1) (len - 1) f else (pos, len)
go pos len len
let (rpos, rlen) := strip rpos rlen
let (spos, slen) := strip spos slen
if 32 < rlen ∨ 32 < slen then some (0, 0) else
let r := beVal ((input.drop rpos).take rlen)
let s := beVal ((input.drop spos).take slen)
-- `secp256k1_ecdsa_signature_parse_compact`: a scalar at or above `n` is an overflow
if r < n ∧ s < n then some (r, s) else some (0, 0)
/-- `secp256k1_ecdsa_sig_verify` on a parsed key, a message scalar and a (normalized) signature. -/
def ecdsaVerifyRaw (Q : Point) (e r s : Nat) : Bool :=
if r = 0 ∨ s = 0 ∨ n ≤ r ∨ n ≤ s then false
else
let w := ninv s
let u1 := e * w % n
let u2 := r * w % n
match padd (pmul u1 G) (pmul u2 Q) with
| none => false
| some (x, _) => decide (x % n = r)
/-- `CPubKey::Verify(hash, vchSig)`: key validity and parsing, lax DER parsing, S normalization,
then `secp256k1_ecdsa_verify` with the message reduced modulo `n`. -/
def pubkeyVerify (pk : Bytes) (hash : Bytes) (sig : Bytes) : Bool :=
if !pubkeyValid pk then false
else match parsePubkey pk with
| none => false
| some Q =>
match parseDerLax sig with
| none => false
| some (r, s) => ecdsaVerifyRaw (some Q) (beVal hash % n) r (normalizeS s)
/-- `CPubKey::CheckLowS`. -/
def checkLowS (sig : Bytes) : Bool :=
match parseDerLax sig with
| none => false
| some (_, s) => !isHighS s
/-! ### BIP340 Schnorr -/
/-- `tagged_hash(tag, m) = SHA256(SHA256(tag) || SHA256(tag) || m)`. -/
def taggedHash (tag : Bytes) (m : Bytes) : Bytes :=
let th := BitcoinSer.sha256 tag
BitcoinSer.sha256 (th ++ th ++ m)
def ascii (s : String) : Bytes := s.toUTF8.toList.map fun c => BitVec.ofNat 8 c.toNat
/-- `lift_x` of BIP340: the point with abscissa `x` and even `y`. -/
def liftX (x : Nat) : Point := if x < p then liftXParity x false else none
/-- `secp256k1_schnorrsig_verify(sig64, msg, pk32)`. -/
def schnorrVerify (pk32 : Bytes) (msg : Bytes) (sig64 : Bytes) : Bool :=
if pk32.length ≠ 32 ∨ sig64.length ≠ 64 then false
else
let r := beVal (sig64.take 32)
let s := beVal (sig64.drop 32)
if p ≤ r ∨ n ≤ s then false
else match liftX (beVal pk32) with
| none => false
| some P =>
let e := beVal (taggedHash (ascii "BIP0340/challenge") (sig64.take 32 ++ pk32 ++ msg)) % n
match padd (pmul s G) (pmul ((n - e) % n) (some P)) with
| none => false
| some (rx, ry) => decide (ry % 2 = 0 ∧ rx = r)
/-! ### Byte-level scripts (`script/script.cpp`) -/
open BitcoinScript (Instr Script)
def OP_PUSHDATA1 : Nat := 0x4c
def OP_PUSHDATA2 : Nat := 0x4d
def OP_PUSHDATA4 : Nat := 0x4e
/-- `GetScriptOp`: one instruction and the remaining bytes, `none` where it returns `false`. -/
def getOp (s : Bytes) : Option (Instr × Bytes) :=
match s with
| [] => none
| op :: rest =>
let o := op.toNat
if o ≤ OP_PUSHDATA4 then
let sz? : Option (Nat × Bytes) :=
if o < OP_PUSHDATA1 then some (o, rest)
else if o = OP_PUSHDATA1 then
match rest with
| b :: r => some (b.toNat, r)
| [] => none
else if o = OP_PUSHDATA2 then
if rest.length < 2 then none else some (BitcoinSer.leVal (rest.take 2), rest.drop 2)
else
if rest.length < 4 then none else some (BitcoinSer.leVal (rest.take 4), rest.drop 4)
match sz? with
| none => none
| some (sz, r) => if r.length < sz then none else some (.push (r.take sz), r.drop sz)
else some (.op op, rest)
/-- Parse a whole script; `none` on a malformed push (`SCRIPT_ERR_BAD_OPCODE`). -/
def parseScriptAux : Nat → Bytes → Option Script
| _, [] => some []
| 0, _ => none
| fuel + 1, s =>
match getOp s with
| none => none
| some (i, r) =>
match parseScriptAux fuel r with
| none => none
| some is => some (i :: is)
def parseScript (s : Bytes) : Option Script := parseScriptAux s.length s
/-- `CScript() << vch`: the canonical push of a byte string. -/
def pushBytes (d : Bytes) : Bytes :=
if d.length < OP_PUSHDATA1 then BitVec.ofNat 8 d.length :: d
else if d.length ≤ 0xff then [BitVec.ofNat 8 OP_PUSHDATA1, BitVec.ofNat 8 d.length] ++ d
else if d.length ≤ 0xffff then BitVec.ofNat 8 OP_PUSHDATA2 :: BitcoinSer.leBytes 2 d.length ++ d
else BitVec.ofNat 8 OP_PUSHDATA4 :: BitcoinSer.leBytes 4 d.length ++ d
/-- `FindAndDelete(script, b)`: at every instruction boundary remove every occurrence of `b`;
returns the result and the number found. -/
def findAndDeleteAux (b : Bytes) : Nat → Bytes → Bytes → Nat → Bytes × Nat
| 0, s, acc, found => (acc ++ s, found)
| fuel + 1, s, acc, found =>
-- strip repeated occurrences at the current position
let rec strip (s : Bytes) (found : Nat) (f : Nat) : Bytes × Nat :=
match f with
| 0 => (s, found)
| f + 1 => if b.length ≤ s.length ∧ s.take b.length = b then strip (s.drop b.length) (found + 1) f else (s, found)
let (s, found) := strip s found (s.length + 1)
match getOp s with
| none => (acc ++ s, found)
| some (_, r) =>
let consumed := s.take (s.length - r.length)
findAndDeleteAux b fuel r (acc ++ consumed) found
def findAndDelete (script b : Bytes) : Bytes × Nat :=
if b.isEmpty then (script, 0) else findAndDeleteAux b (script.length + 1) script [] 0
/-- `SerializeScriptCode`: the script code with every `OP_CODESEPARATOR` instruction removed,
written as a byte string. -/
def scriptCodeBytesAux : Nat → Bytes → Bytes
| 0, s => s
| fuel + 1, s =>
match getOp s with
| none => s
| some (i, r) =>
let consumed := s.take (s.length - r.length)
(if i = .op BitcoinScript.OP_CODESEPARATOR then [] else consumed) ++ scriptCodeBytesAux fuel r
def serScriptCode (sc : Bytes) : Bytes :=
let body := scriptCodeBytesAux (sc.length + 1) sc
BitcoinSer.writeCompactSize body.length ++ body
/-! ### Signature hashes (`SignatureHash`) -/
def SIGHASH_ALL : Nat := 1
def SIGHASH_NONE : Nat := 2
def SIGHASH_SINGLE : Nat := 3
def SIGHASH_ANYONECANPAY : Nat := 0x80
/-- `uint256::ONE` in serialized byte order. -/
def uint256One : Bytes := 1 :: List.replicate 31 0
/-- `CTransactionSignatureSerializer::SerializeInput`. -/
def serSigInput (tx : Tx) (scriptCode : Bytes) (nIn : Nat) (anyoneCanPay single none_ : Bool) (nInput : Nat) : Bytes :=
let nInput := if anyoneCanPay then nIn else nInput
let i := tx.vin.getD nInput ⟨⟨[], 0⟩, [], 0, []⟩
BitcoinSer.serOutPoint i.prevout ++
(if nInput ≠ nIn then BitcoinSer.serBytes [] else serScriptCode scriptCode) ++
(if nInput ≠ nIn ∧ (single ∨ none_) then BitcoinSer.ser32 0 else BitcoinSer.ser32 i.nSequence)
/-- `CTransactionSignatureSerializer::SerializeOutput`. -/
def serSigOutput (tx : Tx) (nIn : Nat) (single : Bool) (nOutput : Nat) : Bytes :=
if single ∧ nOutput ≠ nIn then BitcoinSer.serTxOut ⟨-1, []⟩
else BitcoinSer.serTxOut (tx.vout.getD nOutput ⟨-1, []⟩)
/-- `CTransactionSignatureSerializer::Serialize`. -/
def serSigTx (tx : Tx) (scriptCode : Bytes) (nIn : Nat) (hashType : Nat) : Bytes :=
let anyoneCanPay := decide (hashType &&& SIGHASH_ANYONECANPAY ≠ 0)
let single := decide (hashType &&& 0x1f = SIGHASH_SINGLE)
let none_ := decide (hashType &&& 0x1f = SIGHASH_NONE)
let nInputs := if anyoneCanPay then 1 else tx.vin.length
let nOutputs := if none_ then 0 else if single then nIn + 1 else tx.vout.length
BitcoinSer.ser32 tx.version ++
BitcoinSer.writeCompactSize nInputs ++
(List.range nInputs).flatMap (serSigInput tx scriptCode nIn anyoneCanPay single none_) ++
BitcoinSer.writeCompactSize nOutputs ++
(List.range nOutputs).flatMap (serSigOutput tx nIn single) ++
BitcoinSer.ser32 tx.nLockTime
/-- `SignatureHash(scriptCode, tx, nIn, nHashType, amount, SigVersion::BASE)`: the SIGHASH_SINGLE
bug returns `uint256::ONE`; otherwise SHA-256d of the serializer output and the 4-byte hash type. -/
def sigHashLegacy (scriptCode : Bytes) (tx : Tx) (nIn : Nat) (hashType : Nat) : Bytes :=
if hashType &&& 0x1f = SIGHASH_SINGLE ∧ tx.vout.length ≤ nIn then uint256One
else BitcoinSer.hash256 (serSigTx tx scriptCode nIn hashType ++ BitcoinSer.ser32 hashType)
/-- `SignatureHash(..., SigVersion::WITNESS_V0)` (BIP143). -/
def sigHashWitnessV0 (scriptCode : Bytes) (tx : Tx) (nIn : Nat) (hashType : Nat) (amount : Int) : Bytes :=
let anyoneCanPay := hashType &&& SIGHASH_ANYONECANPAY ≠ 0
let single := hashType &&& 0x1f = SIGHASH_SINGLE
let none_ := hashType &&& 0x1f = SIGHASH_NONE
let zero : Bytes := List.replicate 32 0
let hashPrevouts := if ¬ anyoneCanPay then BitcoinSer.hash256 (tx.vin.flatMap fun i => BitcoinSer.serOutPoint i.prevout) else zero
let hashSequence := if ¬ anyoneCanPay ∧ ¬ single ∧ ¬ none_ then BitcoinSer.hash256 (tx.vin.flatMap fun i => BitcoinSer.ser32 i.nSequence) else zero
let hashOutputs :=
if ¬ single ∧ ¬ none_ then BitcoinSer.hash256 (tx.vout.flatMap BitcoinSer.serTxOut)
else if single ∧ nIn < tx.vout.length then BitcoinSer.hash256 (BitcoinSer.serTxOut (tx.vout.getD nIn ⟨-1, []⟩))
else zero
let i := tx.vin.getD nIn ⟨⟨[], 0⟩, [], 0, []⟩
BitcoinSer.hash256 (
BitcoinSer.ser32 tx.version ++ hashPrevouts ++ hashSequence ++
BitcoinSer.serOutPoint i.prevout ++ BitcoinSer.serBytes scriptCode ++ BitcoinSer.serInt64 amount ++
BitcoinSer.ser32 i.nSequence ++ hashOutputs ++ BitcoinSer.ser32 tx.nLockTime ++ BitcoinSer.ser32 hashType)
/-! ### Encoding checks (`interpreter.cpp`) -/
/-- `IsValidSignatureEncoding` (strict DER with a trailing hash-type byte). -/
def isValidSignatureEncoding (sig : Bytes) : Bool :=
let at_ (i : Nat) : Nat := (sig.getD i 0).toNat
let len := sig.length
if len < 9 then false
else if 73 < len then false
else if at_ 0 ≠ 0x30 then false
else if at_ 1 ≠ len - 3 then false
else
let lenR := at_ 3
if len ≤ 5 + lenR then false
else
let lenS := at_ (5 + lenR)
if lenR + lenS + 7 ≠ len then false
else if at_ 2 ≠ 0x02 then false
else if lenR = 0 then false
else if 0x80 ≤ at_ 4 then false
else if 1 < lenR ∧ at_ 4 = 0 ∧ at_ 5 < 0x80 then false
else if at_ (lenR + 4) ≠ 0x02 then false
else if lenS = 0 then false
else if 0x80 ≤ at_ (lenR + 6) then false
else if 1 < lenS ∧ at_ (lenR + 6) = 0 ∧ at_ (lenR + 7) < 0x80 then false
else true
/-- `IsLowDERSignature`: strict DER and low S (of the signature without the hash-type byte). -/
def isLowDERSignature (sig : Bytes) : Bool :=
isValidSignatureEncoding sig && checkLowS sig.dropLast
def isCompressedOrUncompressedPubKey (pk : Bytes) : Bool :=
match pk with
| [] => false
| h :: _ =>
if pk.length < 33 then false
else if h.toNat = 4 then decide (pk.length = 65)
else if h.toNat = 2 ∨ h.toNat = 3 then decide (pk.length = 33)
else false
def isCompressedPubKey (pk : Bytes) : Bool :=
match pk with
| [] => false
| h :: _ => decide (pk.length = 33) && decide (h.toNat = 2 ∨ h.toNat = 3)
def isDefinedHashtypeSignature (sig : Bytes) : Bool :=
match sig.getLast? with
| none => false
| some b => let t := b.toNat &&& (0xff ^^^ SIGHASH_ANYONECANPAY); decide (SIGHASH_ALL ≤ t ∧ t ≤ SIGHASH_SINGLE)
/-- The `script_verify_flags` consulted by the signature layer. Only `dersig` is a consensus flag on
mainnet; the others are relay policy and are carried for fidelity. -/
structure SigFlags where
dersig : Bool
lowS : Bool
strictenc : Bool
witnessPubkeyType : Bool
deriving DecidableEq, Repr
/-- `CheckSignatureEncoding`: `true` where the source returns `true`, `false` where it sets an error. -/
def checkSignatureEncoding (f : SigFlags) (sig : Bytes) : Bool :=
if sig.isEmpty then true
else if (f.dersig || f.lowS || f.strictenc) && !isValidSignatureEncoding sig then false
else if f.lowS && !isLowDERSignature sig then false
else if f.strictenc && !isDefinedHashtypeSignature sig then false
else true
inductive SigVersion where
| base
| witnessV0
deriving DecidableEq, Repr
/-- `CheckPubKeyEncoding`. -/
def checkPubKeyEncoding (f : SigFlags) (v : SigVersion) (pk : Bytes) : Bool :=
if f.strictenc && !isCompressedOrUncompressedPubKey pk then false
else if f.witnessPubkeyType && v = .witnessV0 && !isCompressedPubKey pk then false
else true
/-! ### The transaction signature checker -/
/-- `GenericTransactionSignatureChecker::CheckECDSASignature`. -/
def checkECDSASignature (tx : Tx) (nIn : Nat) (amount : Int) (v : SigVersion) (sig pk scriptCode : Bytes) : Bool :=
if !pubkeyValid pk then false
else match sig.getLast? with
| none => false
| some ht =>
let sig' := sig.dropLast
let hashType := ht.toNat
let sighash := match v with
| .base => sigHashLegacy scriptCode tx nIn hashType
| .witnessV0 => sigHashWitnessV0 scriptCode tx nIn hashType amount
if v = .witnessV0 ∧ amount < 0 then false
else pubkeyVerify pk sighash sig'
/-- `EvalChecksigPreTapscript`: `FindAndDelete` of the signature push (legacy only), the two encoding
checks (`none` = script error), then the checker's verdict. -/
def checkSigPreTapscript (f : SigFlags) (tx : Tx) (nIn : Nat) (amount : Int) (v : SigVersion)
(scriptCode : Bytes) (sig pk : Bytes) : Option Bool :=
let sc := match v with
| .base => (findAndDelete scriptCode (pushBytes sig)).1
| .witnessV0 => scriptCode
if !checkSignatureEncoding f sig ∨ !checkPubKeyEncoding f v pk then none
else some (checkECDSASignature tx nIn amount v sig pk sc)
def LOCKTIME_THRESHOLD : Nat := 500000000
def SEQUENCE_FINAL : Nat := 0xffffffff
def SEQUENCE_LOCKTIME_DISABLE_FLAG : Nat := 2 ^ 31
def SEQUENCE_LOCKTIME_TYPE_FLAG : Nat := 2 ^ 22
def SEQUENCE_LOCKTIME_MASK : Nat := 0xffff
/-- `GenericTransactionSignatureChecker::CheckLockTime(nLockTime)`. -/
def checkLockTime (tx : Tx) (nIn : Nat) (lockTime : Int) : Bool :=
if ¬ ((tx.nLockTime < LOCKTIME_THRESHOLD ∧ lockTime < LOCKTIME_THRESHOLD) ∨
(LOCKTIME_THRESHOLD ≤ tx.nLockTime ∧ (LOCKTIME_THRESHOLD : Int) ≤ lockTime)) then false
else if (tx.nLockTime : Int) < lockTime then false
else if (tx.vin.getD nIn ⟨⟨[], 0⟩, [], 0, []⟩).nSequence = SEQUENCE_FINAL then false
else true
/-- `GenericTransactionSignatureChecker::CheckSequence(nSequence)`. -/
def checkSequence (tx : Tx) (nIn : Nat) (sequence : Int) : Bool :=
let txToSequence := (tx.vin.getD nIn ⟨⟨[], 0⟩, [], 0, []⟩).nSequence
if tx.version < 2 then false
else if txToSequence &&& SEQUENCE_LOCKTIME_DISABLE_FLAG ≠ 0 then false
else
let mask := SEQUENCE_LOCKTIME_TYPE_FLAG ||| SEQUENCE_LOCKTIME_MASK
let txMasked := txToSequence &&& mask
-- `CScriptNum & mask` on a 5-byte script number: the operand is non-negative here, since
-- `OP_CHECKSEQUENCEVERIFY` rejects negative values before calling the checker
let seqMasked := sequence.toNat &&& mask
if ¬ ((txMasked < SEQUENCE_LOCKTIME_TYPE_FLAG ∧ seqMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ∨
(SEQUENCE_LOCKTIME_TYPE_FLAG ≤ txMasked ∧ SEQUENCE_LOCKTIME_TYPE_FLAG ≤ seqMasked)) then false
else if txMasked < seqMasked then false
else true
/-- The concrete oracle for the legacy interpreter: Core's hashes, the pre-tapscript signature check
on `scriptCode` (the script being executed, for scripts without `OP_CODESEPARATOR`), and the
lock-time checks of the transaction being validated. -/
def legacyOracle (f : SigFlags) (tx : Tx) (nIn : Nat) (amount : Int) (v : SigVersion) (scriptCode : Bytes) :
BitcoinScript.Oracle where
ripemd160 := BitcoinSer.ripemd160
sha1 := BitcoinSer.sha1
sha256 := BitcoinSer.sha256
hash160 := BitcoinSer.hash160
hash256 := BitcoinSer.hash256
checkSig := checkSigPreTapscript f tx nIn amount v scriptCode
checkLockTime := checkLockTime tx nIn
checkSequence := checkSequence tx nIn
/-- The P2PKH output script as bytes: `OP_DUP OP_HASH160 <h> OP_EQUALVERIFY OP_CHECKSIG`. -/
def p2pkhBytes (h : Bytes) : Bytes := [0x76, 0xa9] ++ pushBytes h ++ [0x88, 0xac]
/-- Two transactions with the same version, outputs, lock time, and the same prevouts and sequence
numbers in order (scriptSigs and witnesses may differ): what the signature hashes may depend on. -/
def sameSkeleton (tx tx' : Tx) : Prop :=
tx'.version = tx.version ∧ tx'.vout = tx.vout ∧ tx'.nLockTime = tx.nLockTime ∧
tx'.vin.map (fun i => (i.prevout, i.nSequence)) = tx.vin.map (fun i => (i.prevout, i.nSequence))
/-- The minimal big-endian positive integer encoding DER requires. -/
def minimalInt (v : Bytes) : Prop :=
v ≠ [] ∧ (v.getD 0 0).toNat < 0x80 ∧ (1 < v.length → (v.getD 0 0).toNat = 0 → 0x80 ≤ (v.getD 1 0).toNat)
/-- The DER layout `30 len 02 |r| r 02 |s| s ht`. -/
def derEncode (r s : Bytes) (ht : Byte) : Bytes :=
[0x30, BitVec.ofNat 8 (r.length + s.length + 4), 0x02, BitVec.ofNat 8 r.length] ++ r ++
[0x02, BitVec.ofNat 8 s.length] ++ s ++ [ht]
end BitcoinSig
Read-back
What the Lean code literally says, in plain math · claude-fable-5-1 (independent sub-agent, blind: Lean code + auditor instructions only)
Read-back: Def_BitcoinSig
Scope and ambient types. This file defines, inside a namespace BitcoinSig, a collection of total functions and a few predicates over byte strings and transactions. Throughout, a byte is an 8-bit vector (so a byte's numeric value is an integer in ) and a byte string is a finite list of bytes. Transactions come from the serialization file: a transaction has a natural-number field version, a list of inputs vin, a list of outputs vout, and a natural-number field nLockTime; an input has a prevout (an outpoint: a byte string hash and a natural number n), a byte string scriptSig, a natural number nSequence, and a witness (list of byte strings); an output has an integer nValue and a byte string scriptPubKey. None of these fields is bounded by the types: a version or sequence number may be any natural number, an outpoint hash may have any length. Wherever a list is indexed by a possibly out-of-range index, the code uses "get with default", so a default input (empty prevout hash, prevout index 0, empty scriptSig, sequence 0, no witness) and a default output (value , empty script) silently stand in. The serializers used are: ser32 = the four little-endian bytes of ; serInt64 = the eight little-endian bytes of (two's complement); writeCompactSize = Bitcoin's compact-size prefix; serBytes = compact size of followed by ; serOutPoint = followed by ser32 (so a default outpoint serializes to only four zero bytes, not 36); serTxOut = serInt64 of the value followed by serBytes of the script; hash256 = SHA-256 applied twice; leVal reads a byte string as a little-endian number.
Constants p, n, Gx, Gy. (a natural number computed by truncated subtraction, which here is an honest subtraction). is the literal hexadecimal FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141. and are the literal hexadecimals 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798 and 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8. Nothing in the file proves these are prime, that is on the curve, or that is the order of anything; they are bare numbers.
powModAux and powMod. powModAux is a four-argument recursion on a fuel counter: with fuel it returns the accumulator; with fuel , base , exponent , accumulator : if it returns ; otherwise it recurses with fuel , base , exponent , and accumulator if is odd, else . powMod = powModAux with fuel , base , exponent , accumulator . Since the exponent halves each step, fuel is never exhausted before reaches , so this computes for . For , Lean's , so the function would compute an unreduced power; no caller passes .
finv and ninv. finv = powMod , i.e. . For this is (the accumulator is multiplied by at the first odd bit, since is odd). ninv = , likewise with ninv . No reduction of is required beforehand; powMod reduces the base. These are inverses only when , are prime and ; the file does not state this.
Point, onCurve. A point is either "none" (the point at infinity) or "some " with arbitrary natural numbers, not required to be below or on the curve. onCurve is the Boolean .
padd (affine addition). For points : if is none the result is ; if is none the result is (so none none none). Otherwise, with and :
- if : if the result is none; otherwise the doubling formulas are used with the coordinates of only: , , , result . Note the doubling branch is taken whenever the abscissae agree and the ordinates are not negatives mod , even if (which can only happen for inputs that are not both on the curve); 's ordinate is then ignored. If ,
finvreturns and . - otherwise (distinct abscissae mod ): , , . All outputs have coordinates below ; inputs may be unreduced. No on-curve check is performed.
pmulAux, pmul, G. pmulAux with fuel returns the accumulator; with fuel , scalar , point , accumulator : if returns , else recurses with fuel , scalar , point padd , accumulator padd if odd else . pmul = pmulAux with fuel , scalar , point , accumulator none: right-to-left double-and-add. With fuel 257 any is processed completely; for larger the high bits are silently dropped. = some .
beVal. The big-endian value of a byte string: fold from . The empty string has value . No length limit.
liftXParity odd. Computes (integer division for the exponent). If , returns some where if the parity of (as a natural number, i.e. ) equals the requested Boolean odd, and otherwise; else returns none. Note is not reduced or range-checked here, and the returned abscissa is exactly as given. Edge: if (i.e. ) and odd is true, the returned ordinate is , which is even.
parsePubkey. On the empty string: none. On (first byte ): if the total length is and , let = beVal ; if return liftXParity (odd ordinate exactly when ), else none. Else if the total length is and : = beVal of the first 32 bytes of , = beVal of the remaining 32; return some if and and (if then " is odd" iff ) and onCurve ; else none. In every other case (wrong length for the tag, tag outside ) none. The tag- case has no parity requirement.
pubkeyLen, pubkeyValid. pubkeyLen is for , for , and otherwise. pubkeyValid is false on the empty string and otherwise decides whether pubkeyLen (first byte) equals the actual length. Since a non-empty string has length , an unrecognized header always yields false. This is a header/length check only: no curve membership.
isHighS, normalizeS. isHighS decides . normalizeS = (truncated natural subtraction) if isHighS , else . For (high), truncates to .
scalarOf. Reads big-endian; returns some if , else none. This definition is not used anywhere else in the file.
parseDerLax (lax DER parser). Input: a byte string of length ; at denotes the byte at index or if out of range. Control flow, in order:
- If or
at0x30: none. - Set . If : none. Read =
at; . - Sequence length: if
0x80, let0x80; if (natural subtraction; here) then none, else — the length bytes are skipped, their value is never read. If0x80, stays and the short-form length value is ignored entirely. (Note0x80gives and is accepted.) readInt, used twice: if orat0x02: none. ; if : none. =at; . If0x80:0x80; if : none; then skip up to leading zero bytes among the length bytes (each skip increments and decrements ); if the remaining : none; the integer's length is the big-endian value of the remaining bytes (zero if ); advances past them; if : none; else return (start , length , end ). If0x80: if : none; else return (, , ).- First
readIntat gives or none none. SecondreadIntat gives or none none; the end position of the second integer is discarded, so any trailing bytes after are ignored. - Strip leading zero bytes from each of and (advancing the start, shrinking the length, fuel = the length).
- If the stripped or : some .
- =
beValof the bytes at , likewise. If and : some ; otherwise some . So none is returned only for structural failures (tags, lengths running past the end, a length-of-length of 4 or more bytes); a zero-length integer parses as ; an all-zero or too-long or integer yields the pair , indistinguishable from a signature that genuinely encodes .
ecdsaVerifyRaw . is a point (possibly none), natural numbers. If or or or : false. Else ninv , , , and padd (pmul ) (pmul ). If is none: false; if : the Boolean . is used as given (not reduced here). If is none, .
pubkeyVerify . If not pubkeyValid : false. Else if parsePubkey is none: false. Else with the parsed point: if parseDerLax is none: false; else with : ecdsaVerifyRaw (some ) (beVal ) (normalizeS ). The message is the big-endian value of the byte string reduced mod ; has no length requirement. In particular the constant uint256One below, read this way, is , not . The value is always normalized to the low half before verification, so a high- signature verifies iff its low- twin does.
checkLowS . If parseDerLax is none: false; else true iff the parsed is not high. Note that the overflow result has , so a signature with an overflowing or over-long (or ) passes checkLowS.
taggedHash, ascii, liftX. taggedHash = SHA-256 with = SHA-256. ascii = the UTF-8 bytes of the string , each truncated to 8 bits. liftX = liftXParity false (even ordinate) if , else none.
schnorrVerify . If or : false. = big-endian value of the first 32 bytes of the signature, = of the last 32. If or : false. = liftX(big-endian ); none false. = big-endian value of taggedHash(ascii "BIP0340/challenge") (first 32 signature bytes ), reduced mod . = padd (pmul ) (pmul (some )). If is none: false; if : the Boolean ( even and ). has no length constraint.
OP_PUSHDATA1/2/4. The numbers 0x4c, 0x4d, 0x4e.
getOp . On the empty string: none. On with the value of : if 0x4e, determine a size and remainder: 0x4c size , remainder ; 0x4c size = next byte, remainder after it, none if is empty; 0x4d size = little-endian value of the next 2 bytes, none if fewer than 2; otherwise ( 0x4e) size = little-endian value of the next 4 bytes, none if fewer than 4. Then if the remainder is shorter than the size: none; else some (push of the first size bytes, the rest). If 0x4e: some (op , ). So byte 0x00 is a push of the empty string.
parseScriptAux, parseScript. parseScriptAux with any fuel and empty input: some . Fuel and non-empty input: none. Fuel : getOp; none none; else parse the remainder with fuel and prepend the instruction. parseScript = parseScriptAux with fuel . Since every getOp consumes at least one byte, the fuel is sufficient; the result is none exactly when some push runs past the end of the data.
pushBytes . If 0x4c: the byte followed by (so pushBytes = 0x00). Else if : 0x4c, byte , . Else if : 0x4d, two little-endian length bytes, . Else 0x4e, four little-endian length bytes, (length bytes are truncated mod for absurdly long ).
findAndDeleteAux, findAndDelete. findAndDelete : if is empty, ; else findAndDeleteAux with fuel , remaining , accumulator , count . findAndDeleteAux: with fuel returns (accumulator remaining, count). With fuel : first strip: as long as is a byte-prefix of the remaining string (and remaining length), drop bytes and increment the count (fuel for this inner loop = remaining length , which suffices). Then getOp on what remains: none (accumulator remaining, count) — a malformed tail is appended verbatim; some the consumed bytes (those before ) are appended to the accumulator and the recursion continues on with fuel . So is matched as raw bytes at each instruction boundary (including immediately after a previous deletion), not as a parsed instruction. Each round removes or consumes at least one byte, so the outer fuel suffices.
scriptCodeBytesAux, serScriptCode. scriptCodeBytesAux with fuel returns the input unchanged; otherwise getOp; none the input unchanged (malformed tail kept verbatim); some (the consumed bytes, or if is the opcode instruction with byte 0xab, i.e. OP_CODESEPARATOR) recursion on . serScriptCode = compact size of the length of the stripped body, followed by the body (fuel ).
SIGHASH_* constants and uint256One. SIGHASH_ALL , SIGHASH_NONE , SIGHASH_SINGLE , SIGHASH_ANYONECANPAY . uint256One = the byte followed by 31 zero bytes.
serSigInput . First, if then . Let = the -th input of or the default input. Output: serOutPoint (if then serBytes 0x00 else serScriptCode ) (if and ( or ) then ser32 else ser32 ). The input's own scriptSig and witness are never serialized.
serSigOutput . If and : serTxOut (eight 0xff bytes then 0x00); else serTxOut of the -th output, or of the default if out of range.
serSigTx . := (); := (); := (). = if else . = if , else if , else . Output, in order: ser32 compact size concatenation of serSigInput for compact size concatenation of serSigOutput for ser32 . The hash type is not appended here. If and not , no input ever receives the script code; if , the single serialized input is the default input (4-byte outpoint). Hash types whose low five bits are not or (e.g. , , or –) all serialize as "all outputs".
sigHashLegacy . If and : uint256One. Otherwise hash256(serSigTx ser32 ). Fields serialized: version; input count; per input: prevout, script code (or empty), sequence (or zero); output count; per output: value and script (or /empty); lock time; then the 4-byte hash type. is an unbounded natural number here; ser32 truncates it.
sigHashWitnessV0 . With , , as above and = 32 zero bytes: = hash256 of the concatenation of serOutPoint over all inputs if not , else . = hash256 of the concatenation of ser32 of every input's sequence if not and not and not , else . = hash256 of the concatenation of serTxOut over all outputs if neither nor ; else if and (strict): hash256(serTxOut of output ); else . Let = input or the default. Result: hash256(ser32 version serOutPoint serBytes serInt64 ser32 ser32 nLockTime ser32 ). Here the script code is serialized verbatim with serBytes (no OP_CODESEPARATOR removal, unlike the legacy path), there is no uint256One special case, and a negative is serialized in two's complement without complaint.
isValidSignatureEncoding . With and at as before: false if ; false if ; false if at 0x30; false if at; let = at; false if ; let = at; false if ; false if at 0x02; false if ; false if at 0x80; false if and at and at 0x80; false if at 0x02; false if ; false if at 0x80; false if and at and at 0x80; otherwise true. The final byte (hash type) is never examined. Note that the bound forces .
isLowDERSignature . isValidSignatureEncoding and checkLowS ( with its last byte removed). Both conjuncts are evaluated on the same argument; only the second drops the hash-type byte.
isCompressedOrUncompressedPubKey . Empty: false. Otherwise with first byte : false if ; if : ; if : ; else false (so hybrid / keys are rejected here even though parsePubkey accepts them).
isCompressedPubKey . Non-empty, length , and first byte in .
isDefinedHashtypeSignature . Empty: false. Otherwise with the last byte: 0xff ; true iff .
SigFlags. A record of four Booleans: dersig, lowS, strictenc, witnessPubkeyType.
checkSignatureEncoding . If is empty: true. Else if (.dersig or .lowS or .strictenc) and not isValidSignatureEncoding : false. Else if .lowS and not isLowDERSignature : false. Else if .strictenc and not isDefinedHashtypeSignature : false. Else true. With all four flags false every signature passes.
SigVersion. Two constructors: base and witnessV0.
checkPubKeyEncoding . If .strictenc and not isCompressedOrUncompressedPubKey : false. Else if .witnessPubkeyType and = witnessV0 and not isCompressedPubKey : false. Else true. With both relevant flags false, even the empty key passes.
checkECDSASignature . (Note the argument order: signature, then key, then script code.) If not pubkeyValid : false. If is empty: false. Otherwise let be the last byte of , = without its last byte, (a number in ), and = sigHashLegacy if = base, or sigHashWitnessV0 if = witnessV0. If = witnessV0 and : false. Else pubkeyVerify . The amount is ignored entirely in the base case; pubkeyValid is checked here and again inside pubkeyVerify.
checkSigPreTapscript . Let = the first component of findAndDelete (pushBytes ) if = base, or unchanged if = witnessV0. If checkSignatureEncoding is false or checkPubKeyEncoding is false: none. Otherwise some (checkECDSASignature ). Note that for the empty signature in base mode, pushBytes = 0x00, so every OP_0 byte at an instruction boundary of is deleted before (the inevitably false) verification.
Lock-time constants. LOCKTIME_THRESHOLD , SEQUENCE_FINAL , SEQUENCE_LOCKTIME_DISABLE_FLAG , SEQUENCE_LOCKTIME_TYPE_FLAG , SEQUENCE_LOCKTIME_MASK .
checkLockTime (with an integer, the threshold). False unless (nLockTime and ) or (nLockTime and ). Then false if nLockTime (comparison in the integers). Then false if the sequence of input (or for the default input, which is therefore never "final") equals SEQUENCE_FINAL. Else true. A negative is simply "below the threshold" and, being nLockTime, passes the second test.
checkSequence . Let = the sequence of input (or ). False if (version is an unbounded natural number, so e.g. counts as ). False if . Let , , where a negative becomes . False unless both masked values are or both are . False if . Else true. The disable flag of the argument is not consulted (a comment defers this to the caller).
legacyOracle . A record whose hash fields are the serialization file's RIPEMD-160, SHA-1, SHA-256, Hash160, Hash256; whose checkSig is checkSigPreTapscript awaiting the two remaining arguments (signature, key); whose checkLockTime is checkLockTime ; and whose checkSequence is checkSequence .
p2pkhBytes . 0x76, 0xa9 pushBytes 0x88, 0xac.
sameSkeleton (a proposition). , , , and the lists obtained by mapping each input to the pair (prevout, nSequence) are equal — hence the input counts agree; scriptSigs and witnesses are unconstrained.
minimalInt (a proposition). , the first byte is , and if and the first byte is then the second byte is . The single byte satisfies it; there is no upper bound on .
derEncode . 0x30, , 0x02, 0x02, ; total length .
Observations the auditor may wish to weigh (descriptive only). (i) scalarOf is dead code. (ii) checkLowS returns true on the overflow pair. (iii) The lax parser never reads the sequence-length value and ignores trailing bytes after . (iv) uint256One read by pubkeyVerify is the scalar . (v) The legacy sighash strips OP_CODESEPARATOR from the script code; the witness-v0 sighash does not. (vi) isCompressedOrUncompressedPubKey rejects hybrid keys that parsePubkey accepts. (vii) The default input serializes to a 4-byte outpoint. (viii) checkSequence ignores the disable flag of its argument and maps negative arguments to . (ix) padd's doubling branch ignores 's ordinate. (x) sigHashWitnessV0 uses a strict < for the SINGLE output index, while sigHashLegacy uses ≤ for its special case; the two are complementary.
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.