Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

The Lightning to_local witness script and its two spending conditions

Definition
BitcoinToLocal

by pitimespi · Oct 29, 2026 · Mathlib 0df444a (Lean v4.33.1)

bip112bitcoinbitcoin-mainnetbolt3csvformal-verificationlightningp2wshscript

Names over the script, signature and verification missions; nothing of Core is re-transcribed.

numInstr n / numBytes n — what CScript::operator<<(int64_t) emits for a small integer: OP_1NEGATE for −1-1−1, OP_1 … OP_16 for 111 … 161616, and the CScriptNum push otherwise (the empty push for 000), as an instruction and as bytes.

toLocalScript rev delay dpk — the BOLT #3 to_local witness script OP_IF <rev> OP_ELSE <delay> OP_CHECKSEQUENCEVERIFY OP_DROP <dpk> OP_ENDIF OP_CHECKSIG, parsed; toLocalBytes rev delay dpk — the same as CScript serializes it.

CsvPasses f o delay — what OP_CHECKSEQUENCEVERIFY lets through for the operand delay under flags fff and oracle ooo: the CHECKSEQUENCEVERIFY flag is off, or delay is non-negative and either carries the disable bit (bit 31) or satisfies the oracle's checkSequence.

SpendCondition f o rev delay dpk b sig — the revocation path (bbb true and o.checkSig sig rev = some true) or the delayed path (bbb false, CsvPasses f o delay, and o.checkSig sig dpk = some true), for the witness stack [b, sig] (top first).

inputSequence tx nIn — the nSequence of input nIn of a transaction (an empty input when out of range).

Formalization Note. Flags, Oracle, evalScript, serialize, castToBool are the script mission's; legacyOracle, checkSequence, parseScript, pushBytes the signature mission's; verifyScript, executeWitnessScriptV0, topTrue, witnessBytes the verification mission's. Only Std is imported. MINIMALIF is a policy flag and is off, so any true value selects the revocation branch under consensus.

Definition code
import Definitions.Def_BitcoinVerify

/-!
# The Lightning `to_local` output under Bitcoin's script interpreter

BOLT #3 (Lightning Network specification, *Bitcoin Transaction and Script Formats*) gives the
`to_local` output of a commitment transaction the witness script

```
OP_IF
    <revocationpubkey>
OP_ELSE
    `to_self_delay`
    OP_CHECKSEQUENCEVERIFY
    OP_DROP
    <local_delayedpubkey>
OP_ENDIF
OP_CHECKSIG
```

paid to as pay-to-witness-script-hash. The intent is that the output can be spent either by the
counterparty with the revocation key at any time, or by the local node with its delayed key once
`to_self_delay` blocks have passed. This file states that script as the script and verification
missions model it, so that the two spending conditions can be proved to be exactly what the
interpreter enforces.
-/

namespace BitcoinToLocal

open BitcoinScript BitcoinSig BitcoinVerify

/-- `CScript::operator<<(int64_t n)`: `OP_1NEGATE` for `-1`, `OP_1` … `OP_16` for `1` … `16`, and the
`CScriptNum` push otherwise (`OP_0`, the empty push, for `0`). -/
def numInstr (n : Int) : Instr :=
  if n = -1 ∨ (1 ≤ n ∧ n ≤ 16) then .op (BitVec.ofNat 8 (n + (OP_1.toNat - 1)).toNat)
  else .push (serialize n)

/-- The bytes `CScript::operator<<(int64_t n)` appends. -/
def numBytes (n : Int) : Bytes :=
  if n = -1 ∨ (1 ≤ n ∧ n ≤ 16) then [BitVec.ofNat 8 (n + (OP_1.toNat - 1)).toNat]
  else pushBytes (serialize n)

