Atomic Swaps In A Nutshell

As of July 2019, there are about 2,000 cryptocurrencies, however, there is no single exchange mechanism between different blockchains. In this article, we simplistically consider how one of the technologies of exchange without intermediaries is arranged - atomic swaps.
Enjoy reading!


Atomic Swaps: what is it and what does it eat with?

Atomic swaps are a series of transactions on both blockchains that allows you to exchange coins without the participation of a third party and trust in the second participant of the exchange. In essence, such a transaction is created, the output of which can be spent either in the presence of a certain key, or after a time.
Not all blockchains allow AtomicSwap to be implemented. There are two main requirements:

  • support for smart contracts (generator of this very "initial" transaction);
  • use of the same cryptomagy (hash function).

Smart contracts? No, not heard

Smart contracts — в широком смысле, "неприклонный" алгоритм, выполняющий действия при заведомо определенных условиях и никак иначе. В нашем случае смарт контракт можно расссматривать как большой черный ящик, которому скармливают адрес получателя, адрес отправителя, сумму отправки, время удержания денег и присваивают уникальный идентификаор (hash). На выходе получается желаемая транзакция с условиями.

Hash and his friends

Хеш-функция — еще один персонаж из сказки о высшей математике. Преобразовывает поток входных данных в другое значение. Одни и те же данные дают один и тот же результат. Как правило, входные данные это большое число, именуемое секреным ключем, а выходные — хешем. Преобразовать хеш обратно в секретный ключ — невозможно.

When everything goes smoothly

Consider the exchange between Alice (yes, yes, Alice is no longer the same) and Bob. Alice has Bitcoin (btc), Bob has Ether (eth). Both characters have addresses on both blockchains. Ex: big cryptocurrency signs symbolize blockchains.

Alice generates a key (a large number) and modestly does not tell anyone:

Based on the key, she considers the hash:

Creates a contract with a unique identifier equal to a hash:

Sends money to a contract. Now she cannot spend them a certain time (timelock):

Time is up, or timelock

Timelock — время, после которого создатель контракта сможет вернуть деньги, если отправит транзакцию определенного типа (назовем ее "refund"). Для этой транзакции не нужен секретный ключ. Другой пользователь может снять деньги на адресс указаного в контракте получателя(важно: не на свой), если отправит транзакцию другого типа(назовем ее redeem) с указанием секретного ключа.

В целом механизм обработки транзакций контрактом следующий:

if (transaction_type == "refund"  and sender == contract_creater and timelock < now()) {
} else if (transaction_type == "redeem"  and hash(secret_key) == contract_id) {

Alice reports the hash to Bob. Now he can audit (check) all fields of the contract: make sure the addresses are correct, the amount of the dispatch, the time the money was stored on the contract (the period during which Alice will not be able to withdraw it):

If everything is good, Bob creates a contract on the second blockchain similar to Alisinom (with the same identifier). The recipient and, possibly, the amount changes (if the rate is not 1 to 1).

Alice audits the contract:

If she triples everything, she creates a transaction on Ethereum that spends money on Bob's contract. The only way to do this is to provide a key. Now it is known:

Alice gets eth:

Bob looks at the key and creates a transaction that spends money on Alice’s contract using her key:

Success! Wolves are full, sheep are safe!

When the world is not perfect

However, sometimes something may go wrong. There are two places where the exchange can fail. To do this, there is a mechanism to return the money to their rightful owners.

Suppose Alice as a decent girl sent money for a contract, but after an audit, Bob changed his mind about parting with the airs:

Alice waits for the expiration of the timelock specified in the contract (for example, 48 hours) and returns the blood crickets:

Another story tells of the fickle Alice, who did not want to continue the atomic exchange after Bob created the contract. Alternative scenario: Alice has lost the key and cannot do this:

Bob waits for the time to block money (it is usually less than Alice’s, so that Alice does not withdraw Bob’s money at the last minute, and then doesn’t return hers; for example, 24 hours). Alice returns her money after her timelock.


Atomic exchanges are very convenient for point-to-point exchanges, bypassing exchanges and intermediaries. Participants undertake to pay only a commission for sending transactions.

Summing up, in the exchange between A and C on the blockchains B1 and B2, the following steps can be distinguished:

  1. initialization of the contract on B1 by participant A;
  2. listening to a contract on B1 by part C;
  3. initialization of the contract on B2 by participant C;
  4. Listening to a B2 contract by A;
  5. providing a key and withdrawing money to B2 by participant A;
  6. obtaining a key on B2 by participant C;
  7. withdrawal of money on B1 by party S.

The technology is new, but is already being actively introduced. Perhaps in the near future she will be able to replace the centralized and so ideologically alien for the blockchain exchange.

Also popular now: