BSIP: 0044\
Title: Hashed Time-Locked Contract\
Authors: Ryan R. Fox, John M. Jones, taconator\
Status: Draft\
Type: Protocol\
Created: 2018-08-22\
Discussion: https://github.com/bitshares/bsips/pull/104

# **Abstract**

This BSIP describes an implementation of a Hashed Time-Locked Contract (HTLC) operation.

# **Motivation**

The ability to securely hold tokenized assets within a hashed time-locked contract on the BitShares blockchain is a desirable feature that could be used by many persons, services, and businesses to mitigate risks between participants during asset transfer. HTLC implement conditional transfers, whereby a designated party (the "recipient") will reveal the preimage of a hash in order to execute the asset transfers from a second party (the "depositor"), else after time lock expiry "depositor" may retrieve their assets. No third-party escrow agent is required, rather the HTLC operation enforces conditions, evaluations and transfers through the BitShares consensus protocol.

# **Rational**

## **Elements of a Hashed Time-Locked Contract (HTLC)**

An HTLC is defined to have the following components:

* Parties to the HTLC

    * The depositor

    * The recipient

* Secured Asset

    * Symbol
    
    * Quantity

* Conditions

    * Hash lock

        * Preimage (the secret)

        * Preimage hash (hash of the preimage)

        * Preimage length

    * Time lock

        * Timeout threshold (expiry)

* Condition Evaluators

* Fees

  * Prepare operation fee
  
  * Prepare duration fee

  * Redeem operation fee

### **Parties**

Two parties must be defined within each HTLC: the `depositor` and the `recipient`. The `depositor` will secure their assets within the HTLC and designate the `recipient` to receive them. Note that a proposal transaction may be used for tasks such as multi-signature, but the end result at approval remains a single `depositor` and a single `recipient`.

### **Secured Asset**

An HTLC involves a conditional transfer of the defined `asset symbol` in the amount of `assets quantity` from the `depositor` to the `recipient`. The HTLC holds these designated `secured assets` from `depositor` on the blockchain and will continue to enforce the specified `conditions` until one is satisfied.

### **Conditions**

There are two competing conditions within an HTLC, the `hash lock` and the `time lock`.

The HTLC contains a `hash lock` condition, which comprise both the `preimage hash` and `preimage length`, barring the transfer of held `secured assets` unless satisfied. If a `preimage` of requisite `length` is provided to the HTLC which generates a hash matching the `preimage hash`, the `preimage` is then stored within the blockchain, and the `secured assets` are transferred to the `recipient`.

If a satisfactory `preimage` is not provided to the HTLC before the stipulated `time lock` expires, the `depositor` may request the return of `secured assets`. The HTLC will only evaluate transfer request from `depositor` and after `timeout threshold`, then return `secured assets` to `depositor`.

**Note:** we recommend the Committee the set maximum allowable `preimage length` to ensure unreasonably large submissions are rejected. 

### **Condition Evaluators**

The `preimage` can be thought of a secret key, that will eventually be shared with the `recipient`. This can be a word, a phrase, or even a random series of bytes. The `length` of the `preimage` must be specified within the HTLC at creation.

Upon presentation of a `preimage`, the HTLC `condition evaluator` validates:

1. That the `timeout threshold` has not yet occurred.

2. That the length of the `preimage` matches the specified `preimage length`. 

3. That the hash of the `preimage` calculates to the specified `preimage hash`. 

If all evaluations succeed, the `secured assets` are transferred to the `recipient`. If any evaluation fails, nothing happens; the HTLC remains ready to evaluate the next `preimage`.

### **Timing of Condition Evaluation**

The `timeout threshold` of the contract is defined by `depositor` within the HTLC at creation. It can be any time in the future and should allow enough time for `recipient` to review the HTLC and provide the `preimage`. Further, it should not be set too far into the future to mitigate against an unresponsive `recipient` impacting `depositor`, as their `secured assets` will be locked until `timeout threshold` expiry. The accuracy is based on when the `condition evaluator` runs, and should be considered accurate ± 15 seconds.

