Bitcoin Timelocks: CLTV, CSV, and Time-Based Scripting
How Bitcoin's timelock opcodes enable payment channels, vaults, and time-delayed transactions.
Bitcoin transactions can be programmed to become valid only after a specific point in time. This capability, known as timelocking, is fundamental to nearly every Layer 2 protocol built on Bitcoin. Without timelocks, there would be no payment channels, no revocation mechanisms, and no way to build trustless escrow directly in Bitcoin Script.
Timelocks come in four distinct forms, split along two axes: absolute versus relative, and transaction-level versus script-level. Understanding these distinctions is essential for anyone building on Bitcoin or evaluating the security assumptions of protocols like Lightning and Spark.
Transaction-Level Timelocks
Bitcoin has included basic timelocking since Satoshi's original implementation. The nLocktime field exists in every Bitcoin transaction, and the nSequence field exists on every transaction input. Both operate at the transaction level: they make an entire transaction invalid until a condition is met, but they do not constrain the scripts that guard individual UTXOs.
nLocktime: Absolute Transaction Lock
Every Bitcoin transaction contains a 4-byte nLocktime field. When set to a non-zero value, the transaction cannot be included in a block until the specified condition is satisfied. If the value is below 500,000,000, it is interpreted as a block height. If equal to or above 500,000,000, it is interpreted as a Unix timestamp.
There is a critical caveat: nLocktime is only enforced when at least one input has an nSequence value less than 0xFFFFFFFF. If all inputs have their sequence set to the maximum value, the locktime field is ignored entirely, and the transaction is valid immediately.
Satoshi originally envisioned nLocktime and nSequence working together for transaction replacement: a sender could create multiple versions of a transaction with increasing sequence numbers, and only the final version would confirm after the locktime expired. This mechanism was disabled early in Bitcoin's history because it created denial-of-service risks. The modern replacement, BIP 125 opt-in RBF, uses fee-based incentives instead.
nSequence: Relative Transaction Lock
With BIP 68 (activated in 2016), the nSequence field was repurposed to encode relative timelocks. Rather than specifying an absolute point in time, a relative timelock says: this input cannot be spent until N blocks (or N units of 512 seconds) have elapsed since the referenced output was confirmed.
The encoding uses 18 of the 32 bits in the nSequence field:
- Bit 31 (disable flag): if set, no relative lock is enforced on this input
- Bit 22 (type flag): if unset, bits 0-15 encode a block count; if set, bits 0-15 encode a multiple of 512 seconds
- Bits 0-15 (value): the lock duration in the chosen unit
512-second granularity: When using time-based relative locks, the smallest unit is 512 seconds (roughly 8.5 minutes). A value of 1 means 512 seconds, a value of 2 means 1,024 seconds, and so on. Block-based locks use exact block counts with no minimum granularity beyond one block. This 512-second resolution was chosen because Bitcoin's Median Time Past (BIP 113) already introduces imprecision on the order of minutes.
Script-Level Timelocks
Transaction-level locks have a limitation: they constrain when a transaction can be broadcast, but they cannot enforce that a particular UTXO is locked until a certain time. Anyone who holds the private key can simply create a new transaction without the locktime restriction. Script-level opcodes solve this by embedding the time constraint into the spending conditions of the output itself.
OP_CHECKLOCKTIMEVERIFY (CLTV)
Defined in BIP 65 and activated in December 2015, OP_CHECKLOCKTIMEVERIFY (CLTV) enforces an absolute timelock at the script level. When a script contains CLTV, the spending transaction's nLocktime must be equal to or greater than the value specified in the script. This means the UTXO literally cannot be spent before that block height or timestamp, regardless of who holds the keys.
A basic CLTV script looks like this:
<expiry_height> OP_CHECKLOCKTIMEVERIFY OP_DROP
<pubkey> OP_CHECKSIGThe script pushes the target block height onto the stack, then CLTV checks that the spending transaction's nLocktime is at least that value. If the check passes, OP_DROP removes the height from the stack, and execution continues to the normal signature check.
OP_CHECKSEQUENCEVERIFY (CSV)
Defined in BIP 112 and activated alongside BIP 68 in 2016, OP_CHECKSEQUENCEVERIFY (CSV) enforces a relative timelock at the script level. It verifies that the spending input's nSequence value is at least the value specified in the script, ensuring a minimum delay since the UTXO was confirmed on-chain.
A basic CSV script:
<144> OP_CHECKSEQUENCEVERIFY OP_DROP
<pubkey> OP_CHECKSIGThis script requires 144 blocks (approximately one day) to pass after the output is confirmed before it can be spent. CSV is the foundation of modern payment channel designs because it enables the crucial revocation delay that makes cheating punishable.
Comparing the Four Timelock Types
| Mechanism | Level | Lock Type | BIP | Activated |
|---|---|---|---|---|
nLocktime | Transaction | Absolute | Original protocol | 2009 |
nSequence (BIP 68) | Transaction | Relative | BIP 68 | 2016 |
OP_CHECKLOCKTIMEVERIFY | Script | Absolute | BIP 65 | 2015 |
OP_CHECKSEQUENCEVERIFY | Script | Relative | BIP 112 | 2016 |
The transaction-level mechanisms (nLocktime and nSequence) control when a pre-signed transaction can be broadcast. The script-level opcodes (CLTV and CSV) control what spending conditions a UTXO requires. In practice, the script-level and transaction-level mechanisms work in tandem: CLTV checks nLocktime, and CSV checks nSequence.
Time-Based vs Block-Height Locks
Both absolute and relative timelocks can measure time in two units: block heights and clock time. The system enforces a strict rule: you cannot mix types. If a script uses a block-height CLTV, the spending transaction must set nLocktime to a block height (value below 500,000,000). If the script uses a timestamp CLTV, the transaction must use a timestamp locktime. Attempting to compare a block height against a timestamp causes the script to fail.
For relative timelocks, bit 22 of the nSequence field determines the unit. When unset, the value is in blocks. When set, the value is in multiples of 512 seconds. The same mixing restriction applies: if the script specifies a time-based CSV, the input must use time-based nSequence encoding.
Why 512 seconds? Bitcoin block timestamps are not precise: nodes accept blocks with timestamps up to two hours in the future, and BIP 113 uses the median of the last 11 block timestamps rather than real-world clock time. The 512-second granularity (2^9 seconds) avoids false precision. Most protocols use block-height locks instead, since block production is the more natural unit of progress in Bitcoin consensus.
Timelocks in Payment Channels
Payment channels are the most consequential application of timelocks. The Lightning Network relies on CSV to create a window during which cheating attempts can be detected and punished.
The Revocation Mechanism
In a Lightning channel, each state update produces a new commitment transaction for both parties. When a channel updates from state N to state N+1, both parties exchange revocation keys for state N, effectively making it dangerous to broadcast the old commitment.
Here is why CSV matters: each commitment transaction has an asymmetric structure. The local party's output is encumbered by a CSV delay (typically 144 to 2,016 blocks), while the remote party's output is immediately spendable. If Alice broadcasts a revoked commitment, Bob can claim his output immediately. Alice's output, however, is locked by CSV for the agreed-upon delay. During that window, Bob can use the revocation key Alice previously shared to construct a justice transaction, sweeping Alice's funds as penalty.
Without CSV, there would be no delay window. A cheater could broadcast an old state and immediately sweep their output before the counterparty could react. The timelock creates the enforcement window that makes the penalty mechanism credible.
HTLCs and Timelocked Routing
Hash Time-Locked Contracts (HTLCs) combine hashlocks with timelocks to enable multi-hop payments across Lightning. An HTLC says: the recipient can claim these funds by revealing a preimage before a CLTV deadline, or the sender can reclaim them after the deadline passes.
The timelock values decrease at each hop along a route. If Alice routes a payment through Bob to Carol with a final CLTV expiry of block 800,000, the HTLC from Alice to Bob might expire at block 800,040 (adding a 40-block safety margin). This tiered structure ensures that each routing node has enough time to claim its incoming HTLC after learning the preimage from the outgoing one.
Timelocks in Vaults and Custody
Beyond payment channels, timelocks enable several important custody patterns.
Inheritance Vaults
A simple inheritance scheme uses CLTV to create a dead-man's switch. The owner can spend the funds at any time with their primary key. If the primary key is not used before a specified block height, a secondary key (held by a beneficiary or attorney) becomes valid:
OP_IF
<owner_pubkey> OP_CHECKSIG
OP_ELSE
<expiry_height> OP_CHECKLOCKTIMEVERIFY OP_DROP
<heir_pubkey> OP_CHECKSIG
OP_ENDIFThe owner periodically moves the funds to a new UTXO with an updated expiry to "reset the clock." If they stop refreshing (presumably due to incapacitation or death), the heir can claim the funds after the CLTV expiry.
Covenants and Staged Withdrawals
Vault designs proposed by Bryan Bishop and others use pre-signed transactions with CSV delays to create staged withdrawal processes. Moving funds from cold storage triggers a mandatory waiting period. During this period, a "clawback" key can cancel the withdrawal if it was unauthorized. This pattern significantly reduces the damage from compromised keys, because an attacker must both steal the key and remain undetected through the entire CSV delay.
Discreet Log Contracts (DLCs)
DLCs use timelocks for contract expiration. Two parties lock funds in a multisig output, and the contract settles when an oracle publishes a signed attestation. A CLTV refund path ensures that if the oracle fails to attest by the deadline, both parties can reclaim their collateral. Without this timelock, a missing oracle attestation would lock funds permanently.
Eltoo and the Next Generation of Timelocks
The current Lightning penalty mechanism has a significant drawback: every old state is "toxic." If you accidentally broadcast a revoked state (through a software bug or backup restoration), your counterparty can take all channel funds. The eltoo proposal (also called LN-Symmetry) replaces this punishment model with a simpler update mechanism.
In eltoo, each new state can spend any previous state, not just the immediately preceding one. This is possible because eltoo relies on SIGHASH_ANYPREVOUT (proposed in BIP 118), which allows a signature to bind to any prior output with the same script. When combined with CSV, the latest state always wins: an old state is broadcast, the CSV delay gives the counterparty time to respond with the most recent state, and the final settlement reflects the correct balances.
The key difference from current Lightning: in eltoo, broadcasting an old state does not result in total loss of funds. The worst outcome is a delay, not a penalty. This eliminates the need for complex watchtower infrastructure dedicated to detecting and punishing revoked states.
Timelock Usage Across Protocols
| Protocol | Timelock Type | Purpose | Typical Duration |
|---|---|---|---|
| Lightning (LN-Penalty) | CSV | Revocation delay window | 144 to 2,016 blocks |
| Lightning HTLCs | CLTV | Payment expiry per hop | 40-block decrements |
| Eltoo / LN-Symmetry | CSV | State settlement delay | Configurable per channel |
| Inheritance vaults | CLTV | Dead-man's switch | Months to years |
| Custody vaults | CSV | Staged withdrawal delay | 144 to 1,008 blocks |
| DLCs | CLTV | Oracle timeout refund | Contract-specific |
| Spark (statechains) | CSV / CLTV | Operator key expiry and exit path | Protocol-defined window |
How Spark Uses Timelocks
Spark takes a fundamentally different approach to timelocks compared to Lightning. Lightning uses timelocks for punishment: if you cheat, the revocation delay gives your counterparty time to penalize you. Spark uses timelocks for recovery: if operators become unavailable, the timelock gives users a path to reclaim their funds unilaterally.
In Spark's statechain model, funds sit in a two-of-two multisig between the user and the Spark operator set. Transfers happen by rotating keys rather than broadcasting transactions. Each user holds a pre-signed exit transaction with a relative timelock. If the operators go offline or refuse to cooperate, the user waits for the timelock to expire and then broadcasts the exit transaction to settle back to Bitcoin L1.
This design eliminates the "toxic state" problem entirely. In Lightning, accidentally broadcasting an old commitment transaction can result in losing all channel funds via a justice transaction. In Spark, exit transactions are not punitive: they simply enforce ownership hierarchy through timelock ordering. The current owner always has the shortest timelock, so their exit transaction confirms first, and previous owners' stale exit transactions become invalid.
Timelocks as safety nets: In Spark, the timelock is a last-resort recovery mechanism, not part of normal operation. Under typical conditions, transfers happen instantly through cooperative key rotation. The timelock only activates if something goes wrong with operator availability.
Tradeoffs and Limitations
The Fee Problem
Pre-signed transactions with timelocks lock in a fee rate at signing time. If the fee market changes dramatically before the transaction needs to be broadcast, the pre-signed fee may be too low for timely confirmation or wastefully high. Solutions include anchor outputs (used in modern Lightning) and ephemeral dust patterns that allow fee bumping via CPFP (Child Pays for Parent) at broadcast time.
Timestamp Imprecision
Time-based locks (as opposed to block-height locks) suffer from Bitcoin's loose timestamp requirements. A miner can set a block timestamp up to two hours in the future, and the Median Time Past calculation introduces further smoothing. For applications requiring precise timing, block-height locks are strictly preferable. Most production protocols use block heights for this reason.
Long Timelocks and Capital Efficiency
Longer timelocks increase security (more time to detect and respond to fraud) but reduce capital efficiency (funds are locked for longer during disputes). Lightning channels typically negotiate a to_self_delay of 144 blocks (one day) to 2,016 blocks (two weeks). Channels with larger balances tend toward longer delays as additional protection. Finding the right balance between security and usability is an ongoing design challenge.
Expiring Backup Problem
In protocols using relative timelocks for state updates, the timelock effectively sets a deadline on backup validity. If a Lightning user goes offline for longer than the CSV delay and their counterparty broadcasts a revoked commitment, the penalty window may close before the user can react. This is why watchtowers exist: they monitor the blockchain on behalf of offline users and broadcast justice transactions when needed.
Practical Considerations for Developers
Developers working with timelocks should keep several details in mind:
- CLTV and CSV do not pop values from the stack; they leave the top stack element in place. Use
OP_DROPafter the check to clean up. - Never mix block-height and time-based locks in the same script branch. The comparison will always fail.
- When using CSV, the spending input's
nSequencemust have bit 31 unset (the disable flag cleared) for the relative lock to be enforced. - Taproot (BIP 341/342) does not change how CLTV and CSV work at the consensus level. Both opcodes function identically in tapscript as they do in legacy and SegWit v0 scripts.
- The maximum relative timelock encodable in
nSequenceis 65,535 blocks (about 455 days) or 65,535 x 512 seconds (about 388 days). Protocols requiring longer delays must use absolute timelocks or implement periodic refresh mechanisms.
Conclusion
Timelocks are one of Bitcoin's most powerful scripting primitives. From Satoshi's original nLocktime field to the modern CLTV and CSV opcodes, the ability to make transactions conditional on the passage of time has enabled an entire ecosystem of Layer 2 protocols, custody solutions, and smart contracting patterns.
Lightning's revocation-based channels, eltoo's symmetric update mechanism, Spark's operator-expiry exits, inheritance vaults, and DLCs all depend on the same fundamental capability: the ability to say "this transaction is only valid after block X" or "this output cannot be spent until Y blocks have passed." The four timelock types serve different roles, but together they form the temporal logic layer that makes programmable Bitcoin possible.
This article is for educational purposes only. It does not constitute financial or investment advice. Bitcoin and Layer 2 protocols involve technical and financial risk. Always do your own research and understand the tradeoffs before using any protocol.

