The concept of peer-to-peer “trust-less” exchange across blockchains has been called the “holy grail” of alternative coins.
Currently, trading is achieved through centralized exchanges, which don’t need to commit actual blockchain transactions. The exchange is proxied via “vouchers,” which are swapped internally with low latency. This grants them a significant speed advantage to decentralized exchanges. As centralization allows for consistency and availability with no need for partition tolerance, which puts in disadvantage fault-tolerant networks such as Bitcoin.
The tradeoffs of a centralized system are well-known to the community. End-users are under constant risk of their assets being stolen (Mt.Gox, Coincheck, Binance, Bitgrail), and are constrained by the requirements and regulations of the host’s country, as well as subject casino- like manipulations, and high fees for exchanges and withdrawals. By granting control of the private keys to the exchange, the user is forfeiting sovereignty of their assets. As the adage goes, “If you do not hold your private keys, you do not own your coins.”
The first significant attempt at a decentralized swap was with The MultiGateway Project, which relied on NXT Asset Exchange. This attempted to swap coins by using “off-chain” proxy tokens as their form of vouchers. But since it still relied on blockchain transactions, the trading process was slow. Furthermore, the conversion from coin to proxy-token requires gateways which were a point of failure. This is a similar approach used by sidechains, which convert proxies (2-way pegs) through federated gateways.
The basic constrain for swaps is the procedural nature of computer code, as well as the blockchain ledger: Neither allows simultaneous steps. Therefore, one side must commit their side of the deal first, who would be obliged to “trust” their counterparty. Using the services of an escrow moves the trust to a third party (and adds fees). The swap protocol aims to obliterate the need for trust, protecting both sides from vulnerability by making both sides of the trade interdependent. Trust merely is placed on a cryptographic contract, with automatic execution, which neither party can tamper, and with terms which both agree.
Unfortunately, atomic swaps are neither as fast nor cheaper than a centralized exchange. As the process involves on-chain transactions, for which mining is required. This incurs latency and transaction fees. Furthermore, privacy is not protected, as the blockchain is a public record for pseudonymous data which can be de-anonymized.
The first draft of a trust-less swap was published in bitcointalk forums by Sergio Demian Lerner in July 2012, who also sketched the first draft for DAG-based coins. He called it P2PTradeX, as it was the first peer-to-peer, also called wallet-to-wallet trade. The protocol, as described by Lerner, works as follows:
To unlock the contract and be able to “spend” the value, a proof of the transaction must be submitted. This proof is a branch of the blockchain, which shows that the transaction has taken place. The contract also specifies the following parameters:
• The chain branch size (amount of confirmations required to accept the payment).
• The hash of the block from where the branch should start (root block).
• The maximum number of blocks after the root block where the second payment can appear, to avoid sending money after the expiration date of the contract.
The security of the system relies on the premise that no party can build a blockchain branch longer and faster than the global branch. The proof cannot be computed in advance, as the size of the branch from the root block extends to blocks which haven’t been yet mined. In following algorithms, the proof was replaced from being a branch of the Blockchain to a secret revealed by the contract during the spending of the holding wallet.
Holding wallets are hash time-locked contracts, which are a combination of multi-signature addresses and time-locks. This leverages the scripting opcodes featured in Bitcoin, called SCRIPT, as well as most of its forks such as Litecoin. These contracts are the solution for on- chain atomic swaps for Bitcoin and most of its forks.
This left an imbalance and a vulnerability for Alice, as her transaction is irreversible while Bob’s commitment depends on future proof, and the burden of proof lies with Alice. A year later, in May 2013, Tier Nolan provided an account for “atomic” transactions, inspired by Bitcoin’s colored- coins, which he described as transactions that either happens in their entirety or they don’t, and counterparties never get into a situation where one side pays, and the other is reversed.
In the most simplified process, the steps for a swap are three:
To verify the proof, Nolan provided the Bitcoin opcodes necessary to verify that the second transaction is buried in a second chain, which is done by checking that a token is in the Merkle tree.
- Verify that the token matches the desired token
OP_DUP [target-token] OP_EQUALVERIFY
- Build up the merkle tree (fixed depth)
input: [true/false] [child1] [child2]
 OP_ROLL OP_IF OP_SWAP OP_ENDIF OP_CAT OP_HASH256
If true, then child1 and child2 are swapped, and then the hash is computed. The output is [parent]
When this step is finished, then the merkle root would be on the stack.
Scan the headers of the alt-chain; this computes the hash and checks that it meets the required difficulty.
The inputs are [nonce] [merkle-root] [previous-hash]
OP_CAT OP_CAT OP_HASH256 OP_DUP OP_LESS_THAN [target] OP_VERIFY 
The effect of these steps is that the contract is released if the token is buried in another chain at least a certain number of blocks deep. To spend, one has to provide the merkle path to the root and then the nonce and merkle root for the headers, which build on this one. Depending on the value of the transactions more confirming blocks would be required. However, this process has been described by Komodo as “ahead of its time.” The OP_CAT opcode for concatenating strings is currently disabled in Bitcoin, as most string and bitwise operations were disabled in 2010. A disabled opcode is essentially removed from the protocol, and there’s no way to re-enable, any client parsing them will abort and fail.
The precise algorithm was later reformulated by other people, including Mike Hearn, and specified in this way:
This is atomic (with timeout). If the process is halted, it can be reversed no matter when it is stopped.
Before step 1: Nothing has been broadcasted
Between steps 1 and 2: A can refund the transaction after 72 hours to get his money back
Between steps 2 and 3: B can refund the transactions after 24 hours, while A has 24 more hours to get his refund.
After step 3 the transaction is completed by the following two requirements:
— A must spend his new coin within 24 hours or B can claim the refund and keep his coins
— B must spend his new coin within 72 hours, or A can claim the refund and keep his coins
This approach can be used directly to trade between bitcoin-derived chains without specific support from the protocol.
After Nolan’s post in 2013, no one had written a successful mechanism for atomic swaps until one year later, when jl777 carried a test for swapping Litecoin with Dogecoin. jl777 later became the lead developer for Komodo, who developed BarterDEX, a platform which included order matching, trade clearing, and liquidity provision. Komodo introduced extra steps for the swap, which ensures incentives to proceed at each stage of the swap, as well as disincentives to deviate from it. Two of these are the addition of a spam-deterrent fee (a denial of service protection), and a deposit consisting of 112.5% of the traded amount. BarterDEX also records a merchant’s reputation score for both sides.
The constrains for separate UTXO are of the nature of the Bitcoin protocol. BarterDEX doesn’t provide a service to break up UTXO values into smaller ones so that the BarterDEX will look through the largest UTXO below the total amount offered, as well as the necessary fee. It is up to the client to manage the UTXOs through a greedy algorithm.
Decred successfully achieved an atomic swap with Litecoin and published the technical prerequisites. Both chains must support:
- branched transaction scripts
- the same hash algorithm in both chains’ transaction scripts
- signature checks in transaction scripts
- CheckLockTimeVerify or CheckSequenceVerify (“CLTV” and “CSV” for short) in transaction scripts
All forks of Bitcoin, such as Decred and Litecoin can trivially satisfy the first three conditions. Support for CLTV is supported if the forks have been tracking updates from Bitcoin. CLTV/CSV support is used to effect a refund, in the cases where either party does not complete part of the process.
BarterDEX achieved swaps with the Ethereum network, which bridged the gap between Bitcoin- protocol coins and Ethereum-based ERC-20 tokens, as well as ERC-721 collectibles. This was achieved by supporting coins that run on SPV (Simplified Payment Verification) Electrum servers, which also removes the need to download blockchain data. SPV exploits the Merkle tree structure to allow proof of inclusion without needing the full contents of the block.
Decred successfully achieved an atomic swap with Litecoin in September 2017, Litecoin’s Charlie Lee followed through three days later successfully swapping with Bitcoin. Following the success of Decred, and with the help of their codebase, altcoin.io also achieved swaps with an Ethereum ERC-20 token. This was big news for the community, topped up in March 2018 by Lightning Labs announcing the beta release of their mainnet for both Bitcoin and Litecoin, which opened up the gates for instantaneous and cheap off-chain atomic swaps. The website swapready.net provides a table of how close each network is to supporting atomic swap, either on-chain or with payment-channel network compatibility.
Decred’s algorithm is a standard atomic swap with two holding wallets, which reveal a secret upon spending, described as follows:
Off-chain atomic swaps through payment channels haven’t been explored in this study and might be the subject of a second part. As the technology matures, it will be interesting to see trust-less atomic swaps implemented through other mechanisms, which would allow the exchange of any digital asset, such as data or licenses. Of particular interest are the gateways to cryptocurrency: as more areas –such as the financial ecosystem– interlock with atomic transactions, the network would swell and absorb contingent fields into its cryptographic and decentralized ethos.
At BEAM, we are big believers in decentralization and the possibility of free exchange of cryptocurrencies between users. For that reason, Atomic Swaps with Bitcoin will be an integral part of our solution. This will be achieved by implementing contracts that support multi-signatures and time-locks, based on Decred’s peer-reviewed repository. Support for payment channels will be implemented soon after, as well as an integrated UI for a seamless user experience with our desktop and mobile wallets, and our block explorer. BEAM’s vision of privacy shouldn’t be marred by user’s dependence on centralized exchanges, which are a liability for security and privacy, which are two of our core values.
Article by Ronen Lahat. @ronenl
Learn more about our project on our website
Join our developer community: Gitter