Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Glossary

Hash Time-Locked Contract (HTLC)

A Hash Time-Locked Contract (HTLC) is a smart contract that uses a cryptographic hash and a timelock to enable conditional, trustless payments, forming the basis for atomic swaps and cross-chain transactions.
Chainscore © 2026
definition
CRYPTOGRAPHIC PROTOCOL

What is a Hash Time-Locked Contract (HTLC)?

A smart contract mechanism enabling conditional, trust-minimized transfers across payment channels and blockchain networks.

A Hash Time-Locked Contract (HTLC) is a type of smart contract that facilitates conditional payments by requiring the recipient to acknowledge receipt cryptographically within a specified timeframe or forfeit the ability to claim the funds. It is a foundational protocol for enabling atomic swaps and secure, off-chain transactions in networks like the Lightning Network. The contract locks funds using two primary components: a cryptographic hash preimage (a secret) and a timelock. The payer generates a secret and its hash, then creates an HTLC that can only be unlocked by the payee revealing the secret that produces the matching hash.

The core security mechanism relies on the interplay between the hashlock and the timelock. The hashlock ensures that only the party who knows the secret preimage can claim the payment. The timelock, implemented via OP_CHECKLOCKTIMEVERIFY in Bitcoin or similar constructs in other blockchains, acts as a safety refund. If the payee fails to produce the secret before the timelock expires, the funds are automatically returned to the original sender. This creates a trustless environment where neither party can cheat—the payer cannot take back the funds once the secret is revealed, and the payee cannot stall indefinitely.

HTLCs are the critical building block for cross-chain atomic swaps, allowing users to exchange cryptocurrencies across different blockchains without a centralized intermediary. In this process, two parallel HTLCs are created on two separate chains, linked by the same hash preimage. The first party to reveal the secret to claim their payment on one chain inadvertently discloses it, enabling the counterparty to claim the payment on the other chain. This ensures the swap either completes entirely for both parties or not at all, eliminating counterparty risk.

Within a single blockchain ecosystem, HTLCs power payment channel networks like Bitcoin's Lightning Network. They enable multi-hop payments where intermediaries can forward funds without taking custody of them. Each hop in the route is secured by a separate HTLC with a successively shorter timelock, creating an incentive for the secret to propagate backward through the network. This allows for near-instant, high-volume, low-fee microtransactions that are ultimately settled on the base layer blockchain.

While highly effective, HTLCs have limitations. They introduce liquidity locking as funds are committed for the duration of the timelock. The requirement for decrementing timelocks in payment channels adds routing complexity. Furthermore, the simple hashlock condition is vulnerable to hash collision attacks in theory, though cryptographically secure hash functions like SHA-256 make this practically infeasible. Newer protocols, such as Point Time-Locked Contracts (PTLCs), are being developed to offer greater privacy and efficiency by using cryptographic signatures instead of hash preimages.

how-it-works
MECHANISM

How Does an HTLC Work?

A detailed breakdown of the cryptographic and time-based mechanisms that enable secure, conditional payments across blockchain networks.

A Hash Time-Locked Contract (HTLC) is a conditional payment mechanism that uses a cryptographic hash and a timelock to enforce atomic execution across a payment path. The process begins when the sender, Alice, creates a cryptographic hash (the payment hash) from a secret preimage known only to her. She then locks funds in an HTLC on her blockchain, specifying that the recipient, Bob, can claim them only by revealing the correct preimage that generates the agreed-upon hash. This contract also includes a refund timelock, allowing Alice to reclaim her funds if the secret is not revealed before a specified block height or timestamp.

For the payment to succeed, Bob must discover the secret preimage. In a cross-chain or payment channel scenario, this secret is typically revealed by the final recipient further down the route. Once Bob learns the preimage, he can submit it to claim the funds locked in Alice's HTLC. Critically, the moment Bob reveals the preimage on-chain to claim his payment, it becomes public data on the blockchain ledger. This public revelation is what enables the entire conditional chain to resolve, as every intermediary party can now use the same preimage to claim the funds locked for them by their upstream counterparty.