/-- The BOLT #3 `to_local` witness script, parsed. -/
def toLocalScript (revocationPubkey : Bytes) (toSelfDelay : Int) (localDelayedPubkey : Bytes) : Script :=
  [.op OP_IF, .push revocationPubkey, .op OP_ELSE, numInstr toSelfDelay, .op OP_CHECKSEQUENCEVERIFY,
   .op OP_DROP, .push localDelayedPubkey, .op OP_ENDIF, .op OP_CHECKSIG]

/-- The BOLT #3 `to_local` witness script, as `CScript` serializes it. -/
def toLocalBytes (revocationPubkey : Bytes) (toSelfDelay : Int) (localDelayedPubkey : Bytes) : Bytes :=
  [OP_IF] ++ pushBytes revocationPubkey ++ [OP_ELSE] ++ numBytes toSelfDelay ++
    [OP_CHECKSEQUENCEVERIFY, OP_DROP] ++ pushBytes localDelayedPubkey ++ [OP_ENDIF, OP_CHECKSIG]

/-- What `OP_CHECKSEQUENCEVERIFY` lets through for the operand `delay`: nothing is checked when the
`CHECKSEQUENCEVERIFY` flag is off; otherwise the operand must be non-negative and either carry the
disable flag (bit 31) or satisfy the checker's `CheckSequence`. -/
def CsvPasses (f : Flags) (o : Oracle) (delay : Int) : Prop :=
  f.csv = false ∨ (0 ≤ delay ∧ ((delay.toNat &&& BitcoinScript.SEQUENCE_LOCKTIME_DISABLE_FLAG) ≠ 0 ∨ o.checkSequence delay = true))

instance (f : Flags) (o : Oracle) (delay : Int) : Decidable (CsvPasses f o delay) := by
  unfold CsvPasses; infer_instance

/-- The two ways of satisfying the `to_local` script with the witness stack `[b, sig]` (top first):
the revocation path, `b` true and `sig` valid for the revocation key; or the delayed path, `b` false,
the delay check passing, and `sig` valid for the delayed key. -/
def SpendCondition (f : Flags) (o : Oracle) (revocationPubkey : Bytes) (toSelfDelay : Int)
    (localDelayedPubkey : Bytes) (b sig : Bytes) : Prop :=
  (castToBool b = true ∧ o.checkSig sig revocationPubkey = some true) ∨
  (castToBool b = false ∧ CsvPasses f o toSelfDelay ∧ o.checkSig sig localDelayedPubkey = some true)

/-- The `nSequence` of input `nIn` of a transaction (an empty input when out of range). -/
def inputSequence (tx : BitcoinSer.Tx) (nIn : Nat) : Nat := (tx.vin.getD nIn ⟨⟨[], 0⟩, [], 0, []⟩).nSequence

end BitcoinToLocal
Source
BOLT #3, Bitcoin Transaction and Script Formats, 'to_local Output': https://github.com/lightning/bolts/blob/master/03-transactions.md#to_local-output; Bitcoin Core a773e1e33b349dc819b5a0edc1c7a4839dc73b48: EvalScript (OP_IF/OP_ELSE/OP_ENDIF, OP_CHECKSEQUENCEVERIFY, OP_CHECKSIG), GenericTransactionSignatureChecker::CheckSequence, ExecuteWitnessScript, VerifyWitnessProgram (src/script/interpreter.cpp: https://github.com/bitcoin/bitcoin/blob/a773e1e33b349dc819b5a0edc1c7a4839dc73b48/src/script/interpreter.cpp); CScript::operator<<(int64_t) (script/script.h); BIP68, BIP112, BIP141
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_BitcoinToLocal.lean

Throughout, a byte is an 8-bit word, a byte string is a finite list of bytes, and ∣x∣|x|∣x∣ denotes the length of a list xxx. Stacks are lists written top-first. Bitwise operations &\mathbin{\&}&, ∣\mid∣ act on natural numbers. Integer-to-natural truncation toNat⁡(z)\operatorname{toNat}(z)toNat(z) sends every negative integer to 000 and fixes non-negative ones. Several notions from the preamble are unfolded where first used.


1. numInstr