**Note:** we recommend the Committee set the maximum value for `timeout threshold` to limit the amount of time a contract may consume memory of validation nodes.

### **Early Termination of an HTLC**

To protect the `recipient`, early termination of an HTLC is not allowed by any party. Placing a `timeout threshold` far into the future is valid, up to the maximum defined by the Committee. User protection from locking up funds for an extremely long period could be provided by the UI used to create the HTLC.

### **Automatic Transfers Upon Expiry**

Upon expiry of the `timeout threshold`, the `secured assets` held within the HTLC will be queued for return to `depositor`. From this time, the HTLC will no longer evaluate the `hash lock`, preventing `recipient` from receiving the `secured assets`. No action is required by the `depositor` to receive their "locked" funds back from the contract after expiry. 

### **Fees**

We propose three (3) operations (see Specification) to implement the HTLC feature, each requiring distinct fees. All fees will be set and maintained by the Committee. 

The "prepare" operation will store in-memory data on validation nodes until redeemed or expiry. We recommend the `htlc_preparation_fee` be comprised of two (2) components: `GRAPHENE_HTLC_PREPARE_FEE` which is flat and `GRAPHENE_HTLC_DAILY_FEE` which is variable based on the number of days until `timeout threshold`.

The "redeem" operation frees most of the memory from the validation nodes and adds the `preimage` data into blockchain storage when the transaction is validated. We recommend the `htlc_redemption_fee` be comprised of two (2) components: `GRAPHEN_HTLC_REDEEM_FEE` which is may be quite low and `GRAPHENE_HTLC_KB_FEE` which is variable based on the total number of kilobytes of data committed to the blockchain.

The "extend expiry" operation will update the `timeout_threshold` to a future date, extending in-memory resources on validation nodes. We recommend the `htlc_extend_expiry_fee` be comprised of two (2) components: `GRAPHENE_HTLC_EXTEND_EXPIRY_FEE` which is flat and `GRAPHENE_HTLC_DAILY_FEE` which is variable based on the number of additional days added to extend the `timeout_threshold` of the contract.

## **Existing Escrow Proposals**

This section describes various escrow concepts that have been proposed either for BitShares or for other blockchains or services in terms of the elements that have been defined above. This is intended to provide some background and comparison to the concepts that follow.

### **BitShares Escrow**

A separate BSIP [cite] is currently being discussed that provides a more traditional escrow service. This involves parties, agents, and a more complex evaluation. HTLC shares some similarities, and could be considered a thin subset of BitShares Escrow.

The smaller, well-defined nature of HTLC provides a major advantage for applications that want to attempt tasks such as cross chain atomic swaps.

### **Scorum Atomic Swap**
[cite]

### **BitShares Multi-Signature Account**

One of the existing features of BitShares is the ability to have an account that requires multiples signatures by differently authorized parties [cite] and even hierarchical authorizations. Using this mechanism as a form of escrow is possible. But there are many limitations. More information on escrow and multi-signatures can be found in the BitShares Escrow BSIP [cite].

### **BitShares Proposals**

One of the existing features of BitShares is the ability to have a proposal that is recorded on the blockchain and awaits the authorization of the requisite parties (e.g. M-of-N signatures) to execute. However, the proposal does not "lock" any assets, so the transfer will fail if the sending account lacks sufficient funds during validation. If the required authorizations are not given by proposal expiry, then no transfer will occur. This feature also contains many limitations when compared to HTLC.

## **Possible Concepts to Implement**

The following will describe possible concepts that could be implemented within the BitShares protocol.

### **Set-Price Swap**

Two parties may agree on a swap of two distinct `secured assets` at a set price (defined exchange ratio), without using an exchange such as the BitShares DEX. This will require two (2) HTLC contracts containing the identical `preimage hash` within each to "link" them together and facilitate the execution of an "atomic swap" of these "locked" `secured assets` between the party's accounts resulting in a trustless value exchange.