The timelock is the essential safety mechanism that protects all participants. It creates two guaranteed outcomes: either the secret is revealed and the payment completes, or the timelock expires and the funds are refunded to their original owner. This eliminates the principal risk of a conditional transfer—the possibility of funds being locked indefinitely. Timelocks are implemented using absolute block heights (e.g., cltv in Bitcoin) or relative time delays (e.g., csv), ensuring the contract's execution is bound by the deterministic progress of the blockchain.

HTLCs are the foundational protocol for atomic swaps and Lightning Network payments. In an atomic swap between different blockchains, HTLCs on both chains are locked with the same hash. The revelation of the preimage to claim funds on one chain automatically provides the data needed to claim assets on the other, making the cross-chain trade atomic. In the Lightning Network, HTLCs secure every hop in a multi-hop payment route, allowing funds to be transferred off-chain with the same security guarantees as an on-chain settlement, thereby enabling fast, low-cost micropayments.

key-features
MECHANISM BREAKDOWN

Key Features of HTLCs

Hash Time-Locked Contracts (HTLCs) are a fundamental cryptographic primitive enabling conditional payments across blockchains and payment channels. Their core features provide atomicity, security, and trust-minimization for cross-chain swaps and Lightning Network transactions.

01

Cryptographic Hashlock

The hashlock is a cryptographic condition that locks funds. The sender creates a preimage (secret data) and publishes its cryptographic hash. Funds can only be claimed by any party who reveals this preimage, proving they know the secret. This creates a verifiable, one-way condition for payment release.

  • Example: Alice locks 1 BTC with hash H. Bob can only claim it by providing the secret R where hash(R) = H.
02

Time-Based Timelock

The timelock is a safety mechanism that sets an expiration for the conditional payment. It is enforced via a blockchain's native scripting (e.g., OP_CHECKLOCKTIMEVERIFY in Bitcoin). If the correct preimage is not revealed before the timelock expires, the funds are automatically refunded to the original sender.

  • Prevents Fund Loss: Guarantees the sender's capital is not locked indefinitely if the counterparty fails to act.
03

Atomic Cross-Chain Swaps

HTLCs enable atomic swaps between different blockchains without a trusted third party. Two parties create mirrored HTLCs on two separate chains (e.g., Bitcoin and Ethereum), linked by the same hashlock. The revelation of the preimage to claim funds on one chain automatically reveals it to claim funds on the other, making the swap all-or-nothing.

  • Key Property: The swap is atomic; it either completes entirely for both parties or fails entirely, eliminating counterparty risk.
04

Payment Channel Networks

HTLCs are the backbone of Layer 2 payment channels like the Lightning Network. They allow secure, multi-hop payments where intermediaries can forward funds without needing to trust the sender or receiver. Each hop in the route is secured by its own HTLC, with decrementing timelocks to ensure forward progress.

  • Enables Scalability: Transactions are settled off-chain, with the blockchain acting as a final settlement and dispute layer.
05

Trust-Minimized Escrow

An HTLC acts as a cryptographic escrow that does not require a trusted custodian. The contract's logic, enforced by the blockchain's consensus rules, dictates exactly how and when funds can be disbursed. This reduces reliance on intermediaries and enables decentralized finance (DeFi) applications like cross-chain bridges and atomic DEX trades.

06

Script-Based Implementation

HTLCs are implemented using a blockchain's native smart contract or scripting language. In Bitcoin, this is a Bitcoin Script combining OP_SHA256, OP_EQUAL, and OP_CHECKLOCKTIMEVERIFY. In Ethereum, it's a Solidity contract. The script defines the two possible spending paths: one with the correct preimage, and one with a valid refund after the timelock.

visual-explainer
MECHANISM EXPLAINER

Visualizing an HTLC Atomic Swap

An HTLC atomic swap is a trustless, cross-chain exchange protocol that uses cryptographic time locks to ensure both parties either complete the trade or get their funds back, with no central intermediary.

An HTLC atomic swap visualizes a two-step cryptographic handshake between two parties on different blockchains. The process begins when Party A, wanting to trade Bitcoin for Party B's Litecoin, creates a Hash Time-Locked Contract (HTLC) on the Bitcoin chain. This contract locks A's funds with two crucial conditions: the funds can only be claimed by presenting a secret cryptographic preimage (a random number) that produces a specific hash, and this claim must occur within a defined time window, or the funds are refunded to A. The hash of the secret is publicly visible on the chain, but the secret itself remains unknown to B.