For an integer nnn, numInstr(n)\mathrm{numInstr}(n)numInstr(n) is a single parsed script instruction (an instruction is either a data push carrying a byte string, or a non-push opcode carrying one byte), defined by cases:

  • if n=−1n = -1n=−1, or 1≤n≤161 \le n \le 161≤n≤16, it is the opcode whose byte is toNat⁡(n+80)\operatorname{toNat}(n + 80)toNat(n+80) reduced modulo 256256256 (the constant 808080 is 0x51−1\mathtt{0x51} - 10x51−1, where 0x51=81\mathtt{0x51} = 810x51=81 is the byte called OP_1). Concretely this is byte 0x4f\mathtt{0x4f}0x4f (=79=79=79) for n=−1n=-1n=−1 and bytes 0x51,…,0x60\mathtt{0x51},\dots,\mathtt{0x60}0x51,…,0x60 (=81,…,96=81,\dots,96=81,…,96) for n=1,…,16n = 1,\dots,16n=1,…,16; no truncation or modular reduction actually occurs in this branch;
  • otherwise (so for n=0n = 0n=0, n≤−2n \le -2n≤−2, or n≥17n \ge 17n≥17), it is the data push of serialize(n)\mathrm{serialize}(n)serialize(n).

Here serialize:Z→\mathrm{serialize} : \mathbb{Z} \toserialize:Z→ byte strings is the following encoding: serialize(0)=[ ]\mathrm{serialize}(0) = [\,]serialize(0)=[] (the empty string). For v≠0v \ne 0v=0 let mmm be the little-endian base-256256256 digit list of ∣v∣|v|∣v∣ with no trailing zero bytes (so mmm is non-empty and its last byte is non-zero). If the last byte of mmm has its 0x80\mathtt{0x80}0x80 bit set, the result is mmm followed by one extra byte, 0x80\mathtt{0x80}0x80 if v<0v<0v<0 and 0x00\mathtt{0x00}0x00 if v>0v>0v>0; otherwise, if v<0v<0v<0 the result is mmm with the 0x80\mathtt{0x80}0x80 bit set on its last byte, and if v>0v>0v>0 the result is mmm itself. In particular numInstr(0)\mathrm{numInstr}(0)numInstr(0) is a push of the empty byte string.

2. numBytes

For an integer nnn, numBytes(n)\mathrm{numBytes}(n)numBytes(n) is a byte string:

  • if n=−1n = -1n=−1 or 1≤n≤161 \le n \le 161≤n≤16, the one-byte string [toNat⁡(n+80) mod 256][\operatorname{toNat}(n+80) \bmod 256][toNat(n+80)mod256], i.e. [0x4f][\mathtt{0x4f}][0x4f] for n=−1n=-1n=−1 and [0x51],…,[0x60][\mathtt{0x51}],\dots,[\mathtt{0x60}][0x51],…,[0x60] for n=1,…,16n=1,\dots,16n=1,…,16;
  • otherwise pushBytes(serialize(n))\mathrm{pushBytes}(\mathrm{serialize}(n))pushBytes(serialize(n)).

Here pushBytes(d)\mathrm{pushBytes}(d)pushBytes(d), for a byte string ddd, is: if ∣d∣<76|d| < 76∣d∣<76 (0x4c\mathtt{0x4c}0x4c), the byte ∣d∣|d|∣d∣ followed by ddd; else if ∣d∣≤255|d| \le 255∣d∣≤255, the bytes 0x4c,∣d∣\mathtt{0x4c}, |d|0x4c,∣d∣ followed by ddd; else if ∣d∣≤65535|d| \le 65535∣d∣≤65535, the byte 0x4d\mathtt{0x4d}0x4d, then the two-byte little-endian encoding of ∣d∣|d|∣d∣, then ddd; otherwise the byte 0x4e\mathtt{0x4e}0x4e, the four-byte little-endian encoding of ∣d∣|d|∣d∣, then ddd. In particular numBytes(0)=pushBytes([ ])=[0x00]\mathrm{numBytes}(0) = \mathrm{pushBytes}([\,]) = [\mathtt{0x00}]numBytes(0)=pushBytes([])=[0x00].

