BIP113 - Median Time-Past as Time-Lock Endpoint¶
BIP113 (Bitcoin Improvement Proposal 113) is one of the Bitcoin improvement proposals, put forward by Thomas Kerin and Mark Friedenbach in 2015. This proposal modifies the time-lock verification logic for Bitcoin transactions by using the median time of the past 11 blocks (Median Time-Past, MTP) instead of an individual block's timestamp, thereby improving the reliability and security of time-locked transactions.
Core Concept¶
Before BIP113, Bitcoin used the timestamp in the block header to verify the time-lock conditions of nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP65). However, block timestamps can be manipulated by miners within a certain range, which introduced uncertainty for smart contracts that rely on precise time-locks.
BIP113 introduced the concept of Median Time-Past (MTP), which takes the median of the timestamps of the past 11 blocks as the current block's "time." This mechanism significantly reduces the ability of any single miner to manipulate time and improves the predictability of time-locks.
Problem Background¶
Issues with Block Timestamps¶
Before BIP113, the following problems existed:
- Miner Manipulation:
- Miners can set block timestamps within a certain range
- The only requirement is: timestamp > median time of the past 11 blocks
- And timestamp < network adjusted time + 2 hours
-
This gives miners approximately 2 hours of manipulation window
-
Time-Lock Uncertainty:
- Transactions relying on nLockTime might be confirmed earlier or later than expected
- The execution time of OP_CHECKLOCKTIMEVERIFY scripts was unpredictable
-
This posed risks for time-sensitive applications like the Lightning Network and HTLCs
-
Attack Vectors:
- A malicious miner could deliberately set a block timestamp far in the future
- Preventing time-locked transactions from being confirmed
- Or prematurely unlocking funds that should remain locked
Practical Example¶
Consider the following scenario:
Alice creates a transaction with nLockTime = block height 500,000
When block 499,999 is mined, Alice expects confirmation in the next block
But if the miner sets block 500,000's timestamp very late
Alice's transaction could be delayed by several hours before confirmation
Median Time-Past (MTP)¶
Definition¶
Median Time-Past is the median of the timestamps of the past 11 blocks:
Calculation Example¶
Assuming the current block is 500,000 and the timestamps of the past 11 blocks are:
Block 499,990: 1609459200
Block 499,991: 1609459800
Block 499,992: 1609460400
Block 499,993: 1609461000
Block 499,994: 1609461600
Block 499,995: 1609462200 <-
Block 499,996: 1609462800 <- 6th value (median)
Block 499,997: 1609463400 <-
Block 499,998: 1609464000
Block 499,999: 1609464600
Block 500,000: 1609465200
MTP(500,000) = 1609462800 (the 6th timestamp)
Key Changes¶
1. nLockTime Verification¶
Old Rule (before BIP113):
New Rule (after BIP113):
2. OP_CHECKLOCKTIMEVERIFY¶
Old Rule:
New Rule:
3. nSequence / OP_CHECKSEQUENCEVERIFY¶
BIP113 also affects BIP68 and BIP112, which were introduced subsequently: - BIP68 (relative time-locks) uses MTP - BIP112 (OP_CHECKSEQUENCEVERIFY) uses MTP
Technical Advantages¶
1. Reduced Time Manipulation¶
A single miner cannot significantly affect MTP: - Controlling multiple consecutive blocks is required to manipulate MTP - Even controlling 1 block shifts MTP by at most about 10 minutes (1/11) - Controlling 6 blocks is needed for full control of MTP, which is extremely costly
2. Improved Predictability¶
Transaction creators can more accurately predict unlock times: - MTP changes smoothly without sudden jumps - It increases by approximately 10 minutes (one block) every ~10 minutes - Time-lock trigger times are more reliable
3. Enhanced Security¶
For time-sensitive smart contracts: - HTLCs (Hash Time-Locked Contracts) are more secure - The Lightning Network's timeout mechanisms are more reliable - Atomic swap time windows are more precise
4. Backward Compatibility¶
BIP113 is a soft fork: - Old nodes can still validate new blocks - The new rules are stricter than the old rules - No chain split occurs
Practical Applications¶
Lightning Network¶
The Lightning Network uses time-locks to protect channel security:
Both channel parties agree:
- Cooperative close: No time-lock
- Unilateral close: Locked for 144 blocks (~1 day)
- Fraud penalty: Detect and penalize within the lock period
BIP113 ensures time-locks are reliable:
- A malicious party cannot withdraw early by manipulating timestamps
- The honest party has sufficient time to respond to fraudulent behavior
HTLC (Hash Time-Locked Contracts)¶
Cross-chain atomic swaps rely on HTLCs:
Alice (Bitcoin) <-> Bob (Litecoin)
Step 1: Alice creates an HTLC, lock time = MTP + 24 hours
Step 2: Bob creates an HTLC, lock time = MTP + 12 hours
Step 3: Alice reveals the secret, Bob claims the Bitcoin
Step 4: Bob uses the same secret to claim the Litecoin
If the swap fails midway:
- After 12 hours, Bob can get a refund
- After 24 hours, Alice can get a refund
- The time difference ensures no loss of funds
BIP113 ensures that the above time windows are reliable and prevents either party from cheating by manipulating timestamps.
Escrow Services¶
Multi-signature escrow wallets:
2-of-3 multisig wallet:
- Buyer
- Seller
- Escrow agent
Scenario:
1. Buyer sends payment to the multisig address
2. If the transaction goes smoothly, buyer + seller sign to release funds to the seller
3. If there is a dispute, the escrow agent intervenes
4. After 30 days, if no one takes action, the buyer can unilaterally reclaim funds (nLockTime)
BIP113 ensures the 30-day deadline is accurate, giving the escrow agent sufficient time to act
Inheritance Planning¶
Time-locked inheritance arrangements:
Inheritance address:
- Normal case: The holder uses the primary private key to spend
- Emergency case: After 1 year, the heir can use a backup private key
Implementation:
- Primary path: Holder signs, no time restriction
- Backup path: Heir signs + OP_CHECKLOCKTIMEVERIFY (1 year)
BIP113 ensures the heir cannot inherit early by manipulating time
Relationship with Other BIPs¶
BIP65 (OP_CHECKLOCKTIMEVERIFY)¶
BIP113 modified the time verification logic of BIP65: - BIP65 introduced the OP_CHECKLOCKTIMEVERIFY opcode - BIP113 changed the time comparison baseline for that opcode - From block.time to MTP
BIP68 (Relative Time-Locks)¶
BIP68 introduced relative time-locks (nSequence): - Uses MTP as the time baseline - Allows "after N blocks/hours" types of locks - BIP113 ensures the reliability of relative time-locks
BIP112 (OP_CHECKSEQUENCEVERIFY)¶
BIP112 introduced the opcode for checking relative time-locks: - Verification logic uses MTP - Works together with BIP68 and BIP113 to implement reliable relative locks
BIP9 (Version Bits)¶
BIP113 was activated through BIP9's version bits mechanism: - Uses version bit 0 - Activated simultaneously with BIP68 and BIP112 - Collectively known as the "CSV (CheckSequenceVerify) soft fork"
Activation and Deployment¶
Soft Fork Activation¶
BIP113 was activated in July 2016: - Activation method: BIP9 version bit 0 - Activation height: 419,328 (July 4, 2016) - Activated together with BIP68 and BIP112 - Locked in after reaching 95% miner support
Compatibility¶
Backward Compatible: - Old nodes can validate new blocks - The new rules are a subset of the old rules - No chain split occurs
Forward Compatible: - New nodes reject blocks that violate BIP113 - Old nodes might accept such blocks (but this is extremely rare)
Security Considerations¶
1. Time Precision¶
Precision provided by MTP: - Approximately 10 minutes (one block time) - Not suitable for applications requiring second-level precision - Sufficient for most time-lock applications
2. Clock Synchronization¶
Nodes' local clocks remain important: - Used to validate new block timestamps - Clock drift exceeding 2 hours can cause issues - Using NTP to keep clocks synchronized is recommended
3. Long-Term Time-Locks¶
For long-term locks (such as year-level durations): - MTP provides good protection - But risks like hardware failure and key management should still be considered - Combining multisig and backup solutions is recommended
4. Cross-Chain Applications¶
Cross-chain atomic swaps should note: - MTP calculations may differ slightly across chains - Time windows should include ample margins - A buffer of at least 6-12 blocks is recommended
Technical Details¶
MTP Calculation Algorithm¶
def calculate_mtp(block_height):
"""Calculate the MTP for a given block height"""
if block_height < 11:
# Special rules for the first 11 blocks
return 0
# Collect timestamps of the past 11 blocks
timestamps = []
for i in range(11):
block = get_block(block_height - i)
timestamps.append(block.timestamp)
# Return the median
timestamps.sort()
return timestamps[5] # The 6th element (index 5)
nLockTime Verification¶
def verify_locktime(tx, block):
"""Verify the transaction's nLockTime"""
if tx.nLockTime == 0:
return True # No lock
# Calculate the MTP for the current block
mtp = calculate_mtp(block.height)
# Distinguish between block height lock and timestamp lock
if tx.nLockTime < 500000000:
# Block height lock
return tx.nLockTime < block.height
else:
# Timestamp lock (uses MTP)
return tx.nLockTime < mtp
OP_CHECKLOCKTIMEVERIFY Implementation¶
def op_checklocktimeverify(stack, tx, mtp):
"""Execute OP_CHECKLOCKTIMEVERIFY"""
if len(stack) < 1:
return False
locktime = stack[-1] # Top of stack
# Verify lock time
if locktime < 0:
return False
# Distinguish between block height and timestamp
if locktime < 500000000:
# Block height
threshold = tx.block_height
else:
# Timestamp (uses MTP)
threshold = mtp
# Check if unlocked
if locktime >= threshold:
return False # Not yet unlocked
return True
Comparison: Before and After BIP113¶
| Feature | Before BIP113 | After BIP113 |
|---|---|---|
| Time Baseline | Block timestamp | Median Time-Past (MTP) |
| Miner Manipulation Ability | High (~2 hours) | Low (requires controlling multiple blocks) |
| Time Predictability | Lower | High |
| Time-Lock Reliability | Unstable | Stable |
| Lightning Network Security | At risk | Significantly improved |
| Activation Method | N/A | Soft fork (BIP9) |
| Backward Compatibility | N/A | Yes |
Practical Impact¶
Impact on Users¶
- More reliable time-locks: Inheritance, escrow, and similar applications are safer
- Better privacy protection: Time-locked transactions are less easily identified
- Reduced risk: Lower chance of fund loss due to time manipulation
Impact on Developers¶
- Simpler smart contracts: Time logic is more predictable
- More secure protocols: HTLCs, Lightning Network, etc. are more reliable
- Better user experience: Fewer issues caused by time uncertainty
Impact on Miners¶
- Limited time manipulation: Cannot significantly influence MTP with a single block
- Standardized block timestamps: More accurate timestamp settings are required
- Maintained compatibility: Must follow MTP rules to avoid block rejection
Layer 2 Applications¶
BIP113 laid the groundwork for Layer 2: - Lightning Network channel timeout mechanisms - Sidechain cross-chain transactions - State channel dispute resolution
Smart Contracts¶
More complex time-related smart contracts: - Periodic payments (salaries, rent) - Time-decaying voting rights - Time-based conditional execution
Summary¶
BIP113 significantly improved the reliability and security of Bitcoin's time-lock mechanism by introducing Median Time-Past (MTP):
Core Improvements: - Reliability: Reduced the ability of miners to manipulate time - Predictability: More precise time-lock trigger times - Security: Protects time-sensitive smart contracts - Compatibility: Implemented as a soft fork, backward compatible
Practical Value: - Laid the groundwork for Layer 2 solutions like the Lightning Network - Made HTLCs and atomic swaps more secure - Supports practical applications such as inheritance and escrow - Increased user confidence in time-locks
BIP113 is an important step in the evolution of the Bitcoin protocol. It addressed a long-standing security vulnerability and paved the way for more complex smart contracts and Layer 2 applications. Although it is a relatively simple change, its impact is far-reaching and it serves as an indispensable piece of infrastructure for building a reliable decentralized financial system.