hash time-locked contract (HTLC)
A hash time-locked contract is the small but powerful primitive underneath atomic swaps and payment-channel routing. It locks funds under two simultaneous conditions: a hashlock, meaning the recipient can claim the funds only by revealing a secret value whose hash was specified in advance; and a timelock, meaning if that secret is not revealed before a deadline, the sender can reclaim the funds. It is a conditional payment with a built-in escape hatch.
The cleverness is that the same secret can be reused to coordinate actions across multiple contracts or chains. Because claiming the money forces you to publish the preimage, and that preimage then unlocks a second HTLC elsewhere, you can chain payments so that either every hop completes or each one safely times out and refunds. This is precisely how the Lightning Network routes a payment through intermediaries who never need to trust one another, and how cross-chain atomic swaps bind two independent ledgers.
The timelocks must be ordered carefully: each hop toward the destination needs a longer timeout than the next, so that an honest party always has time to react after the secret is revealed downstream. Get the ordering wrong and a counterparty can claim from you while your own claim has already expired. HTLCs also assume liveness — you must be online to act before your timelock, which is why Lightning relies on watchtowers and why long timelocks lock up capital. The hash function must be preimage-resistant for the lock to be meaningful.
function withdraw(bytes calldata preimage) external {
require(sha256(preimage) == hashlock, "bad secret");
receiver.transfer(address(this).balance); // reveals preimage on-chain
}
function refund() external {
require(block.timestamp >= timelock, "too early");
sender.transfer(address(this).balance);
}Claim by secret, or refund after timeout — the two paths that make swaps all-or-nothing.