Cross-chain atomic swap

The idea of ​​atomic swap was first proposed on the BitcoinTalk forum in 2013, which enables the exchange of tokens between two blockchains.

These exchanges are atomic because both parties either receive the other's coins or both keep their own coins. It is impossible for one party to deceive the other. It does not rely on any trusted third party, eliminating counterparty risk.

There are many use cases. For example, they can serve as the basis for non-custodial trading, where users can trade while controlling their funds.

basic knowledge

A Bitcoin address is like a locked mailbox with a deposit slot. When Bob sends Bitcoin to Alice, he puts the Bitcoin into the slot of Mailbox A, which contains Alice's "address." Only Alice has the key to open the mailbox and retrieve the coins.

There are more exotic locks than those that can be opened with a simple private key. These locks are considered Bitcoin smart contracts and can specify arbitrarily complex locking conditions.

Hash lock

They can be unlocked with a password, such as a PIN that unlocks your phone. The secret is actually a value/preimage that hashes to a given value, which is displayed on the lock for everyone to see. The corresponding smart contract is a hash puzzle. Once unlocked using the PIN/preimage, it becomes publicly visible on the blockchain.

time lock

These locks cannot be opened until a predetermined time is reached, which can be the UNIX epoch time (the number of seconds since January 1, 1970) or the block height. The corresponding smart contract is called CheckLockTimeVerify.

Atomic swap

Let’s use these locks to exchange Alice’s BSV coins and Bob’s BTC coins in a mutually agreed-upon ratio.

set up

Alice puts the BSV with the hash lock into Bob’s mailbox and tells Bob the hash value. Bob then puts the BTC into Alice's mailbox using the same hash lock. The two hash locks share the same PIN, which was generated by Alice and temporarily hidden from Bob.

exchange

Alice uses her private key A and secret PIN to open mailbox A to get the BTC Bob deposit. Bob learns the PIN that Alice just revealed on the BTC blockchain. He can use the same PIN to open mailbox B, along with his private key B, and get a BSV Alice deposit. They exchanged coins without any third party.

Opening one mailbox effectively gives the other party the ability to open another mailbox. If Alice doesn't open her mailbox, Bob can't open her mailbox.

What if Alice or Bob terminates?

If Bob does not put BTC into mailbox A after Alice deposits BSV, her BSV will be stuck. Likewise, if Alice does not enter a PIN after setup, Bob's BTC coins will be stuck, and so will Alice's BSV. This is where time locks come in. Each mailbox has an anti-jam time lock, so if no one opens the lockbox in time, the coins can be returned. For example, Bob can unlock mailbox A with his key B after a certain amount of time.

Note that Alice's time lock on mailbox B must be longer than Bob's time lock on primary mailbox A. Otherwise, Alice can wait until the time lock on mailbox B expires, retrieve her BSV coins, and use the PIN to open mailbox A to withdraw Bob's BTC deposit.

Hash Time Lock Contract (HTLC)

Atomic swaps use a smart contract called a Hash Time Lock Contract (HTLC) because it combines a hash lock and a time lock.

In BSV, HTLC can be implemented in sCrypt as shown below.

class HashTimeLockContract extends SmartContract {
    
    
    @prop() readonly alicePubKey: PubKey

    @prop() readonly bobPubKey: PubKey

    @prop() readonly hashX: Sha256

    @prop() readonly timeout: bigint // Can be a timestamp or block height.


    // hash lock
    @method()
    public unlock(x: ByteString, aliceSig: Sig) {
    
    
        // Check if H(x) == this.hashX
        assert(sha256(x) == this.hashX, 'Invalid secret.')

        // Verify Alices signature.
        assert(this.checkSig(aliceSig, this.alicePubKey))
    }

    // time lock
    @method()
    public cancel(bobSig: Sig) {
    
    
        assert(this.ctx.locktime >= this.timeout, 'locktime has not yet expired')

        // Verify Bobs signature.
        assert(this.checkSig(bobSig, this.bobPubKey))
    }
}

HLTC contract source code

There are two ways to call the contract, namely opening the mailbox:

  1. unlock():Successfully exchanged using PIN
  2. cancel(): No exchange occurs and the coins are returned. this.ctx Yes ScriptContext that allows access to the lock time of the spending transaction.

In BTC, HTLC can be implemented as follows:

OP_IF
  // hash lock branch
  OP_SHA256
  <hash of secret>
  OP_EQUALVERIFY
  <pubKey of swap>
  OP_CHECKSIG
OP_ELSE
  // time lock branch
  <locktime>
  OP_CHECKLOCKTIMEVERIFY
  OP_DROP
  <pubKey of refund>
  OP_CHECKSIG
OP_ENDIF

It also has two unlocking methods, which are used in the time lock branchOP_CHECKLOCKTIMEVERIFY. Use script instead of sCrypt because BTCdisables many opcodes.

Complete protocol sequence

In summary, the atomic swap protocol between BSV and BTC can be executed by following the following steps.

  1. Alice generates a secure random number x and calculates its hash: h = SHA256(x). Alice sends h to Bob.
  2. Alice locked her coins in HTLC on BSV, which can be unlocked in one of two ways: 1) hashing to the value of h and Bob's signature; 2) Alice's signature after say 24 hours. Alice deploys the contract by broadcasting a transaction to the BSV network.
  3. Bob locked the coins in BTC's HTLC, which can be unlocked in one of two ways: 1) hashing to the value of h and Alice's signature; 2) Bob's signature after 48 hours. Bob deploys the contract by broadcasting a transaction to the BTC network.
  4. After confirming Bob's transaction, Alice claims the BTC by providing x and her signature.
  5. Bob observes x on BTC and claims BSV using x and his signature.

If steps 3 or 4 do not occur, both parties can get their coins back after the time lock expires.

generalize

We have demonstrated how to automatically exchange coins on the BSV and BTC blockchains. Any two blockchains can support cross-chain atomic swaps as long as they support HTLC, i.e. have the same hash function and support time locks. For example, the following exchange has been implemented:

Surprisingly, atomic swaps can even be implemented on blockchains without HTLC, such asMonero. Usingadvanced cryptography, atomic swaps can even be used on any blockchain, as long as it can verify signatures.

Guess you like

Origin blog.csdn.net/freedomhero/article/details/134642493