Every transaction type we have studied—P2PKH, P2WSH, multisig, timelocks, RBF, CPFP—converges in the Lightning Network. Lightning is not a separate blockchain or token; it is a protocol for constructing Bitcoin transactions that parties hold but do not broadcast, updating them off-chain until a final settlement is written to the blockchain.
This chapter examines the on-chain transaction anatomy of Lightning: the funding transaction that opens a channel, the commitment transactions that track balances, the HTLC outputs that route payments, and the closing transactions that settle on-chain. All formats follow BOLT 3†, the Lightning specification for on-chain transactions.
A Lightning channel begins with a funding transaction: an on-chain transaction that locks bitcoin into a 2-of-2 P2WSH multisig output.
The funding output is a P2WSH whose witness script is:
OP_2 <pubkey1> <pubkey2> OP_2 OP_CHECKMULTISIG
where pubkey1 is the lexicographically lesser of the two funding public keys (compressed, 33 bytes each) and pubkey2 is the greater. The canonical ordering ensures both parties derive the same script and the same P2WSH address.
Once the funding transaction confirms on-chain:
The funding output is never spent during normal operation. It sits on-chain, holding the channel's capacity, while the commitment transactions (held off-chain) track the current balance.
A 2-of-2 multisig ensures that neither party can spend the funds unilaterally during normal operation. Both signatures are required to create any valid transaction spending the funding output. This mutual control is what makes the off-chain update mechanism safe: neither party can steal by broadcasting a transaction the other hasn't co-signed.
The core innovation of Lightning is the commitment transaction: a pre-signed Bitcoin transaction that both parties hold but do not broadcast. Each commitment transaction spends the funding output and distributes the channel's balance according to the current state.
A critical design choice: each party holds a different commitment transaction for the same state. Alice's version and Bob's version distribute the same balances, but they differ in two important ways:
to_local output) and gives Bob his funds immediately (the to_remote output).The delay on the broadcaster's own funds creates a window for the counterparty to detect and punish a revoked commitment (an old state).
Per BOLT 3, a commitment transaction has:
| Field | Value |
|---|---|
| Version | 2 |
| Input | Funding outpoint (2-of-2 P2WSH) |
| nSequence | Upper 8 bits = 0x80, lower 24 bits = upper 24 bits of obscured commitment # |
| nLockTime | Upper 8 bits = 0x20, lower 24 bits = lower 24 bits of obscured commitment # |
| Outputs | to_local, to_remote, HTLCs, anchors |
The 48-bit commitment number is obscured by XOR with the lower 48 bits of: \[ \text{SHA256}(\textit{payment\_basepoint}_A \| \textit{payment\_basepoint}_B) \] This hides how many state updates have occurred. The nLockTime carries the lower 24 bits and nSequence carries the upper 24 bits, so together they reconstruct the full obscured value. The 0x20 prefix places nLockTime above 500,000,000 (interpreted as a past Unix timestamp), and the 0x80 prefix sets bit 31 of nSequence (disabling BIP 68)—neither field imposes an actual lock.
The to_local output returns funds to the commitment's owner, but with two spending paths:
OP_IF
<revocationpubkey>
OP_ELSE
<to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP
<local_delayedpubkey>
OP_ENDIF
OP_CHECKSIG
to_self_delay blocks (typically 144–2,016). Witness: <local_sig> <><revocation_sig> 1The counterparty's funds. In the simplest case, this is a standard P2WPKH output, immediately spendable with no delay.
With option_anchors (the modern default), the to_remote output adds a 1-block CSV lock:
<remotepubkey> OP_CHECKSIGVERIFY
1 OP_CHECKSEQUENCEVERIFY
This 1-block delay ensures the output cannot be spent in the same block as the commitment, preventing certain fee-manipulation attacks.
Every time the channel state updates (a payment is made), both parties:
Once Alice reveals her old revocation secret, she has effectively "destroyed" her old commitment: if she broadcasts it, Bob can use the revocation key to claim all channel funds (not just his share—all of it). This is the penalty mechanism that keeps Lightning honest.
If a party broadcasts a revoked commitment, the counterparty can claim the entire channel balance—not just their share. This harsh penalty ensures that broadcasting old states is economically irrational: you lose everything, even the funds that were legitimately yours. This is why watchtowers exist: automated services that monitor the blockchain for revoked commitments and broadcast penalty transactions on the user's behalf.
When a payment is routed through a channel, it appears as an HTLC output on the commitment transaction. Each in-flight payment adds an HTLC output with two spending paths:
Both paths additionally include a revocation clause (if the commitment is revoked, the counterparty claims everything).
BOLT 3 defines two HTLC types:
The offered HTLC witness script (without option_anchors) illustrates all three spending paths:
OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
OP_IF
OP_CHECKSIG revocation path
OP_ELSE
<remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
OP_NOTIF
OP_DROP 2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
timeout path
OP_ELSE
OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
OP_CHECKSIG preimage path
OP_ENDIF
OP_ENDIF
<revocation_sig> <revocationpubkey>. The script hashes the key, matches it against the revocation hash, and verifies the signature.<remote_sig> <payment_preimage>. The OP_SIZE 32 OP_EQUAL check distinguishes a 32-byte preimage from a public key; the script verifies the hash and signature.nLockTime set to the CLTV expiry). The 2-of-2 OP_CHECKMULTISIG requires both local and remote HTLC signatures, ensuring the timeout cannot be claimed unilaterally before expiry.HTLC outputs are resolved via separate HTLC-success and HTLC-timeout transactions (second-stage transactions), each of which includes its own CSV delay. This two-stage design separates the HTLC resolution from the to_self_delay, preventing the delay from extending HTLC timeouts across the network.
A Lightning channel can close in three ways:
Both parties agree on the final balance and co-sign a closing transaction that spends the funding output directly to each party's address. No timelocks, no HTLCs, no delays—the simplest and most efficient close.
One party broadcasts their latest commitment transaction. The broadcaster's funds are subject to the CSV delay (to_local); the counterparty receives their funds immediately (to_remote). Any in-flight HTLCs are resolved on-chain via HTLC-success or HTLC-timeout transactions.
Force closes are expensive: multiple on-chain transactions, each paying fees, and funds locked for the delay period.
If a party broadcasts a revoked commitment, the counterparty detects it (directly or via a watchtower) and broadcasts a penalty transaction that sweeps all outputs using the revocation key. The cheating party loses their entire channel balance.
Commitment transactions are pre-signed, so their fee is fixed at signing time. If the fee market changes between signing and broadcast, the commitment may be too expensive (wasting funds) or too cheap (failing to confirm).
Anchor outputs solve this by attaching small, spendable outputs (330 sats each, per BOLT 3) to the commitment. Each party gets its own anchor, locked to their funding key:
<local_funding_pubkey> OP_CHECKSIG OP_IFDUP
OP_NOTIF
OP_16 OP_CHECKSEQUENCEVERIFY
OP_ENDIF
The keyholder spends immediately with <sig>. If the anchor remains unspent for 16 blocks, anyone can sweep it with an empty witness (<>), preventing UTXO set pollution. This "self-cleaning" design ensures abandoned anchors do not bloat the UTXO set indefinitely.
Either party can use CPFP (Chapter 17) to attach a high-fee child to their anchor, adjusting the effective feerate at broadcast time.
With TRUC transactions and package relay (also Chapter 17), this mechanism is further improved: the commitment can pay minimal or even zero fees, with the child transaction covering the full cost.
The Lightning channel lifecycle ties together nearly every concept in this book: P2WSH (funding output), multisig (2-of-2), CSV (to_local delay), CLTV (HTLC timeouts), hash preimages (HTLC success), SegWit (witness-based scripts), RBF/CPFP (fee management), and TRUC/package relay (anchor outputs). Lightning is not built beside Bitcoin—it is built from Bitcoin's transaction primitives.
to_local output has two paths: normal (CSV delay) and revocation (immediate, for penalty).Lightning uses Bitcoin's transaction primitives for payments. Chapter 19 explores a very different use of transaction anatomy: Ordinals and Inscriptions, which embed arbitrary data—images, text, even programs—into the witness field, turning Bitcoin into a data layer.
*Exercises
to_local output have a CSV delay?to_local witness script for a channel with to_self_delay = 144 blocks. What nSequence value must the spending input use?*Solutions
L1. A 2-of-2 P2WSH multisig output. The witness script is OP_2 <pubkey1> <pubkey2> OP_2 OP_CHECKMULTISIG, with keys in lexicographic order.
L2. The CSV delay creates a time window during which the counterparty can detect and punish a revoked commitment. Without the delay, the broadcaster could spend their output immediately, leaving no opportunity for the penalty transaction.
L3. The counterparty can claim the entire channel balance using the revocation key. The broadcaster loses all funds—not just the counterparty's share, but their own share too. This is the penalty mechanism.
L4. (1) Cooperative close (both parties agree, no delays). (2) Force close (one party broadcasts their latest commitment, CSV delays apply). (3) Breach remedy / penalty (revoked commitment detected, all funds swept).
L5. Anchor outputs (330 sats each) allow either party to fee-bump the commitment transaction via CPFP after broadcast. This decouples the fee decision from the signing time.
H1. The to_local witness script:
OP_IF
<revocationpubkey>
OP_ELSE
02 90 00 OP_CHECKSEQUENCEVERIFY OP_DROP
<local_delayedpubkey>
OP_ENDIF
OP_CHECKSIG
The spending input must set \(\texttt{nSequence} = 144 = \texttt{0x00000090}\) (BIP 68 block-based relative timelock). In the witness: <local_sig> <> (the empty vector selects the OP_ELSE branch).
H2. Target: 20 sat/vB for the package. Package = commitment (900 vB, 500 sats) + child. Assume a minimal P2WPKH child spending the 330-sat anchor: 141 vB.
Required package feerate: \((500 + f) / (900 + 141) = 20\), so \(f = 20 \times 1,041 - 500 = 20,320\) sats.
The child must pay 20,320 sats in fees (144 sat/vB for the child alone). The child spends the 330-sat anchor, so it needs an additional input providing at least \(20,320 - 330 = 19,990\) sats.
H3. If C claims the preimage from B (settling the BC HTLC), B must relay the preimage upstream to settle the AB HTLC before A's timeout. If A's timeout were \(\leq\) B's, then A could reclaim funds via timeout before B can settle—B would lose the payment. The decreasing timeouts (\(n+40 > n+20\)) give each hop a safety margin to propagate the preimage upstream.
P1. If both parties held identical commitments, the revocation mechanism would fail. When Alice reveals her revocation secret, she would also be revealing the key to her own commitment—Bob could use it against her even if she broadcast the current (non-revoked) state. Asymmetric commitments solve this: Alice's revocation secret only compromises Alice's version of the commitment. Bob's version has a different revocation key derived from Bob's secret. Each party can safely reveal old secrets without compromising their current commitment.
P2. If HTLC outputs were resolved directly from the commitment (without second-stage transactions), the CSV to_self_delay would apply to HTLC resolution. This would extend the effective HTLC timeout by the delay period. For multi-hop payments, each hop adds delay, so a 144-block delay per hop on a 5-hop route would add 720 blocks (5 days) to the HTLC timeout. Second-stage transactions decouple the CSV delay from HTLC resolution: the HTLC can be resolved (success or timeout) immediately, and only the resulting output is delayed. This keeps HTLC timeouts reasonable across the network.
P3. Broadcasting a revoked commitment is economically rational only if the counterparty cannot detect it before the CSV delay expires—i.e., the counterparty is offline and has no watchtower. If detected, the broadcaster loses their entire balance (penalty). The expected value of cheating is: \(P(undetected) \times gain - P(detected) \times entire_{balance}\). As long as the counterparty (or their watchtower) monitors the chain, \(P(detected) \approx 1\), making cheating deeply irrational. The penalty must be total (not proportional) to ensure the expected value is negative even for small probability of detection.
C1. Timelocks in a Lightning force close:
0x20 prefix makes it a past Unix timestamp—not a functional lock.0x80 prefix disables BIP 68.to_local: prevents the broadcaster from spending their own funds for the delay period—the revocation window.to_remote (anchors): 1-block delay prevents same-block spending.C2. Pre-SegWit, transaction malleability allowed third parties (or miners) to modify the txid of the funding transaction without invalidating it. If the funding txid changes, every commitment transaction (which references the funding outpoint) becomes invalid—the entire channel breaks. SegWit fixes this by moving the witness (the malleable part) outside the txid calculation. The funding transaction's txid is stable, so all commitment transactions remain valid. This is why Lightning was not practical before SegWit's activation in August 2017.
B1. In theory, witness data in a commitment transaction could contain an inscription envelope. In practice, this is impractical: commitment transactions are pre-signed by both parties, and the witness data is tightly specified by BOLT 3 (signatures, keys, hash preimages). Adding arbitrary inscription data would require both parties to agree to include it and would increase the transaction's weight, raising fees. Lightning commitment transactions are designed for minimal on-chain footprint, which is the opposite of inscriptions' goal.
B2. Lightning excels for frequent, small payments between parties with established channels: near-zero marginal cost, instant finality, and no on-chain footprint. On-chain batching excels for one-time payments to many recipients: a single transaction with many outputs. Lightning requires channel setup (on-chain funding transaction) and liquidity management; batching requires only one on-chain transaction but no persistent relationship. For recurring payments to the same parties, Lightning is far more efficient. For one-time distributions (e.g., exchange withdrawals), batching is simpler.