To proceed, Party B takes the published hash and creates a corresponding HTLC on the Litecoin chain, locking their LTC with the same hash and a shorter time limit. This shorter deadline is critical, as it ensures B has enough time to claim the Bitcoin after learning the secret. Once B's contract is confirmed, Party A can claim the LTC by revealing the secret preimage to the Litecoin contract. This act of claiming publicly broadcasts the secret to both blockchains.

Finally, with the secret now public, Party B can use it to unlock and claim the Bitcoin from the original HTLC before A's longer time lock expires. The swap's atomic property is enforced by the time locks: if any step fails—for instance, if B never creates the second contract—the initial funds are automatically refunded when the time lock expires. This elegant mechanism eliminates counterparty risk without requiring a trusted third party, enabling decentralized exchanges and cross-chain liquidity.

In practice, visualizing this flow highlights the interlocking conditions that make the swap trustless. The protocol's security relies on the cryptographic one-way property of the hash function (easy to verify, hard to reverse) and the deterministic finality of the participating blockchains. While powerful, HTLCs require compatible scripting capabilities (like Bitcoin's SegWit) and careful parameter setting for time locks to account for network congestion and block time variances between chains.

ecosystem-usage
HASH TIME-LOCKED CONTRACT (HTLC)

Protocols & Ecosystem Usage

A Hash Time-Locked Contract (HTLC) is a smart contract that enables conditional payments across blockchains or payment channels, requiring the recipient to provide a cryptographic proof of payment within a set time limit.

01

Core Mechanism

An HTLC locks funds with two conditions:

  • Cryptographic Lock: The payer generates a secret and shares only its hash. The recipient must reveal the original secret to claim the funds.
  • Time Lock: A refund clause. If the secret is not revealed before a specified block height or timestamp, the funds are returned to the payer. This creates a trust-minimized conditional transfer, ensuring atomicity—either both legs of a swap succeed or both fail.
02

Cross-Chain Atomic Swaps

HTLCs are the foundational protocol for trustless cross-chain asset swaps without centralized intermediaries. Process:

  1. Alice locks Bitcoin in an HTLC on its blockchain, using a secret hash.
  2. Bob, seeing the lock, locks an equivalent amount of Litecoin in a corresponding HTLC on its chain, using the same hash.
  3. Alice reveals the secret to claim Bob's Litecoin.
  4. Bob uses the now-public secret to claim Alice's Bitcoin. This enables direct peer-to-peer trading between disparate blockchains like Bitcoin and Litecoin.
03

Lightning & Payment Channels

HTLCs are the building blocks of bidirectional payment channels in the Lightning Network and similar Layer 2 systems. How it works:

  • Payments are routed across a network of channels via HTLC forwarding.
  • Each hop in the path creates an HTLC, with decreasing time locks.
  • The final recipient reveals the secret, which propagates backwards, allowing each intermediary to claim funds from the preceding hop. This enables instant, high-throughput micropayments secured by the underlying blockchain's finality.
04

Interoperability Bridges

While modern bridges often use more complex architectures, early and simpler bridge designs relied on HTLCs for cross-chain asset transfers. Example Flow:

  1. A user locks Asset A on Chain A in an HTLC.
  2. A bridge validator or watchtower observes this event.
  3. Upon confirmation, an equivalent amount of a wrapped Asset A is minted on Chain B and sent to the user. The time lock ensures the bridge operator has a bounded timeframe to act, reducing certain risks.
05

Security Considerations

HTLCs introduce specific security parameters that must be carefully configured:

  • Time Lock Granularity: Must account for block time variance and network congestion. Too short risks failing legitimate swaps; too long increases capital lockup and exposure.
  • Hash Collision Attacks: While cryptographically improbable, the hash function (e.g., SHA-256) must be secure.
  • Fee Management: In routed payments, fees must be embedded, and time locks must accommodate potential transaction replacement or fee bumping.