#### **Business Approach**

Alice begins by generating a distinct `preimage` of her choosing, notes the `preimage length` and calculates the `preimage hash`. She retains the `preimage` in secret, then creates a new HTLC stipulating that the `depositor` account "alice" will transfer `quantity` "100" "bitUSD" `asset` into the `recipient` account "bob" if a `preimage` is presented matching the `preimage hash` before the `timelock threshold` of 10AM tomorrow. Upon consensus validation of the HTLC, the 100 bitUSD `secured assets` are transferred from Alice's `depositor` account into the HTLC where they remain locked by the `preimage hash` and `timelock threshold`. She then shares the resulting `contract identifier` with Bob.

Bob queries the blockchain for the `contract identifier` Alice provided. He examines to ensure it contains his desired `recipient` account, `asset` symbol, asset `quantity`, `preimage length`, and `timelock threshold`. Bob now creates his own HTLC that will deposit `quantity` "10,000" "BTS" `symbol` into the `recipient` account "alice" from `depositor` account "bob", if a `preimage` that generates the `preimage hash` Bob copied from Alice's HTLC before the `timelock threshold` of 5pm today. Upon consensus validation of Bob's HTLC, his 10,000 BTS `secured assets` are transferred from his `depositor` account and "locked" into the contract. He then shares the resulting `contract identifier` with Alice. Notice Bob specified a `timelock threshold` much shorter than Alice defined in her contract. This ensures Bob will have enough time to observe and use the `preimage` Alice will publish to the blockchain next. 

Alice now examines the HTLC Bob created, ensuring the `preimage hash` and `preimage length` both match the original values she used within her contract. She also verifies her desired `recipient` account "alice", the `quantity`, `symbol`, and the `timelock threshold` agree with her intentions. She now uses her `preimage` to "unlock" Bob's contract. Once consensus validation occurs, the HTLC will transfer the `secured assets` 10,000 BTS into her `recipient` account "alice". This reveals the `preimage` on the BitShares blockchain for Bob to use next. NOTE: She must do this before 5PM. Otherwise, Bob may (and should) reclaim the funds in the contract he created.

Bob can now observe the `preimage` Alice used to "unlock" his HTLC, and he will use it to "unlock" her HTLC to receive the 100 bitUSD `secured assets` into his `recipient` account "bob". NOTE: He must do this before 10AM tomorrow. Otherwise, Alice may (and should) reclaim the funds in the contract she created.

### **Cross-Chain Swap**

Similar to the set-price swap mentioned above, two parties may exchange tokens between distinct blockchains when both implement HTLC support. Bitcoin, Litecoin and many others support HTLC [cite].

#### **Business Approach**

Alice and Bob intend to swap BTC (bitcoin token) and BTS (BitShares token). This will require both parties to define both a BTC deposit address and BTS deposit account. These addresses/accounts will be exchanged between the parties.

Alice will initiate the first leg of the swap on the BitShares Network with her HTLC and Bob will follow up on the Bitcoin Network with his HTLC. Allice generates a distinct `preimage` of her choosing, notes the `preimage length` and calculates the `preimage hash`. She retains the `preimage` in secret, then creates a new HTLC stipulating that the `depositor` account "alice" will transfer `quantity` "10,000" "bitUSD" `asset` into the `recipient` account "bob" if a `preimage` is presented matching the `preimage hash` before the `timelock threshold` of 10AM tomorrow. Upon consensus validation of the HTLC on the BitShares Network, the 10,000 bitUSD `secured assets` are transferred from Alice's `depositor` account into the HTLC where they remain locked by the `preimage hash` and `timelock threshold`. She then shares the resulting `contract identifier` with Bob.

