BIP199 for Hashed Timelocked Contracts

Hashed Timelocked Contracts (HTLC) are a well-known and simple technique for building protocols for atomic swaps. They allow you to pay another party for some information (generally, a key) with a condition that allows you to receive your money back if the party does not cooperate.

HTLCs are a fundamental tool in the Lightning network, in zero-knowledge contingent payments (ZKCP) like the one we performed last year at FC’16, and in our XCAT project that we announced last month. One of the first steps forward is the inclusion of general HTLC functionality in the Bitcoin Core wallet.

This week, our submitted BIP199 draft was merged. We also have a work-in-progress reference implementation in the Bitcoin Core wallet. HTLCs can be used today without any changes to the Bitcoin protocol, so these proposals and implementations are for standardizing best practices and ecosystem compatibility.

Check out the current BIP text here:

Overview of HTLC

HTLC scripts look like this:

    [HASHOP] <digest> OP_EQUALVERIFY OP_DUP OP_HASH160 <seller pubkey hash>
    <num> [TIMEOUTOP] OP_DROP OP_DUP OP_HASH160 <buyer pubkey hash>

HASHOP is a hashing algorithm (RIPEMD, SHA256), and TIMEOUTOP is either OP_CHECKLOCKTIMEVERIFY or OP_CHECKSEQUENCEVERIFY. This script allows the “buyer” to purchase the preimage to <digest> by forcing the seller to reveal it when they claim their funds. If the seller doesn’t reveal it, the buyer can get their money back after the timeout period.

It’s easy to see how cross-chain atomic swaps can be built with this mechanism:

  1. Alice randomly samples K, the key. She hashes it, producing X.
  2. Alice creates a transaction paying Bob 1 BTC, with a timeout of 1 day, to produce the preimage of X.
  3. Bob waits for Alice’s transaction to appear in the Bitcoin blockchain, and then submits an HTLC transaction paying Alice 0.02 ZEC for the preimage of X with a smaller timeout of half a day.
  4. Once Bob’s transaction appears in the Zcash blockchain, Alice can obtain her ZEC. The script forces her to reveal K.
  5. Once Bob sees Alice’s reveal of K, he can obtain his BTC.

The timeouts are selected so that Bob always has an opportunity to obtain a refund before Alice. Otherwise, Alice could wait to obtain her refund, and then claim Bob’s money by revealing K.

Having contracts like HTLCs standardized and included in Bitcoin and Zcash will help both of our communities build exciting technologies like decentralized exchanges.