06

Example: Simple Bitcoin HTLC Script

A simplified version of a Bitcoin Script for an HTLC showcases its logic:

code
OP_IF
    [HASHOP] <hash> OP_EQUALVERIFY
    <Recipient's PubKey> OP_CHECKSIG
OP_ELSE
    <Timeout> OP_CHECKLOCKTIMEVERIFY OP_DROP
    <Sender's PubKey> OP_CHECKSIG
OP_ENDIF

Interpretation:

  • The IF branch allows the recipient to claim with the correct secret and signature.
  • The ELSE branch allows the sender to refund after the CHECKLOCKTIMEVERIFY timeout passes.
security-considerations
HASH TIME-LOCKED CONTRACT (HTLC)

Security Considerations & Risks

While HTLCs are a foundational cryptographic primitive enabling trust-minimized swaps, they introduce specific security parameters and failure modes that participants must understand.

02

Timelock Expiry & Race Conditions

The timelock is a critical parameter that creates a race condition. If the secret is revealed late in the process, the counterparty may have a narrow window to claim their funds before the timelock expires, allowing the original sender to refund. Poorly synchronized blockchains or network congestion can exacerbate this risk.

  • Setting the Locktime: Too short risks the recipient; too long locks capital unnecessarily.
  • Blockchain Finality: On chains with probabilistic finality, a refund transaction might be reversed if a secret-revealing transaction is later reorged out.
03

Griefing & Denial-of-Service (DoS)

A malicious participant can initiate an HTLC without ever intending to fulfill it, locking the counterparty's capital for the duration of the timelock. This griefing attack is a form of economic denial-of-service.

  • Cost: The attacker only loses the transaction fee to initiate the lock, while the victim's capital is immobilized.
  • Amplification: In multi-hop payment channels (e.g., the Lightning Network), a single failed HTLC can stall funds across multiple nodes.
04

Implementation Bugs & Oracle Risks

Bugs in the smart contract code for the HTLC (on chains like Ethereum) or in the protocol logic (in Layer-2 networks) can lead to loss of funds. Furthermore, cross-chain HTLCs often rely on external oracles or relayers to verify proofs, introducing a trust assumption.

  • Smart Contract Vulnerabilities: Reentrancy, integer overflow, or incorrect timelock logic.
  • Oracle Manipulation: A compromised oracle could falsely attest to a secret reveal or timelock expiry.
05

Fee Market & Transaction Malleability

Successfully claiming funds from an HTLC requires broadcasting a transaction to the blockchain. During periods of high network congestion, participants must outbid others for block space. Transaction malleability (historically on Bitcoin) could change a transaction's ID, potentially breaking the script's spending conditions.

  • Claim Priority: A refund transaction with a higher fee might be mined before the legitimate claim.
  • Malleability Fixes: SegWit (Bitcoin) and specific smart contract patterns mitigate this historical issue.
06

Privacy Leakage from Hash Reuse

The hash H is public on-chain. If the same hash is reused across multiple HTLCs, it creates a correlation vector that can link seemingly unrelated transactions. This is a significant privacy concern in networks like the Lightning Network, where payment correlation can reveal the network topology and payment routes.

  • Pattern Analysis: Observers can track the flow of a specific hash to map channel balances and relationships.
  • Solution: Modern protocols use point-time-locked contracts (PTLCs) with adaptor signatures to avoid this leakage.
COMPARISON MATRIX

HTLC vs. Other Cross-Chain Mechanisms

A technical comparison of Hash Time-Locked Contracts against other prominent cross-chain interoperability solutions.

Feature / MechanismHTLC (Atomic Swap)Lock & Mint (Bridge)Liquidity Network

Core Principle

Cryptographic hash/time lock on two chains

Asset custody & synthetic issuance on destination chain

Peer-to-peer liquidity pools across chains

Trust Model

Trustless (cryptographic guarantees)

Custodial or Federated (trust in bridge operators)

Trustless (cryptographic & economic guarantees)

Native Asset Transfer

Intermediary Token

Capital Efficiency

Low (requires locked capital on both sides)

High (mints wrapped tokens)

High (utilizes shared liquidity pools)