Bob queries the BitShares Network for the `contract identifier` Alice provided. He examines to ensure it contains his desired `recipient` account, `asset` symbol, asset `quantity`, `preimage length`, and `timelock threshold`. Bob now creates and funds his own HTLC on the Bitcoin Network that will spend the `UTXO` of this contract to the `recipient address` Alice provided during their setup phase, of `amount` 1 BTC if a `preimage` that generates the `preimage hash` Bob copied from Alice's HTLC before the `timelock threshold` of 5pm today. Upon consensus validation of Bob's HTLC on the Bitcoin Network, 1 BTC he controlled are spent into the contract and "locked". He then shares the resulting `contract identifier` with Alice. Notice Bob specified a `timelock threshold` much shorter than Alice defined in her contract. This ensures Bob will have enough time to observe and use the `preimage` Alice will publish to the blockchain next. 

Alice now examines the HTLC Bob created on the Bitcoin Network, ensuring the `preimage hash` and `preimage length` both match the original values she used within her contract. She also verifies her desired `recipient address`, `quantity`, and `timelock threshold` agree with her intentions. She now uses her `preimage` to "unlock" Bob's contract. Once consensus validation occurs on the Bitcoin Network, the HTLC will spend 1 BTC to Alice's `recipient address`. This reveals the `preimage` on the Bitcoin Network for Bob to use next. NOTE: She must do this before 5PM. Otherwise, Bob may (and should) reclaim the funds in the contract he created.

Bob has now observed the `preimage` Alice used to "unlock" his HTLC, and he will use it to "unlock" her HTLC to receive the 10,000 bitUSD `secured assets` into his `recipient` account "bob". NOTE: He must do this before 10AM tomorrow. Otherwise, Alice may (and should) reclaim the funds in the contract she created.

# **Specifications**

## **Objects**

```
      class htlc_object : public graphene::db::abstract_object<htlc_object> {
         public:
            static const uint8_t space_id = implementation_ids;
            static const uint8_t type_id  = impl_htlc_object_type;

            account_id_type depositor;
            account_id_type  recipient;
            asset amount;
            fc::time_point_sec expiration;
            asset pending_fee;
            vector<unsigned char> preimage_hash;
            uint16_t preimage_size;
            transaction_id_type preimage_tx_id;
      };
```

## **Operations**

### **Prepare**

```
transaction_obj htlc_prepare(depositor, quantity, symbol, recipient, hash_algorithm, preimage_hash, preimage_length, timeout_threshold, htlc_preparation_fee)
  Validate: HTLC signed by requisite `authority` for `depositor` account 
  Validate: `depositor` account has requisite `quantity` of `symbol` asset for the `guarantee`
  Validate: `timeout_threshold` < now() + GRAPHENE_HTLC_MAXIMUM_DURRATION
  Calculate: `required_fee` = GRAPHENE_HTLC_OPERATION_FEE + GRAPHENE_HTLC_DAILY_FEE * count((`timeout_threshold` - now()), days)
  Validate: `depositor` account has requisite `quantity` of BTS for `required_fee`
  Validate: `recipient` account exists
  Validate: `preimage_length` does not exceed GRAPHENE_HTLC_MAXIMUM_PREIMAGE_LENGTH
  Validate: `preimage_hash` well formed
  Update: BTS balance of `depositor` based on `required_fee`)
  contract = new htlc_obj
  Set: `contract.depositor` = `depositor`
  Set: `contract.recipient` = `recipient`
  Set: `contract.hash_algorithm` = `hash_algorithm`
  Set: `contract.preimage_hash` = `preimage_hash`
  Set: `contract.preimage_length` = `preimage_length`
  Set: `contract.timeout_treshold` = `timeout_threshold`
  Transfer: from `depositor` account to `contract.quantity` of `contract.symbol`
  return results
```

### **Redeem**