3. toLocalScript

For byte strings RRR (named revocationPubkey) and DDD (named localDelayedPubkey) and an integer ddd (named toSelfDelay), toLocalScript(R,d,D)\mathrm{toLocalScript}(R, d, D)toLocalScript(R,d,D) is the following list of exactly nine instructions, in this order:

[ op 0x63,  push R,  op 0x67,  numInstr(d),  op 0xb2,  op 0x75,  push D,  op 0x68,  op 0xac ]\big[\ \mathrm{op}\,\mathtt{0x63},\ \ \mathrm{push}\,R,\ \ \mathrm{op}\,\mathtt{0x67},\ \ \mathrm{numInstr}(d),\ \ \mathrm{op}\,\mathtt{0xb2},\ \ \mathrm{op}\,\mathtt{0x75},\ \ \mathrm{push}\,D,\ \ \mathrm{op}\,\mathtt{0x68},\ \ \mathrm{op}\,\mathtt{0xac}\ \big][ op0x63,  pushR,  op0x67,  numInstr(d),  op0xb2,  op0x75,  pushD,  op0x68,  op0xac ]

where the opcode bytes are named in the preamble OP_IF (0x63\mathtt{0x63}0x63), OP_ELSE (0x67\mathtt{0x67}0x67), OP_CHECKSEQUENCEVERIFY (0xb2\mathtt{0xb2}0xb2), OP_DROP (0x75\mathtt{0x75}0x75), OP_ENDIF (0x68\mathtt{0x68}0x68), OP_CHECKSIG (0xac\mathtt{0xac}0xac). No restriction is placed on ∣R∣|R|∣R∣, ∣D∣|D|∣D∣, or ddd by this definition; the fourth instruction is an opcode when d∈{−1,1,…,16}d \in \{-1, 1, \dots, 16\}d∈{−1,1,…,16} and a data push of serialize(d)\mathrm{serialize}(d)serialize(d) otherwise (the empty push when d=0d = 0d=0).

4. toLocalBytes

For RRR, ddd, DDD as above, toLocalBytes(R,d,D)\mathrm{toLocalBytes}(R, d, D)toLocalBytes(R,d,D) is the byte string obtained by concatenation:

[0x63]+ ⁣ ⁣+pushBytes(R)+ ⁣ ⁣+[0x67]+ ⁣ ⁣+numBytes(d)+ ⁣ ⁣+[0xb2,0x75]+ ⁣ ⁣+pushBytes(D)+ ⁣ ⁣+[0x68,0xac],[\mathtt{0x63}] \mathbin{+\!\!+} \mathrm{pushBytes}(R) \mathbin{+\!\!+} [\mathtt{0x67}] \mathbin{+\!\!+} \mathrm{numBytes}(d) \mathbin{+\!\!+} [\mathtt{0xb2}, \mathtt{0x75}] \mathbin{+\!\!+} \mathrm{pushBytes}(D) \mathbin{+\!\!+} [\mathtt{0x68}, \mathtt{0xac}],[0x63]++pushBytes(R)++[0x67]++numBytes(d)++[0xb2,0x75]++pushBytes(D)++[0x68,0xac],

with pushBytes\mathrm{pushBytes}pushBytes and numBytes\mathrm{numBytes}numBytes as unfolded above. Again there is no restriction on RRR, DDD, ddd; for ∣R∣|R|∣R∣ or ∣D∣|D|∣D∣ above 757575 the push prefix becomes the two-byte (0x4c\mathtt{0x4c}0x4c) or longer forms.

5. CsvPasses