Typical Latency

Minutes to hours (on-chain confirmation)

Seconds to minutes (off-chain validation)

< 1 second (off-chain state channels)

Security Foundation

Blockchain finality & time locks

Security of bridge multisig/validators

Bonding, fraud proofs, & channel states

Primary Use Case

Peer-to-peer atomic swaps

Bridging assets to non-native ecosystems

Fast, low-cost payments & swaps

examples
HASH TIME-LOCKED CONTRACT (HTLC)

Primary Use Cases & Examples

HTLCs are cryptographic smart contracts that enable conditional payments across blockchains or payment channels, serving as the foundational building block for trustless interoperability.

05

Limitations & Considerations

While powerful, HTLCs have inherent constraints that shape their application:

  • Liquidity Requirements: For routing payments (e.g., Lightning), nodes must have sufficient locked capital in their channels, creating capital efficiency challenges.
  • Routing Complexity: Finding a path with adequate liquidity and favorable fees across a decentralized network is a non-trivial problem.
  • Timelock Management: Mismatched or poorly set timelocks can lead to funds being stuck or vulnerable. The entire route must use decrementing timelocks to prevent theft.
  • Privacy Leakage: The hash value is public, allowing network observers to correlate payments across different hops in a route.
06

Beyond Cryptocurrency: Smart Contract Oracles

The HTLC pattern can be adapted for oracle services, where data delivery is conditional on proof.

  • Example: A smart contract offers a reward for providing a specific data point (e.g., a sports score). The reward is locked in an HTLC. The first oracle to submit the correct data, which hashes to the predefined value, can claim the reward by revealing the data as the secret.
  • Use Case: This creates a simple, trust-minimized bounty system for data feeds, though it is less common than dedicated oracle networks like Chainlink for complex, frequent data.
HASH TIME-LOCKED CONTRACTS

Technical Deep Dive

Hash Time-Locked Contracts (HTLCs) are a fundamental cryptographic primitive enabling conditional, trust-minimized payments across blockchain networks. They are the core mechanism behind atomic swaps and payment channel networks.

A Hash Time-Locked Contract (HTLC) is a smart contract that enables conditional payments by requiring the recipient to provide cryptographic proof of payment knowledge within a specified time limit. It uses a hash lock and a time lock to create a secure, self-executing agreement. The hash lock requires the presentation of a cryptographic secret (preimage) that produces a known hash, while the time lock ensures the funds are returned to the sender if the condition is not met before a deadline. This mechanism allows for trustless transactions across different parties and even different blockchains, forming the backbone of technologies like Lightning Network payments and cross-chain atomic swaps.

HASH TIME-LOCKED CONTRACT (HTLC)

Common Misconceptions

Clarifying widespread misunderstandings about Hash Time-Locked Contracts, a fundamental building block for atomic swaps and payment channels.

No, a Hash Time-Locked Contract is a specific cryptographic primitive and conditional payment logic, not a general-purpose smart contract. While often implemented within a smart contract on platforms like Ethereum, an HTLC's core functionality—a payment locked by a hash preimage and a timelock—can also be implemented at the base protocol layer, as seen in the Lightning Network's script. Its purpose is narrowly defined to enable trustless exchange, unlike a general smart contract which can encode arbitrary business logic.

HASH TIME-LOCKED CONTRACT

Frequently Asked Questions (FAQ)

A Hash Time-Locked Contract (HTLC) is a smart contract that enables conditional payments across blockchains or payment channels, requiring the recipient to acknowledge a payment by submitting cryptographic proof within a set timeframe.

A Hash Time-Locked Contract (HTLC) is a specialized smart contract that enforces a conditional payment, requiring the recipient to produce a cryptographic proof (a secret preimage) to claim funds before a specified time limit expires. It works by locking funds with two conditions: 1) The recipient can claim the funds by revealing the secret that produces a pre-agreed cryptographic hash, or 2) The sender can refund the funds after the timelock period passes. This mechanism creates a trustless swap where both parties are protected: the recipient is incentivized to act, and the sender is guaranteed a refund if they don't. HTLCs are the foundational primitive for atomic swaps and Lightning Network payments.

ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team