```
transaction_obj htlc_redeem(fee_paying_account, id, preimage, htlc_redemption_fee)
  Validate: transaction signed by requisite `authority` for `fee_paying_account` // any account may attempt to redeem
  Get: get_htlc(id)
  Validate: `fee_paying_account` account has requisite `quantity` of BTS for `htlc_redeem_fee` and `htlc_kb_fee`
  Update: balance of `fee_paying_account` based on total fees
  // Evaluate: timelock
     if now() < `timeout_threshold` then return error // "timeout exceeded"
  // Evaluate: hashlock
     if length(preimage) != `id.preimage_length` then return error // "preimage length mismatch"
     Calculate: `preimage_hash` = hash(preimage)
     if `preimage_hash` != `id.preimage_hash` then return error // "invalid preimage submitted"
     Update: balance of `id.recipient` add asset `id.symbol` of quantity `id.quantity`
     Add: transaction to mempool 
     Set: `id.preimage_tx_id` = `transaction_id` 
     Cleanup: memory allocated to this htlc
     Virtual Operation: Update account history for `depositor` to reflect redemption as by default the above operation will only appear for `redeemer`

     return: results
```

### **Extend Expiry**

```
transaction_obj htlc_extend_expiry(depositor, id, timeout_threshold, htlc_extention_fee)
  Validate: 'depositor' = get_htlc(id).depositor 
  Validate: `timeout_threshold` < now() + GRAPHENE_HTLC_MAXIMUM_DURRATION
  Calculate: `required_fee` = GRAPHENE_HTLC_DAILY_FEE * count((`timeout_threshold` - now()), days)
  Validate: `depositor` account has requisite `quantity` of BTS for `required_fee`
  Update: BTS balance of `depositor` based on `required_fee`)
  Set: `contract.timeout_treshold` = `timeout_threshold`
  return results
```

### **At Expiry** (evaluated at each block commit)

```
  Get: get_htlc(id)
  Update: balance of `depositor` add asset `id.symbol` of quantity `id.quantity`
  Cleanup: memory allocated to this htlc
  Virtual Operation: Update account history for `depositor` to reflect expiry without redemption.
```

## **cli_wallet APIs**

### **htlc_prepare**

### **htlc_redeem**

### **htlc_extend_expiry**

## **witness_node APIs**

### **get_htlc**

### **get_htlcs_for_account**

# **Discussion**

https://github.com/bitshares/bsips/pull/104

# **Summary for Tokenholders**

Hashed Timelock Contracts (HTLCs) enable conditional transfers, whereby distinct account holders may transfer tokens from one account (`sender`) to a second account (`receiver`) before a defined expiry (`timelock`), only if the `preimage` (a.k.a. password) is revealed (`hashlock`) on the blockchain. If the `hashlock` condition is not satisfied prior to the `timelock` the tokens are return to the `sender`.

A typical scenario involves “Alice” and “Bob” each having accounts on the BitShares Network and addresses on the Bitcoin Network willing to trade their tokens. Alice will begin by creating an HTLC on BitShares to transfer BTS tokens from account `alice` to account `bob` with conditions set for hash of preimage (`hashlock`) and contract expiry (`timelock`). Bob will review her HTLC, if acceptable he will create an HTLC on the Bitcoin Network to transfer BTC from `his address` to `her address` with conditions set to the same `hashlock` value and a `timelock` value approximately half that specified by Alice. Next, Alice will review Bob’s HTLC for correctness and if acceptable, will redeem the BTC therein by publishing her `preimage` to satisfy the `hashlock` prior to the `timelock` expiry. Finally, Bob will observe the revealed `preimage` and use it to redeem Alice’s HTLC on the BitShares Network resulting in the BTS transferring to his account. Alice and Bob successfully exchanged native BTS and BTC at their agreed to ratio without any intermediaries.

# **Copyright**

This document is placed in the public domain.

# **See Also**

A description of [Hashed Timelock Contracts](https://en.bitcoinwiki.org/wiki/Hashed_Timelock_Contracts)