Let fff be a flag record — a triple of booleans (f.cltv,f.csv,f.nulldummy)(f.\mathrm{cltv}, f.\mathrm{csv}, f.\mathrm{nulldummy})(f.cltv,f.csv,f.nulldummy) — and let ooo be an oracle: a record of eight arbitrary functions, five hash functions ripemd160,sha1,sha256,hash160,hash256\mathrm{ripemd160}, \mathrm{sha1}, \mathrm{sha256}, \mathrm{hash160}, \mathrm{hash256}ripemd160,sha1,sha256,hash160,hash256 from byte strings to byte strings, a function o.checkSigo.\mathrm{checkSig}o.checkSig from two byte strings (signature first, public key second) to an optional boolean (either "none" or "some bbb" with bbb a boolean), o.checkLockTime:Z→Boolo.\mathrm{checkLockTime} : \mathbb{Z} \to \mathrm{Bool}o.checkLockTime:Z→Bool and o.checkSequence:Z→Boolo.\mathrm{checkSequence} : \mathbb{Z} \to \mathrm{Bool}o.checkSequence:Z→Bool. Nothing is assumed about these functions. For an integer δ\deltaδ (named delay), the proposition CsvPasses(f,o,δ)\mathrm{CsvPasses}(f, o, \delta)CsvPasses(f,o,δ) is

f.csv=false  ∨  (0≤δ ∧ ((toNat⁡(δ)&231)≠0  ∨  o.checkSequence(δ)=true)),f.\mathrm{csv} = \mathrm{false}\ \ \lor\ \ \Big( 0 \le \delta\ \land\ \big( (\operatorname{toNat}(\delta) \mathbin{\&} 2^{31}) \ne 0\ \ \lor\ \ o.\mathrm{checkSequence}(\delta) = \mathrm{true} \big) \Big),f.csv=false  ∨  (0≤δ ∧ ((toNat(δ)&231)=0  ∨  o.checkSequence(δ)=true)),

where 231=21474836482^{31} = 2147483648231=2147483648 is the constant the preamble calls SEQUENCE_LOCKTIME_DISABLE_FLAG (the script-layer copy of it). Edge cases: when f.csv=falsef.\mathrm{csv} = \mathrm{false}f.csv=false the proposition holds for every δ\deltaδ, negative or not, whatever ooo is; when f.csv=truef.\mathrm{csv} = \mathrm{true}f.csv=true every negative δ\deltaδ fails it (the truncation toNat⁡\operatorname{toNat}toNat is never evaluated on a negative in a way that matters, because of the guard 0≤δ0 \le \delta0≤δ); when f.csv=truef.\mathrm{csv} = \mathrm{true}f.csv=true and δ≥0\delta \ge 0δ≥0 has bit 313131 set, it holds regardless of o.checkSequenceo.\mathrm{checkSequence}o.checkSequence; otherwise it holds exactly when o.checkSequence(δ)=trueo.\mathrm{checkSequence}(\delta) = \mathrm{true}o.checkSequence(δ)=true.

6. Decidability instance for CsvPasses

For every fff, ooo, δ\deltaδ the proposition CsvPasses(f,o,δ)\mathrm{CsvPasses}(f, o, \delta)CsvPasses(f,o,δ) is given a decision procedure (obtained by unfolding the definition and combining the decidability of boolean equality, integer order, natural-number disequality, and the connectives). This declaration asserts nothing mathematical beyond that; it is what allows later statements to write "if CsvPasses(f,o,δ)\mathrm{CsvPasses}(f,o,\delta)CsvPasses(f,o,δ) then …\dots… else …\dots…" as a computable branch.

7. SpendCondition

For a flag record fff, an oracle ooo, byte strings RRR (revocationPubkey), DDD (localDelayedPubkey), an integer ddd (toSelfDelay), and two further byte strings bbb and sig\mathrm{sig}sig, the proposition SpendCondition(f,o,R,d,D,b,sig)\mathrm{SpendCondition}(f, o, R, d, D, b, \mathrm{sig})SpendCondition(f,o,R,d,D,b,sig) is the disjunction

