A hashed timelock contract (HTLC) is a type of smart-contract pattern used in blockchains to create conditional, time-limited escrowed payments that require a cryptographic secret (a preimage) to unlock. HTLCs reduce counterparty risk in scenarios such as cross‑chain atomic swaps and payment-channel routing (for example, in the Lightning Network) by ensuring either the intended recipient can claim funds by revealing the secret within a deadline, or the sender can reclaim the funds after the deadline expires.
Key takeaways
– HTLCs combine two mechanisms: a hashlock (requires revealing a secret preimage) and a timelock (forces expiry/refund if the secret isn’t revealed).
– They enable atomic swaps (cross‑chain exchanges) and secure off‑chain payment routing (Lightning Network).
– Bitcoin supports HTLC-style constructs (and expanded smart-contract capability after Taproot); two common timelock opcodes are CheckLockTimeVerify (CLTV) and CheckSequenceVerify (CSV).
– Proper use requires careful sequencing and channel/transaction setup; mistakes can lead to lost funds.
Understanding the two core elements
1) Hashlock
– A hashlock is a cryptographic constraint: the contract stores H = HASH(secret). The recipient can spend the funds only by presenting secret such that HASH(secret) = H (the preimage).
– The secret is generated by one party (often the recipient of the funds) and kept private until they spend the output; revealing the secret during one claim can be used by other parties to claim related outputs on another chain or channel (this is what makes swaps atomic).
2) Timelock
– A timelock sets a deadline after which funds can be returned to the sender if the hashlock condition was not satisfied.
– Two commonly used timelock forms on Bitcoin:
• CheckLockTimeVerify (CLTV): locks spending until a specific block height or timestamp is reached — fixed calendar/block deadline.
• CheckSequenceVerify (CSV): enforces a relative delay measured in blocks or time since the funding transaction — used for relative time-based sequencing (e.g., channel refunds).
– Using different timelocks on the two sides of an exchange is important so the original sender can safely refund after the counterparty’s claim window ends.
How an HTLC works — step‑by‑step (atomic swap example)
Scenario: Alice wants to swap Bitcoin (BTC) for Bob’s Litecoin (LTC).
Preparation (secrets and hashes)
1. Bob generates a random secret “s” and calculates H = HASH(s). He gives H (but not s) to Alice.
2. Both parties agree on amounts, timelocks, and fee arrangements.
Create conditional outputs
3. Alice creates an on‑chain HTLC on the Bitcoin blockchain that pays Bob if he can provide s (such that HASH(s) = H) before time T1; otherwise Alice can refund after T1.
4. Bob creates an on‑chain HTLC on the Litecoin blockchain that pays Alice if she provides s (HASH(s) = H) before time T2; otherwise Bob can refund after T2.
Important timelock ordering
– T2 must be shorter than T1 (i.e., Bob’s refund deadline comes earlier) so that if Alice claims on Bob’s chain and reveals s, Bob has time to use s to claim Alice’s HTLC before Alice’s refund becomes available.
Claiming and settlement
5. If Alice wants the LTC, she spends Bob’s LTC HTLC by presenting s on the Litecoin chain. This publicly reveals s.
6. Bob sees s on the Litecoin blockchain and uses it to redeem the BTC HTLC before T1.
7. If the swap does not complete (secret not revealed), each party waits until their timelock expires and refunds their own HTLC.
Where HTLCs are used
– Atomic swaps (cross‑chain asset exchange) — enable trustless cross‑chain swaps without a centralized intermediary.
– Lightning Network (LN) — each hop uses HTLCs to route payments; revealing the final preimage lets all intermediate nodes settle their forwarded payments.
– Payment channels and other conditional payments or escrows that require an all-or-nothing reveal.
Timelock contract / Smart contracts & Bitcoin
– A timelock contract is any on‑chain program that conditions spending on a time or block‑height constraint. HTLCs are one class of timelock contracts.
– Bitcoin originally had limited smart‑contract expressiveness but supports script opcodes (including CLTV/CSV). The Taproot upgrade (2021) expanded Bitcoin’s capability to express more complex scripts more privately and efficiently, making complex contract patterns cheaper and stealthier on‑chain [Bitcoin Magazine: Understanding Taproot] [Builder’s Guide to the LND Galaxy: Timelocks].
– Ethereum and many other chains allow Turing‑complete smart contracts; they execute when preconditions are met and cost gas to deploy and run (gas is paid in denominations such as Gwei for ether). Complexity and network gas prices determine cost; simple contracts are cheap, complex contracts cost more [Wood: Ethereum paper].
Practical steps — creating and using HTLCs
Below are high‑level practical steps for two common HTLC use cases: an on‑chain atomic swap and a Lightning Network payment.
A. On‑chain atomic swap (high‑level)
1. Agreement: Parties agree amount, chains, fee contributions, and timelock values (T1 for Alice’s refund, T2 for Bob’s refund, with T2 < T1).
2. Secret: Recipient (Bob) creates secret s and computes H = HASH(s). He gives H to sender (Alice).
3. Create and fund HTLCs:
• Alice creates and broadcasts a transaction that locks BTC into an HTLC script paying Bob if HASH(s) matches and before T1; otherwise returns to Alice after T1.
• After Alice’s funding is confirmed (enough blocks), Bob creates and funds the LTC HTLC with similar logic but expiry T2.
4. Claim:
• Alice can claim LTC by broadcasting the redeem transaction that includes s. When she does, s becomes public.
• Bob monitors the LTC chain, extracts s from Alice’s claim, and immediately uses s to redeem the BTC HTLC before T1.
5. Refunds:
• If claims are not made, each party waits until their respective timelock and spends the refund path.
Practical notes:
– Wait for confirmations before proceeding between steps to avoid race conditions.
– Choose timelocks to be comfortably longer than expected confirmation/propagation delays.
– Use well-tested wallet software or atomic-swap tools (e.g., Liquality or other reputable implementations) rather than hand-crafting scripts unless experienced.
B. Lightning Network payment (practical flow)
1. Invoice creation:
• The final recipient creates a payment invoice containing H = HASH(s) and the amount.
2. Routing and HTLC offers:
• The sender constructs an HTLC to the next hop conditioned on H and a short CSV/CLTV delay, and that HTLC propagates along the route.
3. Preimage reveal and settlement:
• The recipient, upon receiving the routed HTLC, reveals s to claim funds. Each intermediate node that forwarded the payment uses s to claim its incoming HTLC, enabling atomic multi-hop settlement.
4. Failure and timeout:
• If the payment fails (no route, timeout), HTLCs expire and funds are automatically refunded after their relative timelocks.
Security, risks and best practices
– Timing and order matter: incorrect timelock ordering or insufficient confirmation waiting can lead to loss of funds.
– Fee and mempool risks: if a claimant doesn’t include sufficient fees, transactions can be delayed and timeouts triggered; set timelocks with sufficient safety margins.
– Software correctness: use audited and widely used implementations (e.g., Lightning Daemon implementations like lnd; atomic-swap tools like Liquality) rather than homebrewed scripts.
– Privacy: on‑chain HTLC scripts reveal some information; Taproot improves privacy for complex spending conditions on Bitcoin.
– Cross‑chain compatibility: ensure script expressiveness and hashing functions are compatible across chains (e.g., both chains support the same HASH algorithm and necessary timelock opcodes).
– Legal and compliance: some jurisdictions treat atomic swaps and decentralized exchange activity differently — consult legal advice if relevant.
Costs: “How much does a smart contract cost?”
– On Bitcoin, HTLCs are implemented as scripts embedded in transactions; the cost is transaction fees (size in vbytes × fee rate).
– On Ethereum, deploying and executing smart contracts consumes gas. Cost depends on the contract complexity, on‑chain storage used, and current gas price (paid in Gwei). Simple contracts and transactions are relatively cheap; complex, storage‑heavy contracts are more expensive [Wood: Ethereum].
– Off‑chain solutions (Lightning) reduce on‑chain fee burden by batching many payments off‑chain and only settling channel opens/closes on-chain.
Further reading and sources
– Investopedia — “Hashed Timelock Contract (HTLC)” (overview and examples)
– Builder’s Guide to the LND Galaxy — “Hashed Timelock Contract (HTLC)” and “Timelocks”
– Liquality — “Hash Time Locked Contracts (HTLCs) Explained” (practical atomic swap tools)
– Monika, Bhatia, et al., “Hash Time Locked Contract Based Asset Exchange Solution for Probabilistic Public Blockchains,” Cluster Computing (2022) — academic treatment of HTLC-based exchange
– Bitcoin Magazine — “Understanding Taproot in a Simple Way” (Taproot and advanced Bitcoin scripts)
– Wood, Gavin. “Ethereum: A Secure Decentralised Generalised Transaction Ledger” — foundational paper on Ethereum and smart contracts
– Provide a concrete HTLC script example (Bitcoin Script pseudocode) and explain each line.
– Walk through a real‑world atomic swap tooling workflow (commands and confirmations) using a known implementation (e.g., Liquality).
– Show how HTLCs are encoded in Lightning Network invoices and how multi‑hop settlement uses preimages.