Part VI · Protocol Layer Chapter 17

Lightning Network: Payment Channels

"Lightning is a protocol for making fast payments with Bitcoin using a network of channels."—BOLT #0: Introduction (2017)

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.

17.1The Funding Transaction

A Lightning channel begins with a funding transaction: an on-chain transaction that locks bitcoin into a 2-of-2 P2WSH multisig output.

17.1.1The Funding Output Script

The funding output is a P2WSH whose witness script is:

Funding Output Witness Script (BOLT 3)

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.

17.1.2Channel Lifecycle

Once the funding transaction confirms on-chain:

  1. The channel is open: both parties can send and receive payments through it.
  2. Payments are made by exchanging commitment transactions—pre-signed transactions that spend the funding output—without broadcasting them.
  3. When the parties are done, they close the channel by broadcasting a final transaction.

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.

Why 2-of-2 Multisig?

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.

17.2Commitment Transactions

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.

17.2.1Asymmetric Commitments

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:

  1. Alice's commitment gives Alice her funds with a CSV delay (the to_local output) and gives Bob his funds immediately (the to_remote output).
  2. Bob's commitment does the reverse: Bob's funds are delayed, Alice's are immediate.

The delay on the broadcaster's own funds creates a window for the counterparty to detect and punish a revoked commitment (an old state).

17.2.2Commitment Transaction Structure

Per BOLT 3, a commitment transaction has:

FieldValue
Version2
InputFunding outpoint (2-of-2 P2WSH)
nSequenceUpper 8 bits = 0x80, lower 24 bits = upper 24 bits of obscured commitment #
nLockTimeUpper 8 bits = 0x20, lower 24 bits = lower 24 bits of obscured commitment #
Outputsto_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.

17.2.3The to_local

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

17.2.4The to_remote Output

The 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:

to_remote with Anchors (BOLT 3)

<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.

17.3Revoking Old States

Every time the channel state updates (a payment is made), both parties:

  1. Exchange signatures for the new commitment transaction.
  2. Reveal the revocation secret for the old commitment.

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.

The Penalty Is Total

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.

17.4HTLC Outputs

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:

Offered HTLC Witness Script (BOLT 3)

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

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.

17.5Closing Transactions

A Lightning channel can close in three ways:

17.5.1Cooperative Close

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.

17.5.2Force Close (Unilateral)

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.

17.5.3Breach Remedy (Penalty)

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.

17.6Anchor Outputs and Fee Management

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:

Anchor Output Script (BOLT 3)

<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.

Everything Connects

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.

17.7What We Learned

17.7.1Looking Ahead

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

Litmus (L)

  1. What type of output does a Lightning funding transaction create?
  2. Why does the to_local output have a CSV delay?
  3. What happens if a party broadcasts a revoked commitment transaction?
  4. Name the three types of channel closure.
  5. What is the purpose of anchor outputs?

Hands-On (H)

  1. Write the to_local witness script for a channel with to_self_delay = 144 blocks. What nSequence value must the spending input use?
  2. A commitment transaction has a 500-sat fee but needs 20 sat/vB to confirm. The commitment is 900 vB and the anchor output is 330 sats. Design a CPFP strategy: how large and how expensive must the child transaction be?
  3. In a multi-hop payment A B C, the HTLC from A to B has CLTV expiry at block \(n+40\) and B to C expires at block \(n+20\). Why must A's timeout be larger than B's?

Proofs and Reasoning (P)

  1. Explain why commitment transactions are asymmetric. What would go wrong if both parties held identical commitment transactions?
  2. Why are HTLC outputs resolved via second-stage transactions (HTLC-success, HTLC-timeout) rather than directly from the commitment?
  3. Explain the economic game theory behind the penalty mechanism. Under what conditions is it rational for a party to broadcast a revoked commitment?

Connections (C)

  1. Timelock layers. Identify every timelock mechanism (nLockTime, CSV, CLTV) used in a Lightning force close with in-flight HTLCs. Describe what each one protects against.
  2. SegWit dependency. Explain why Lightning requires SegWit (BIP 141). What problem would transaction malleability cause for the commitment transaction chain?

Bridge (B)

  1. Chapter 19 covers Ordinals inscriptions, which embed data in the witness. Could an Ordinals inscription be embedded inside a Lightning commitment transaction? Why or why not?
  2. Compare the efficiency of Lightning (off-chain payments settled via commitment transactions) with on-chain batching (Chapter 15's OP_RETURN discussion). When is each approach more appropriate?

*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:

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.

← Ch. 16 Ch. 18 →