Lightning HTLCs Explained: Hashlocks, Timelocks, and Payment Safety
A hash time-locked contract (HTLC) is a conditional transfer that can be completed with a matching secret or recovered after a timeout, subject to the protocol's transaction and timing rules. HTLCs have historically been central to multi-hop Lightning payments.
Payment hashes and preimages
A recipient creates a secret value called a payment preimage and supplies its hash as a payment condition. A payer and the forwarding nodes can lock transfers against that hash. When the recipient reveals the matching preimage to claim the payment, upstream hops can use the same proof to complete their conditional transfers.
The hash is not the secret. Publishing a payment hash alone does not authorize claiming funds. Implementations must verify that a supplied preimage hashes to the expected value.
Why timelocks are necessary
If the preimage never arrives, a conditional payment must not remain unresolved forever. HTLCs therefore include expiry conditions. In multi-hop routes, deadlines are staggered so a forwarding node has time to settle its incoming contract after settling its outgoing one.
This timing is a security property, not just a convenience. Poorly chosen or mishandled deadlines can expose intermediaries to losses when channels close or the chain becomes congested.
A three-node example
Alice wants to pay Carol through Bob. Alice conditionally pays Bob, and Bob conditionally pays Carol against the same payment hash. Carol reveals the preimage when claiming her payment; Bob then uses that preimage to claim from Alice. If the payment cannot complete, the relevant timeout paths eventually allow recovery according to the channel rules.
This is a simplified model. Real implementations account for routing fees, onion messages, commitment updates, failure messages, and on-chain resolution.
What developers should test
Test success, incorrect preimages, expired invoices, insufficient liquidity, route failure, and a channel closing while a payment is pending. Distinguish an HTLC being offered, accepted, fulfilled, failed, or resolved on-chain. A pending HTLC is not the same as final payment success.
Primary references
BOLT 2 — Peer Protocol for Channel Management: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
BOLT 3 — Bitcoin Transaction and Script Formats: https://github.com/lightning/bolts/blob/master/03-transactions.md
BOLT 4 — Onion Routing Protocol: https://github.com/lightning/bolts/blob/master/04-onion-routing.md