(castToBool(b)=true ∧ o.checkSig(sig,R)=some true)  ∨  (castToBool(b)=false ∧ CsvPasses(f,o,d) ∧ o.checkSig(sig,D)=some true).\big( \mathrm{castToBool}(b) = \mathrm{true}\ \land\ o.\mathrm{checkSig}(\mathrm{sig}, R) = \mathrm{some}\,\mathrm{true} \big) \ \ \lor\ \ \big( \mathrm{castToBool}(b) = \mathrm{false}\ \land\ \mathrm{CsvPasses}(f, o, d)\ \land\ o.\mathrm{checkSig}(\mathrm{sig}, D) = \mathrm{some}\,\mathrm{true} \big).(castToBool(b)=true ∧ o.checkSig(sig,R)=sometrue)  ∨  (castToBool(b)=false ∧ CsvPasses(f,o,d) ∧ o.checkSig(sig,D)=sometrue).

Here castToBool\mathrm{castToBool}castToBool of a byte string is: false\mathrm{false}false for the empty string; for a one-byte string [x][x][x], true iff x≠0x \ne 0x=0 and x≠0x80x \ne \mathtt{0x80}x=0x80; for a string x::restx :: \mathrm{rest}x::rest with rest\mathrm{rest}rest non-empty, true iff x≠0x \ne 0x=0 or castToBool(rest)\mathrm{castToBool}(\mathrm{rest})castToBool(rest). Equivalently, some byte is non-zero, except that a string whose only non-zero byte is its last byte and that byte equals 0x80\mathtt{0x80}0x80 is false. The two disjuncts are mutually exclusive since castToBool(b)\mathrm{castToBool}(b)castToBool(b) is a single boolean. In both disjuncts the oracle's signature check must return exactly some true\mathrm{some}\,\mathrm{true}sometrue: the outcomes "none" and "some false\mathrm{some}\,\mathrm{false}somefalse" both fail the condition. CsvPasses\mathrm{CsvPasses}CsvPasses is as in item 5; note it is trivially satisfied when f.csv=falsef.\mathrm{csv} = \mathrm{false}f.csv=false.

8. inputSequence

A transaction tx\mathrm{tx}tx is a record with fields version∈N\mathrm{version} \in \mathbb{N}version∈N, vin\mathrm{vin}vin (a list of inputs), vout\mathrm{vout}vout (a list of outputs) and nLockTime∈N\mathrm{nLockTime} \in \mathbb{N}nLockTime∈N; an input is a record with fields prevout\mathrm{prevout}prevout (a pair of a byte string and a natural), scriptSig\mathrm{scriptSig}scriptSig (a byte string), nSequence∈N\mathrm{nSequence} \in \mathbb{N}nSequence∈N, and witness\mathrm{witness}witness (a list of byte strings). No upper bound on version\mathrm{version}version or nSequence\mathrm{nSequence}nSequence is imposed by these types. For a transaction tx\mathrm{tx}tx and a natural ninn_{\mathrm{in}}nin​,

inputSequence(tx,nin)=(tx.vin[nin]).nSequence,\mathrm{inputSequence}(\mathrm{tx}, n_{\mathrm{in}}) = \big(\mathrm{tx}.\mathrm{vin}[n_{\mathrm{in}}]\big).\mathrm{nSequence},inputSequence(tx,nin​)=(tx.vin[nin​]).nSequence,

the sequence number of the ninn_{\mathrm{in}}nin​-th input (zero-indexed), where if nin≥∣tx.vin∣n_{\mathrm{in}} \ge |\mathrm{tx}.\mathrm{vin}|nin​≥∣tx.vin∣ the "default input" (([ ],0),[ ],0,[ ])(([\,],0), [\,], 0, [\,])(([],0),[],0,[]) is used instead, so the value is 000 in that out-of-range case.

Human review
  • Endorsed by Shuze Chen · Oct 29, 2026

    Confirmed by the moderator at approval.

  • Endorsed by pitimespi · Oct 29, 2026

    Confirmed by the mission captain (proposal self-audit).

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me