Hash Time-Locked Contracts: The Cryptography Behind Trustless Trading
A deep explanation of Hash Time-Locked Contracts (HTLCs) — the cryptographic construction that makes atomic swaps, payment channels, and cross-chain trading possible without any trusted intermediary.
The Trust Problem
Suppose you want to buy Marscoin from a stranger on the internet. You have Bitcoin. They have MARS. You’ve agreed on a price. Now what?
If you send your Bitcoin first, the stranger could simply keep it and never send the Marscoin. If they send their Marscoin first, you could keep it and never send the Bitcoin. No matter who goes first, someone is exposed. This is not a new problem — it is the same dilemma that has plagued long-distance commerce for thousands of years, from Phoenician merchants sending goods across the Mediterranean to modern wire transfers between countries with no shared legal system.
The traditional solution is a trusted intermediary. A bank, an escrow agent, a marketplace with a reputation system, a regulated exchange. Someone both parties believe will enforce the deal honestly. This works well enough on Earth, where legal systems, regulatory bodies, and corporate accountability create layers of enforcement. But it introduces a dependency: both parties must trust the intermediary’s competence, honesty, and continued existence.
A Hash Time-Locked Contract — HTLC — eliminates the intermediary entirely. It replaces human trust with mathematical proof. Two people who have never met, operating on two completely independent blockchains, can execute a trade where either both get what they were promised, or neither loses anything, and no third party is involved at any point.
This is not a theoretical construct. Marscoin completed its first mainnet atomic swap using HTLCs on April 12, 2026, exchanging real Bitcoin for real MARS between two machines that shared nothing but a cryptographic secret.
To understand how this works, we need to build up from two fundamental ideas: hash functions and time locks.
Part 1: The Hash Lock
What Is a Hash Function?
A hash function is a mathematical one-way street. You give it any input — a word, a number, an entire book — and it produces a fixed-length output called a hash or digest. The same input always produces the same output. But given the output, there is no practical way to work backwards to find the input. It would take more energy than the sun produces in its lifetime to brute-force a 256-bit hash.
For example, the SHA-256 hash of the text hello is:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Change a single character — Hello with a capital H — and the hash is completely different:
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
There is no pattern. No relationship between the inputs that would let you predict the output. This property — called preimage resistance — is the foundation of the hash lock.
The Secret and Its Fingerprint
Now imagine you generate a random number — 32 bytes of pure randomness from your computer’s cryptographic random number generator. This is your preimage: a secret that only you know.
You compute the hash of this secret. In Marscoin and Bitcoin’s HTLC system, we use HASH160 — which is SHA-256 followed by RIPEMD-160, producing a 20-byte output. This hash is the fingerprint of your secret. You can share the fingerprint with anyone in the world, and they cannot derive your secret from it. But the moment you reveal the secret, anyone can verify it matches the fingerprint by computing the hash themselves.
This asymmetry — easy to verify, impossible to reverse — is what makes the hash lock work.
Building a Lockbox
In Bitcoin Script — the simple programming language that defines how transaction outputs can be spent — you can create an output that says:
“To spend these coins, you must provide a value whose HASH160 equals this specific 20-byte fingerprint, and a valid signature from this specific public key.”
In script notation:
OP_HASH160 <fingerprint> OP_EQUALVERIFY <recipient_pubkey> OP_CHECKSIG
This is the hash lock. The coins are locked behind two conditions: knowledge of the secret (proven by providing the preimage that hashes to the fingerprint) and ownership of a specific private key (proven by a digital signature). Both conditions must be met simultaneously. Knowing the secret alone is not enough — you also need the right key. Having the right key alone is not enough — you also need the secret.
The person who created the secret can share the fingerprint openly. The person who receives the fingerprint can verify any claimed preimage instantly. But without the actual preimage, the coins are immovable.
Part 2: The Time Lock
The Problem with Hash Locks Alone
A pure hash lock has a critical flaw: what if the secret is never revealed? The coins would be locked forever. The sender cannot get them back (they’re locked behind the recipient’s public key), and the recipient cannot claim them (they don’t know the preimage). The funds become permanently inaccessible — a financial black hole.
This is where time enters the picture.
OP_CHECKLOCKTIMEVERIFY
Bitcoin (and Marscoin, which shares Bitcoin’s scripting system) includes an operation called OP_CHECKLOCKTIMEVERIFY, or CLTV. It does exactly what the name suggests: it checks that a transaction is not valid until a specific point in time — expressed as either a block height or a Unix timestamp.
When CLTV is included in a script, any transaction attempting to spend the output must have its nLockTime field set to at least the specified value. Miners enforce this: they will not include a transaction in a block if its locktime hasn’t been reached. This enforcement is not discretionary — it is a consensus rule. Every node on the network independently verifies it.
The Refund Path
By combining CLTV with a second spending condition, we create a refund path:
“Alternatively, if the block height exceeds 944,820, the original sender can reclaim these coins with their own signature.”
In script:
<locktime> OP_CHECKLOCKTIMEVERIFY OP_DROP <sender_pubkey> OP_CHECKSIG
Now the output has an expiration date. If the intended recipient doesn’t claim the coins by revealing the preimage before the locktime, the sender can take them back. The coins are never permanently stuck.
Part 3: The Complete HTLC
Two Paths, One Output
The hash lock and the time lock are combined into a single Bitcoin Script using an OP_IF / OP_ELSE conditional:
OP_IF
OP_HASH160 <fingerprint> OP_EQUALVERIFY
<recipient_pubkey> OP_CHECKSIG
OP_ELSE
<locktime> OP_CHECKLOCKTIMEVERIFY OP_DROP
<sender_pubkey> OP_CHECKSIG
OP_ENDIF
This script defines two mutually exclusive spending paths. The person spending the output chooses which path to take by providing either OP_TRUE (selecting the IF branch) or OP_FALSE (selecting the ELSE branch) in their transaction’s witness data.
Path 1 — Claim: The recipient provides the preimage and their signature. The script verifies that HASH160(preimage) matches the fingerprint and that the signature is valid for the recipient’s public key. If both checks pass, the coins are spent.
Path 2 — Refund: The sender provides their signature, and the transaction’s nLockTime must exceed the embedded locktime. The script verifies the timelock condition and the signature. If both pass, the coins return to the sender.
Both paths are baked into the same transaction output. Both are enforced by every miner on the network. Neither party can modify or remove either path after the output is created. This is the fundamental property that makes HTLCs trustless: the rules are set when the contract is funded, and the blockchain enforces them impartially.
Wrapping It in P2WSH
The raw HTLC script above is not placed directly in the transaction output. Instead, it is hashed (SHA-256), and the hash is placed in a P2WSH (Pay-to-Witness-Script-Hash) output. This is a standard SegWit address that looks like bc1q... on Bitcoin or mars1q... on Marscoin.
The actual script — called the witness script — is revealed only when someone spends the output. Until then, the blockchain stores only the 32-byte hash. This saves space and provides a modest privacy benefit: observers cannot see the HTLC conditions until the output is claimed or refunded.
When spending, the full witness script is provided alongside the preimage (or locktime proof) and the signature. Every node independently hashes the provided script, checks that it matches the committed hash, and then executes the script to verify the spending conditions.
Part 4: Making Swaps Atomic
The Key Insight
Here is where everything comes together. Suppose Alice has Marscoin and wants Bitcoin. Bob has Bitcoin and wants Marscoin. They agree on a price.
Alice generates a random preimage and computes its HASH160 fingerprint. She shares the fingerprint — but not the preimage — with Bob.
Alice creates a Marscoin HTLC: “Bob can claim these MARS if he provides the preimage matching this fingerprint, OR Alice can refund after 234 blocks (~8 hours).”
Bob, seeing Alice’s MARS locked on the Marscoin blockchain, creates a Bitcoin HTLC using the same fingerprint: “Alice can claim this BTC if she provides the preimage matching this fingerprint, OR Bob can refund after 24 blocks (~4 hours).”
Now both currencies are locked, and the same secret unlocks both. Alice knows the preimage. She claims the Bitcoin by providing it. The moment she does, the preimage becomes visible in the Bitcoin transaction’s witness data — it’s public, on-chain, readable by anyone.
Bob’s wallet watches the Bitcoin blockchain. When it sees Alice’s claim transaction, it extracts the preimage from the witness and uses it to claim the Marscoin on the Marscoin blockchain.
Alice got Bitcoin. Bob got Marscoin. Neither had to trust the other. The preimage that unlocked one side necessarily unlocked the other.
Why the Timelocks Are Asymmetric
Notice that Alice’s MARS refund takes 8 hours, but Bob’s BTC refund takes only 4 hours. This asymmetry is deliberate and critical.
Bob funded second (he sent BTC after seeing Alice’s MARS locked). Therefore, he needs to be able to exit first. If both timelocks were equal, Alice could wait until the very last moment to claim the BTC, leaving Bob no time to extract the preimage and claim the MARS before Alice’s refund path opened. Alice would get the BTC, then immediately refund her MARS — ending up with both currencies.
The 4-hour gap ensures that when Alice claims the BTC, Bob has at least 4 hours to observe the preimage reveal and submit his own MARS claim before Alice’s refund becomes possible. Under normal conditions this takes minutes, not hours. The gap is a safety margin, not a minimum waiting period.
The rule is simple: the party who funds last must be able to refund first. This eliminates the race condition that would otherwise break atomicity.
What if Nobody Claims?
If Alice never claims the BTC — perhaps she loses her internet connection, or changes her mind — then nobody learns the preimage. Bob cannot claim the MARS (he doesn’t know the secret). After his 4-hour timelock expires, Bob refunds his BTC. After Alice’s 8-hour timelock expires, she refunds her MARS. Both parties end up exactly where they started. The swap simply didn’t happen.
This is the meaning of atomic: all or nothing. There is no intermediate state where one party holds both currencies.
Part 5: Where HTLCs Are Used
Atomic Swaps
The application described above — and now implemented in Electrum-Mars — is the most direct use of HTLCs. Two independent blockchains, two HTLC outputs, one shared secret. The construction works between any two chains that support hash functions and timelocks in their scripting systems. Bitcoin, Litecoin, Marscoin, Monero (with adaptations), and dozens of others can participate.
Payment Channels (Lightning Network)
The Lightning Network — Bitcoin’s layer-2 scaling solution — is built almost entirely on HTLCs. When a Lightning payment routes through multiple nodes, each hop is an HTLC: the payment is forwarded by revealing the preimage, and it can be reclaimed by the sender if the payment fails. The network of HTLCs across multiple hops creates a chain of conditional payments that either all complete or all unwind — exactly the same atomicity property used in cross-chain swaps.
Submarine Swaps
A submarine swap is a trade between an on-chain cryptocurrency and a Lightning payment. It uses the same HTLC construction but with one leg on the blockchain and the other in a payment channel. Boltz Exchange is a well-known implementation of this pattern.
Cross-Chain Bridges (with Caveats)
Some cross-chain bridge designs use HTLCs to move assets between chains. However, most modern bridges use different trust assumptions (multisig committees, optimistic verification, zero-knowledge proofs) because HTLCs require active participation from both parties. Bridges typically need to serve thousands of users without requiring individual handshakes.
Part 6: Limitations and Honest Caveats
HTLCs are not a universal solution. Their strengths come with inherent tradeoffs.
Active participation required. Both parties must be online (or have a wallet running in the background) to claim within the timelock window. If your wallet is offline when the preimage is revealed, you might miss the claim window and be forced to refund. This is acceptable for peer-to-peer swaps but doesn’t scale to automated high-frequency trading.
On-chain footprint. Each HTLC is a visible, on-chain transaction. Observers can see the HTLC structure in the witness data, correlate the timing and amounts between two chains, and identify swap participants. HTLCs do not provide privacy. More advanced constructions — like adaptor signatures using Taproot — can hide the HTLC mechanics inside a normal-looking transaction, but this is future work.
Timelock UX. If a swap fails, your funds are not immediately available. You wait 4 hours (BTC) or 8 hours (MARS) for the refund. This is the price of trustlessness — the timeout exists to prevent cheating, and it cannot be shortened without weakening the safety guarantee.
Fee sensitivity. On the Bitcoin side, if network fees spike during the claim window, a low-fee claim transaction might not confirm before the refund becomes available. The 4-hour gap is designed to absorb typical fee fluctuations, but extreme conditions could create pressure. A future version of Electrum-Mars may implement dynamic timelocks that adjust based on observed fee conditions.
Part 7: Beyond Earth — IPAS
Here is where HTLCs reveal their most profound property: they do not require real-time communication.
The preimage doesn’t degrade with distance. The hash function doesn’t know what planet it’s on. OP_CHECKLOCKTIMEVERIFY uses block heights, not wall-clock time, so clock synchronization between Earth and Mars is irrelevant. Every property that makes HTLCs trustless on Earth makes them equally trustless across 225 million kilometers.
This realization leads to IPAS — the InterPlanetary Atomic Swap. Named in the same spirit as IPFS (the InterPlanetary File System already integrated into the Martian Republic), IPAS extends atomic swap timelocks from hours to days, enabling trustless cross-planetary commerce, remittance, and investment.
Both planets would naturally maintain delayed, batched mirrors of each other’s blockchain — Mars relaying Bitcoin block headers at the speed of light, Earth receiving Marscoin blocks with the same delay. Neither planet depends on the other’s chain for its own consensus. They simply observe. And that observation — detecting a preimage revealed in a claim transaction — is all IPAS needs to complete a swap.
The implications are startling. Capital on Earth can fund operations on Mars almost directly. Martian wealth can purchase equipment, supplies, even spacecraft on Earth immediately. A colonist locks MARS. An investor on Earth locks BTC directed to the colonist’s supplier. The preimage bridges both chains across the void. Neither party trusts the other. Both get exactly what they agreed to.
The full analysis — timelock calculus for various orbital positions, solar conjunction handling, the destination address insight that enables interplanetary commerce and remittance, relay infrastructure requirements, and economic implications — is published as a dedicated research paper: IPAS: InterPlanetary Atomic Swaps.
For a practical guide to using atomic swaps today on Earth, see Atomic Swaps: Trustless BTC↔MARS Exchange. For the full implementation details, see the technical reference on GitHub. For background on blockchain fundamentals, see the Martian Republic Academy.