the arwen trading protocols · the arwen trading protocols ethan heilman, sebastien lipmann, sharon...

21
The Arwen Trading Protocols * Ethan Heilman, Sebastien Lipmann, Sharon Goldberg Version 1.0, January 28, 2019 ABSTRACT The Arwen Trading Protocol is a layer-two blockhchain protocol that allows traders to securely trade cryptocur- rencies at a centralized exchange, without ceding cus- tody of their coins to the exchange. Before trading be- gins, traders deposit their coins in an on-blockchain es- crow, rather than in the exchange’s wallet. The agent of escrow is the blockchain itself. Each individual trade is backed by the coins locked in escrow. Each trade is fast, because it happens off-blockchain, and secure, because atomic swaps prevent even a hacked exchange from tak- ing custody of a trader’s coins. Arwen is designed to work even with the “lowest common denominator” of blockchains—namely Bitcoin-derived coins without Seg- Wit support. As a result, Arwen supports essentially all “Bitcoin-derived” coins, including BTC, LTC, BCH, ZEC as well as Ethereum and ERC-20 tokens. 1. INTRODUCTION The promise of blockchain-backed cryptocurrencies is the ability to transact in digital assets without rely- ing on a single trusted party. Blockchains therefore present a technical breakthrough that circumvents a long-standing result in cryptography: namely, that atomic swaps are impossible without the help of a trusted third party [26]. In an atomic swap, two parties that do not trust each other swap items, such that either (1) both Alice gets Bob’s item and Bob gets Alice’s item, OR (2) neither Bob nor Alice gets the other party’s item. In fact, atomic swaps of digital assets are possible when the blockchain acts as the trusted third party [7]. Fully realizing the promise of blockchain-backed cryp- tocurrencies demands that atomic swaps be brought into the mainstream. Today, we still live in a world where the vast majority of cryptocurrency trading re- quires traders to trust either each other, or a centralized cryptocurrency exchange. This seems absurd. Much of the value of a blockchain-backed cryptocurrency follows because it does not rely on a single trusted party. Why, then, is a single trusted party still required when trading cryptocurrency? The Arwen Trading Protocol seeks to deliver on this * Major contributions to the design of these protocols were made by James Dalessandro, Ezequiel Gomes Perez, Haydn Kennedy, Yuval Marcus, Chet Powers, Omar Sagga, Aleksander Skjolsvik and Scott Sigel. promise by bringing atomic swaps to the mainstream use case of cryptocurrency trading. With Arwen, traders can benefit from the liquidity at a centralized cryptocurrency- to-cryptocurrency exchange without trusting the exchange with custody of their coins. Instead, Arwen traders maintain custody of their cryptographic keys and their coins, and Arwen trades are backed by on-blockchain es- crows. Each coin’s native blockchain acts as the agent of escrow (i.e., the agent of escrow for bitcoins is the Bit- coin blockchain). Arwen trades are fast because they happen off blockchain, and secure, because they are atomic swaps. Arwen ensures that even a compromised exchange cannot steal a trader’s coins, and that a mali- cious user cannot grief or steal coins from the exchange. Arwen is designed to align incentives for the trad- ing use case, and to support trading instruments from traditional financial markets. Arwen is focused on the cross-blockchain trading use case, Arwen must support as many coins as possible. For this reason, the Arwen protocols are designed to work even with the “lowest common denominator” of Bitcoin-derived coins without SegWit [39] support. As a result, Arwen supports es- sentially all “Bitcoin-derived” coins, including Bitcoin (BTC), Litecoin (LTC), Bitcoin Cash (BCH), Zcash (ZEC)), etc.as well as Ethereum and ERC-20 tokens. 2. WHITHER ATOMIC SWAPS? There has been a flurry of activity that seeks to bring cross-blockchain atomic swaps to the mainstream. A cross-blockchain atomic swap allows one cryptocurrency (e.g., Bitcoin (BTC)) to be atomically swapped for an- other cryptocurrency (e.g., Bitcoin Cash (BCH)). Nev- ertheless, there are number of subtle issues that prevent known solutions from seeing widespread adoption for cryptocurrency trading. We now highlight several of these issues, and explain how Arwen overcomes them. 2.1 The promise of atomic swaps. Cross-blockchain atomic swaps seek to supplant to- day’s dominant form of cryptocurrency trading: cus- todial trading at centralized cryptocurrency exchanges. With custodial trading, when users wish to trade on a centralized exchange, they must first deposit their coins at the exchange; this is done using an on-blockchain transfer of coins from the user’s own wallet to the ex- change’s wallet. Trading occurs within the databases of the centralized exchange, and is not recorded on the 1

Upload: others

Post on 03-Feb-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

  • The Arwen Trading Protocols∗

    Ethan Heilman, Sebastien Lipmann, Sharon GoldbergVersion 1.0, January 28, 2019

    ABSTRACTThe Arwen Trading Protocol is a layer-two blockhchainprotocol that allows traders to securely trade cryptocur-rencies at a centralized exchange, without ceding cus-tody of their coins to the exchange. Before trading be-gins, traders deposit their coins in an on-blockchain es-crow, rather than in the exchange’s wallet. The agent ofescrow is the blockchain itself. Each individual trade isbacked by the coins locked in escrow. Each trade is fast,because it happens off-blockchain, and secure, becauseatomic swaps prevent even a hacked exchange from tak-ing custody of a trader’s coins. Arwen is designed towork even with the “lowest common denominator” ofblockchains—namely Bitcoin-derived coins without Seg-Wit support. As a result, Arwen supports essentiallyall “Bitcoin-derived” coins, including BTC, LTC, BCH,ZEC as well as Ethereum and ERC-20 tokens.

    1. INTRODUCTIONThe promise of blockchain-backed cryptocurrencies is

    the ability to transact in digital assets without rely-ing on a single trusted party. Blockchains thereforepresent a technical breakthrough that circumvents along-standing result in cryptography: namely, that atomicswaps are impossible without the help of a trusted thirdparty [26]. In an atomic swap, two parties that do nottrust each other swap items, such that either (1) bothAlice gets Bob’s item and Bob gets Alice’s item, OR (2)neither Bob nor Alice gets the other party’s item. Infact, atomic swaps of digital assets are possible whenthe blockchain acts as the trusted third party [7].

    Fully realizing the promise of blockchain-backed cryp-tocurrencies demands that atomic swaps be broughtinto the mainstream. Today, we still live in a worldwhere the vast majority of cryptocurrency trading re-quires traders to trust either each other, or a centralizedcryptocurrency exchange. This seems absurd. Much ofthe value of a blockchain-backed cryptocurrency followsbecause it does not rely on a single trusted party. Why,then, is a single trusted party still required when tradingcryptocurrency?

    The Arwen Trading Protocol seeks to deliver on this

    ∗Major contributions to the design of these protocolswere made by James Dalessandro, Ezequiel GomesPerez, Haydn Kennedy, Yuval Marcus, Chet Powers,Omar Sagga, Aleksander Skjolsvik and Scott Sigel.

    promise by bringing atomic swaps to the mainstreamuse case of cryptocurrency trading. With Arwen, traderscan benefit from the liquidity at a centralized cryptocurrency-to-cryptocurrency exchange without trusting the exchangewith custody of their coins. Instead, Arwen tradersmaintain custody of their cryptographic keys and theircoins, and Arwen trades are backed by on-blockchain es-crows. Each coin’s native blockchain acts as the agent ofescrow (i.e., the agent of escrow for bitcoins is the Bit-coin blockchain). Arwen trades are fast because theyhappen off blockchain, and secure, because they areatomic swaps. Arwen ensures that even a compromisedexchange cannot steal a trader’s coins, and that a mali-cious user cannot grief or steal coins from the exchange.

    Arwen is designed to align incentives for the trad-ing use case, and to support trading instruments fromtraditional financial markets. Arwen is focused on thecross-blockchain trading use case, Arwen must supportas many coins as possible. For this reason, the Arwenprotocols are designed to work even with the “lowestcommon denominator” of Bitcoin-derived coins withoutSegWit [39] support. As a result, Arwen supports es-sentially all “Bitcoin-derived” coins, including Bitcoin(BTC), Litecoin (LTC), Bitcoin Cash (BCH), Zcash (ZEC)),etc.as well as Ethereum and ERC-20 tokens.

    2. WHITHER ATOMIC SWAPS?There has been a flurry of activity that seeks to bring

    cross-blockchain atomic swaps to the mainstream. Across-blockchain atomic swap allows one cryptocurrency(e.g., Bitcoin (BTC)) to be atomically swapped for an-other cryptocurrency (e.g., Bitcoin Cash (BCH)). Nev-ertheless, there are number of subtle issues that preventknown solutions from seeing widespread adoption forcryptocurrency trading. We now highlight several ofthese issues, and explain how Arwen overcomes them.

    2.1 The promise of atomic swaps.Cross-blockchain atomic swaps seek to supplant to-

    day’s dominant form of cryptocurrency trading: cus-todial trading at centralized cryptocurrency exchanges.With custodial trading, when users wish to trade on acentralized exchange, they must first deposit their coinsat the exchange; this is done using an on-blockchaintransfer of coins from the user’s own wallet to the ex-change’s wallet. Trading occurs within the databasesof the centralized exchange, and is not recorded on the

    1

  • blockchain. Finally, once trading is complete, users re-gain custody of their coins by withdrawing their coinsfrom the exchange; that is, the exchange uses an on-blockchain transaction to transfer coins from the ex-change’s wallet back to the user’s wallet. Custodialtrading at a centralized exchange exposes the user toserious counterparty risk—if the exchange is compro-mised, the exchange may be unable to transfer coin backto the user’s wallet. This risk has been realized, start-ing with the hack of Mt. Gox [38] and affecting severalcentralized exchanges, e.g., [10, 30, 16, 8, 24, 12, 18,17, 31, 6, 40].

    With cross-blockchain atomic swaps, a user would nolonger need to trust a centralized exchange with custodyof her coins. Instead, the user could maintain custodyof her coins even while she trades, and the user’s coinswould not be at risk even if her counterparty becomesadversarial in the middle of a trade.

    In an atomic swap of 1 BTC for 20 BCH, it is cryp-tographically guaranteed that: (1) if the Alice trans-fers her 1 BTC to her counterparty, even a maliciouscounterparty cannot prevent Alice from claiming her 20BCH, and (2) if the counterparty transfers his 20 BCHto Alice, even a malicious Alice cannot prevent the coun-terparty from claiming his 1 BTC.

    Atomic swaps are an even stronger security paradigmthan “second send” protocols such as ShapeShift. Ina ShapeShift trade, Alice first transfers her 1 BTC toShapeShift’s wallet, and then ShapeShift transfers 20BCH to Alice’s wallet. This is not an atomic swap, be-cause an adversarial ShapeShift could always decide tokeep Alice’s 1 BTC without paying out her 20 BCH.Thus, while such “second send” protocols are sometimesreferred to as non-custodial, they in fact have brief win-dow of custody.

    2.2 The challenge of providing liquidity.Most decentralized exchange (DEX) protocols, includ-

    ing EtherDelta [1], 0x [37], and SparkSwap [4], are peer-to-peer trading systems, where each trade involves atransfer of funds directly from trader Alice’s wallet totrader Bob’s wallet. The peer-to-peer approach limitsliquidity, because it means that Alice can only tradewith traders that use that same peer-to-peer tradingsystem. If a system has too few users, it will not beable to provide good liquidity.

    Arwen eschews the peer-to-peer approach because, to-day, the best liquidity for cryptocurrency trading can befound at centralized exchanges. With Arwen, Alice canbenefit from the liquidity at a centralized exchange evenif she is the only Arwen user at the exchange. This fol-lows because Arwen trades only involve the movementof coins from the user’s wallet to the exchange’s wallet,without the involvement of any intermediaries. In otherwords, Arwen can be thought of as a secure settlementleg for the centralized exchange. Meanwhile, orders arepriced as usual, using the centralized exchange’s exist-ing orderbook.

    2.3 The pitfalls of on-blockchain protocols.Some of the best-known atomic swaps protocols are

    on-blockchain protocols, where the swap does not actu-

    ally execute until certain transactions are confirmed bythe blockchain.

    Ethereum DEX protocols. Ethereum DEX pro-tocols, including EtherDelta [1] and 0x [37], use theEthereum blockchain to trade one ERC-20 token for an-other ERC-20 token. Both EtherDelta and 0x uses thefollowing protocol framework. First, Alice broadcastsan order to the network without identifying a counter-party. Some counterparty Bob then sees Alice’s broad-cast, decides to trade with Alice, adds his informationto the order. Bob then posts the order to the Ethereumblockchain, where it is then executed by a smart con-tract on the Ethereum blockchain.

    The Bitcoin TierNolan Protocol. The TierNolanprotocol [34] is the original Bitcoin-compatible atomicswap; it can also be used for cross-blockchain atomicswaps for “Bitcoin-like” blockchains (e.g., BCH, LTC,ZEC, etc.). TierNolan uses Hashed Time-Locked Con-tract (HTLC) smart contracts as follows.

    Bob chooses a random solution x and computes a puz-zle y, where y = H(x) and H is a cryptographic hashfunction. Bob reveals the puzzle y to Alice and keepsthe solution x secret. Next, Alice locks up 1 BTC in anHTLC smart contract on the Bitcoin blockchain whichstipulates: “before time τA, the 1 BTC can be claimedby a transaction signed by Bob containing the solutionto puzzle y”. Bob similarly locks up 100 LTC on theLitecoin blockchain in an HTLC, which stipulates: “be-fore time τB, the 100 LTC can be claimed by a transac-tion signed by Alice containing the solution to the puzzley”. The atomic swap executes when Bob reveals the xor when he claims the 1 BTC by signing and posting atransaction to the Bitcoin blockchain that contains thesolution x. (For convenience, we will call this a solvetransaction.) Once this happens, Alice learns the so-lution x from the Bitcoin blockchain and can sign andpost a solve transaction to the Litecoin blockchain thatclaims Bob’s 100 LTC.

    Security follows from the cryptographic hash functionH (which ensures that no one can learn the solution xgiven only the puzzle y) and the fact that Bob mustreveal x on the blockchain in order to claim his coins.

    There are several issues with on-blockchain protocols.

    Speed. On-blockchain execution is slow, because it islimited by the speed at which the blockchain confirmsblocks. The expected time to confirm a single block isabout 10 minutes for Bitcoin (BTC) and Bitcoin Cash(BCH), 2.5 minutes for Litecoin (LTC) and 15 secondsfor Ethereum (ETH). Moreover, a single confirmation isoften insufficent to ensure that a transaction can not bereversed [13]; for instance, the cryptocurrency exchangeKraken waits 6 confirmations (60 minutes) for BTC and30 confirmations for ETH (6 minutes) [19]. Even a fewseconds of latency can be problematic when trading,especially given that cryptocurrency prices are famouslyvolatile. An atomic swap protocol that is compatiblewith high-frequency trading strategies must ensure thattrades execute instantly.

    Scalability. If each individual trade needs to be con-firmed on the blockchain, and a healthy trading ecosys-tem leads to many trades, then the blockchain itself

    2

  • will be clogged up with transactions resulting from eachindividual trade. Note that today’s custodial tradingecosystem avoids this problem, since the only transac-tions that need to be confirmed on the blockchain cor-respond to deposit and withdrawal of coins from theexchange. To avoid clogging the blockchain, an atomicswap protocol should require the blockchain to confirmonly the consolidated balance across multiple trades.

    Front-running. The EtherDelta and 0x protocolsrequire the trader to broadcast information about thetrade to all nodes on the blockchain before the trade isexecuted by the blockchain. This can lead to race con-ditions. Any blockchain node can learn the details ofAlice’s trade with Bob, and attempt to profit from it byfront-running Bob’s trade with its own trade [37]. Theseprotocols also allow a trader to cancel a order (e.g., dueto changing market conditions) by posting a cancella-tion request the blockchain. The on-blockchain natureof this cancellation is also subject to race conditions, be-cause a blockchain node Charlie could add himself as acounterparty to Alice’s order before the blockchain hasa chance to cancel it. These race conditions, however,are avoided by the TierNolan protocol because Alice andBob are required to identify each other counterpartiesat the moment that they lock up coins in the HTLCsmart contract.

    The Arwen Trading Protocol avoids speed and scal-ability pitfalls, because individual trades execute off-blockchain. Arwen also avoids the front-running prob-lem by building trading instruments that complementthe puzzle approach pioneered by TierNolan; see Sec-tion 2.6.

    2.4 Trading in a layer-two protocolBecause Arwen atomic swaps are executed entirely

    off-blockchain, Arwen falls into the same class of blockchainlayer-two protocols [25] as the Lightning Network [29].

    In a blockchain layer-two protocol, parties first lockup their coins in an on-blockchain smart contract. Thecoins locked in the smart contracts are then transferredbetween the parties via off-blockchain interactions. Fi-nally, the smart contract is closed on the blockchain, re-flecting the parties’ balance, consolidated across all theoff-blockchain transfers. Blockchain layer-two protocolsare fast, because coins are moved off-blockchain, andscalable, because only consolidated balances are postedto the blockchain.

    Arwen escrows. Arwen’s on-blockchain smart con-tracts are called escrows. Before trading begins, Al-ice deposits her coins in an on-blockchain user escrow,where the agent of escrow is the blockchain itself. Theexchange also deposits coins in an on-blockchain ex-change escrow, to prove to Alice that the exchange holdsenough coins to collateralize its trades. Each exchangeescrow is specific to a single user (i.e., Alice) and a sin-gle coin (e.g., Bitcoin Cash). Escrows are opened andclosed by confirming a transaction on the coin’s nativeblockchain. (So, to open a Bitcoin Cash exchange es-crow for Alice, the exchange confirms a transaction onthe Bitcoin Cash blockchain.)

    Multiple fast off-blockchain atomic-swap trades can

    be executed against a given pair of escrows. Thus, ifAlice wanted to trade 1 BTC for 20 BCH, Alice tradewould be backed by Alice’s user escrow for Bitcoin, andAlice’s exchange escrow for Bitcoin Cash. If Alice hasmultiple open user escrows with a given exchange (e.g.,a user escrow for BTC and a user escrow for ZEC), Alicecan pair them with any of her open exchange escrows(e.g., an exchange escrow for BCH and an exchangeescrow for ETH). This way, Alice can trade across mul-tiple currency pairs (BTC-BCH, BTC-ETH, ZEC-LTCand ZEC-ETH).

    To compensate the exchange for locking its coins inescrow, Alice pays an escrow fee each time the exchangefunds an exchange escrow for her. The exchange couldfund exchange escrows from its own inventory of coins.Alternatively, the exchange could fund exchange escrowsusing deposits provided by custodial users of the ex-change, and pay these custodial users a part of the es-crow fee. This creates a new interest-bearing featurethat the exchange can offer to its custodial users.

    Arwen vs. the Lightning Network. While Light-ning is designed for the use case of fast peer-to-peerBitcoin micropayments, Arwen is designed for the usecase of cryptocurrency trading. Arwen therefore avoidssome of the incentive issues that result when layer-twomicropayment systems (like Lightning) are repurposedto enable large value trades via atomic swaps.

    In the Lightning Network, Alice, Bob and any in-termediate nodes on the path first lock their coins inon-blockchain smart contract—one smart contract forevery consecutive pair of nodes on the path—and thenmove coins along the path via a series of off-blockchainatomic swaps. Arwen does not use a path of interme-diate nodes; instead, coins are transferred only betweenAlice and the exchange. This eliminates the risk thatan intermediate node will strategically disrupt a tradein order to manipulate market prices.

    Lightning only works with blockchains that have Seg-Wit support; such as only Bitcoin and Litecoin. Arwendoes not require SegWit support. This means that Ar-wen works with more “Bitcoin-derived” blockchains, in-cluding both coins with SegWit support and coins whichhave not deployed SegWit such as Bitcoin Cash, Zcash,and others. Technically speaking, supporting “Bitcoin-derived”blockchains that lack SegWit requires Arwen towithstand transaction malleability attacks, as discussedin Section 7. Arwen also has support for Ethereum andERC-20 tokens [36], as discussed in Section 6.

    2.5 Dealing with lockup griefing.Lockup griefing affects any protocol that requires users

    to lock coins in a smart contract. We describe the prob-lem, and explain how Arwen solves it via reputation anda novel escrow fee mechanism.

    Lockup griefing in TierNolan. In the TierNolanprotocol, Alice’s coins and Bob’s coins are locked intheir smart contracts until either (1) the trade executesor (2) the timelock on the smart contract expires attime τ . These timelocks τA, τB must at least as longas the time it takes to reliably confirm transactions onthe blockchain, i.e., several hours. The fact that coins

    3

  • must locked for a long time can creates “lock-up grief-ing” problem, where Alice locks her coin in her smartcontract, but Bob refuses to lock his own coins. Alice’scoins are thus pointlessly locked in the smart contractuntil it expires at time τA. (Alice could similarly launcha lockup-griefing attack on Bob.) TierNolan lacks amechanism to incentivize Alice and Bob to avoid lockupgriefing. This is especially problematic when Alice andBob are two random people that met over the Internet.

    Lockup griefing in Lightning. Lightning nodesearn fees for transfers of coins across their channel; how-ever, if no transfer of coins occurs, no fees will be earned,which can lead to lockup griefing. Worse yet, a node onthe Lightning path between Alice and Bob could alsodecide to strategically close its smart contract, breakingthe path from Alice to Bob. The makes it risky to useLightning for very high-value trades, where the incen-tive to disrupt a trade can be very significant. This riskis further exacerbated by the fact that Alice and Bobmay have no relationship with the intermediate nodeson the Lightning path.

    Using reputation to avoid lockup griefing. Ar-wen sidesteps the risk of lockup griefing because itsinteractions only involve the trader Alice and the ex-change, rather than a peer Bob or a path of intermediatenodes. The exchange has no incentive to launch a lockupgriefing attack against Alice; such an attack harms theexchange’s reputation, and prevents Alice from trading,which is the exchange’s main source of revenue.

    Using escrow fees to avoid lockup griefing. Theexchange, however, must protect itself from lockup grief-ing by a trader Alice, who might ask the exchange tolock up coins in exchange escrows willynilly, withoutactually executing any trades against those exchangeescrows. Arwen therefore requires Alice to lock up herown coins in a user escrow before she can ask the ex-change to lock up its own coin in an exchange escrow.Arwen also introduces a novel escrow fee mechanism (seeSection 3.5) that compensates the exchange for lockingup coins for Alice. Arwen’s escrow fees are an in-bandmechanism designed to avoid the introduction of out-of-band payments or of a superfluous fee token. The mech-anism generates revenue for the exchange from locked-up coins, while encouraging the user to close her ex-change escrows (and unlock the exchange’s coin) in atimely manner once she is done trading.

    2.6 Atomic swaps as trading instruments.The vision behind Arwen is to use atomic swaps in

    traditional trading instruments. For this reason, Ar-wen is specifically designed to avoid a misalignment ofincentives. We’ve already discussed how Arwen alignsincentives when opening and closing escrows; we nowfocus on the incentives involved in trading.

    To understand the importance of designing the incen-tive structure used in trading instruments, we returnagain to the TierNolan protocol.

    TierNolan as an American call option. TheTierNolan Protocol is asymmetric, because only Bobchooses and knows the secret solution x. This meansthat Bob has the unilateral ability to decide whether

    or not the atomic swap executes, by revealing x (ornot). Because the timelocks τA, τB on the smart con-tracts must at least as long as the time it takes to con-firm transactions on the blockchain, Bob has minutesor hours to decide whether market conditions justifythe execution of the swap (or not). This means that theTierNolan Protocol is actually an American call option:namely, Bob has the right, but not the obligation, tobuy 1 BTC from Alice at a strike price of 100 LTC, anytime before the expiry time τ . Typically, the asymme-try in an option is handled by requiring Bob to pay apremium to Alice before the option is set up. However,in the TierNolan Protocol, Bob gets the option for free,resulting in a misalignment of incentives.

    This American call option is implicit in many atomicswap protocols. For instance, it exists whenever theLightning Network is used for peer-to-peer trading be-tween Alice and Bob. By contrast, Arwen swaps areexplicitly designed to support different trading instru-ments. The first version of Arwen supports Request ForQuote (RFQ) trading instrument, while limit orders arenext on the Arwen roadmap.

    RFQ trading with Arwen. Arwen’s RFQ tradinginstrument is a off-blockchain atomic swap. In an RFQtrade, the exchange commits to a price, called the quote,before Alice decides whether or not to place an order forthe trade. (Request: “How many BCH can I buy for 2BTC?” Quote: “You can buy 40 BCH, quote open for 1second”) If Alice places the order before quote expires,Alice cannot back out of the trade and the exchange isexpected to execute a trade (of exactly 2 BTC for 40BTC). Importantly, RFQs are inherently asymmetric,because Alice gets to decide whether the trade happensor not. Therefore, to align incentives, the exchange’squote includes a spread around the current market price;this compensates the exchange for any volatility in mar-ket prices between the time the quote is given and thetime the trade is executed.

    Arwen RFQs also include an way out for the exchange.In times of strife, when the exchange is unable to executea trade against a quote it provided, the exchange doeshave the option to abort a trade. The abort is possiblebecause Arwen’s off-blockchain RFQ trading instrumentis built from HTLC smart contracts similar to those ofTierNolan. Specifically, the exchange chooses a secretsolution x to a puzzle y = H(x), and releases x in orderto execute the trade. To abort the trade, the exchangerefuses to release x. The aborted trade, however, isungraceful and costly because it requires the user andexchange to stop trading and close the escrows backingthe aborted trade. While no coins are lost, this suf-ficiently harmful to the exchange’s reputation that wewould expect an exchange to avoid aborting wheneverpossible. A full protocol description is in Section 5.

    Limit orders with Arwen. Arwen also supportsoff-blockchain fill-or-kill limit orders, where the user totells the exchange the lowest price at which she is willingto buy or sell coins. (i.e., Order: “I will sell 2 BTC ifI can buy at least 40 BCH”) A fill-or-kill order is onlyexecuted by the exchange if it can be completely filled(i.e., if all 40 BCH can be bought by the user). The user

    4

  • also has the ability to cancel the order. This instrumentis well aligned with the exchange’s incentives, because itcan execute the limit order instantly, once market pricesalign with the user’s order. It also aligns with the user’sincentives, because she can essentially “name her price”and easily adjust her price based on market conditions(by cancelling the order).

    2.7 White paper overview.The rest of this paper is organized as follows. In

    Section 3, we start with an overview of Arwen thatcovers Arwen escrows, escrow fees, and the basics ofoff-blockchain trading. We then provide a detailed de-scription of Arwen’s unidirectional RFQ protocol for“Bitcoin-derived” blockchains, including those that donot support SegWit. Section 7 explains the reasonswhy this protocol withstands transaction malleabilityattacks on blockchains like BCH that lack SegWit sup-port. We describe how to port the unidirection RFQprotocol to Ethereum and ERC-20 tokens in Section 6.Arwen’s bidirectional RFQ protocol is in Section 8 andbidirectional limit order protocol is in Section 9. Wecompare Arwen to other atomic swap and layer-two pro-tocols in Section 10.

    3. ARWEN OVERVIEWThe Arwen Trading Protocol is a blockchain-backed

    two-party cryptographic protocol between a user Al-ice and a centralized cryptocurrency exchange. Alicefirst locks her coins in an on-blockchain user escrow.Next, Alice asks the exchange to lock its coins in anon-blockchain exchange escrow. To compensates the ex-change for locking up its coins, Alice pays and escrow feeto the exchange using the coins Alice locked in her userescrow. Alice can now trade across a pair of escrows.Each individual trade is an off-blockchain atomic swap,using one of the Arwen trading instruments described inSections 5. Finally, the escrows are closed and the coinsare released to the wallets of the user and the exchange.

    3.1 The Arwen DaemonThe user executes the Arwen Trading Protocol using

    the Arwen Daemon. The Arwen Daemon is an open-source executable that the user downloads to her localmachine. The Arwen Daemon allows the user to engagein the Arwen Trading Protocol without trusting a third-party or a webserver, thus realizing the promise of non-custodial cryptocurrency trading. The Arwen Daemonperforms the cryptographic operations involved in theArwen Trading Protocol, posts and verifies transactionsfrom relevant blockchains, and stores the secret tradingkeys used to securely trade against the Arwen escrows.

    3.2 Opening on-blockchain escrows.Escrows are opened and closed by confirming a trans-

    action on the coin’s native blockchain. (Thus, the trans-action that opens an escrow for bitcoins is confirmed onthe Bitcoin blockchain.) Opening and closing escrowstakes the same amount of time it would take to depositor withdraw coins from a custodial centralized exchange.

    This exposition below assumes that Alice wishes to

    trade her bitcoins for some litecoins, as shown Figure 1.

    User escrow. Alice funds the on-blockchain user es-crow that is specific to this exchange. The user escrowlocks e.g., 5 BTC from the user’s wallet on the Bitcoinblockchain until some pre-agreed-upon expiry time twA.The initial balance in this escrow is 5 BTC owned by theuser, and 0 BTC owned by the exchange. While the es-crow is open, these coins are locked and cannot be usedfor anything other than cryptocurrency trades with theexchange. Once the escrow is closed, the balance of thecoins owned by the user are released and transferred tothe user’s wallet, and the balance of the coins ownedby the exchange are released and transferred to the ex-change’s wallet.

    Exchange escrow. The exchange funds the exchangeescrow that is specific to this user Alice. To open theexchange escrow, Alice pays the exchange an escrow fee,as described in Section 3.5. The exchange escrow locks500 LTC from the exchange’s wallet on the Litecoinblockchain until some pre-agreed-upon expiry time tw .The locked coins cannot be used for anything other thancryptocurrency trades with this specific user. The ini-tial balance in this escrow is 0 LTC owned by the user,and 500 LTC owned by the exchange. Once the escrowis closed, the balance of the coins owned by the Aliceare released and transferred to Alice’s wallet, and thebalance of the coins owned by the exchange are releasedand transferred to the exchange’s wallet.

    Pairing. Alice can execute multiple fast off-blockchaintrades against any (user escrow, exchange escrow) pair.If Alice has multiple open user escrows with a givenexchange, she can pair them with any of her open ex-change escrows with that exchange. In the example ofFigure 1, initially pairs her 5 BTC user escrow and her500 LTC exchange escrow, allowing her to sell up to 5BTC and buy up to 500 LTC.

    Escrow expiry times. Escrows come with an expirytime that protect each party against a malicious coun-terparty. As long as the exchange is not compromised,the user can close her escrows early, before they expire.Escrow expiry times can vary, but must be longer thanthe time it takes to reliably confirm a transaction onblockchain. Thus, expiry times are least several hoursafter the escrow has been opened.

    Escrow smart contracts. The Arwen escrow isa timelocked two-of-two multisig smart contract thatstipulates the following:

    “coin may be released from escrow via a trans-action that is signed by both the user’s ephemeralkey and the exchange’s ephemeral key, ORafter time tw , the party that funded that es-crow can unilaterally withdraw coins fromthe escrow by signing a transaction usingtheir ephemeral key.”

    Each ephemeral key is chosen and used for this specificescrow only. This way, even if a trading key is compro-mised, there is no risk to the coins that remain in theuser wallet or the exchange wallet. The user’s ephemeraltrading key is stored in the Arwen Daemon on the user’slocal machine.

    5

  • Request: Sell 1 BTC for some LTC?

    Quote: 1 BTC for 100 LTC.

    Confirmed!

    Order! 1 BTC for 100 LTC.

    CENTRALIZED EXCHANGETRADER

    First trade(off blockchain!)

    User EscrowUser: 5 BTC Exchange: 0 BTC

    Exchange EscrowUser: 0 LTC Exchange: 500 LTC

    On-blockchain escrow

    transactions

    BTC CashOutUser: 2 BTC Exchange: 3 BTC

    LTC CashOut:User: 300 LTC Exchange: 200 LTC

    These transactions are posted to the

    blockchain only when the escrows

    are closed

    Request: Sell 2 BTC for some LTC?

    Quote: 2 BTC for 200 LTC.

    Confirmed!

    Order! 2 BTC for 200 LTC.Second trade

    (off blockchain!)

    Figure 1: Arwen Trading Protocol for a two RFQ trades between the user and exchange.

    Bitcoin script implementation. When Arwen es-crows lock coins on blockchains that support the BitcoinScript language (e.g., BTC, BCH, LTC, ZEC, etc.), theArwen escrow smart contract operates is quite simple,comprising only 16 opcodes. (Bitcoin Script is a highlyrestricted language, reminiscent of Assembly language.)

    User escrows and exchange escrows are transactionsconfirmed on their native blockchain. The reader mighttherefore wonder if a third party can inform their owntrading strategies by scanning the blockchain to find Ar-wen escrows. Fortunately, with Bitcoin-fork blockchains,a third party can only observe that a certain amountof coins has been transferred into a smart contract ad-dress; the amount of coins is visible on the blockchain,but the details of the smart contract are completely un-known to the third party. This follows because openingan escrow amounts to funding a P2SH-type address ona “Bitcoin-fork” blockchain. A P2SH address is just acryptographic hash of the smart contract itself. No de-tails of the smart contract are apparent from this hash,other than the fact that it is a smart contract. More-over, the P2SH-type address is commonly used by othersystems, not just by the Arwen Trading Protocol.

    Ethereum smart contract implementation. TheEthereum and ERC-20 implementation of Arwen usesan escrow smart contract that mimics the UTXO trans-action paradigm that is used on Bitcoin. Once thesmart contract is funded, it enters the OPEN state,and remains in the OPEN state until either a trans-action is posted that is (1) doubly-signed by the users’sephemeral key and the exchange’s ephemeral key (thisis 2-of-2 multisig condition of the Arwen escrow), or (2)the escrow expires after time tw , and the party thatfunded the escrow posts a signed message that unlocksthe coins in the escrows (this is the timelock conditionof the Arwen escrow). See the description in Section 6.

    3.3 Off-blockchain trading via atomic swaps.

    Arwen supports several off-blockchain trading instru-ments, backed by the user escrow and exchange escrowscontracts. These trading instruments and their accom-panying cryptographic protocols are described in Sec-tions 5,6,9. Arwen trades are fast, because they hap-pen off-blockchain. To trade, the user’s Arwen Daemonand the exchange send cryptographic messages betweenthemselves. Because no other party can see these mes-sages, the trade is protected from front-running, grief-ing, and other strategic manipulations.

    Each trade is an atomic swap, and cannot be reversedonce it executes. If a trade successfully executes, it re-sults in a pair of off-blockchain transactions that reflectthe balance of coins in the escrows after the trade. Thesetransactions protect the user and the exchange in casethe other party becomes uncooperative (i.e., maliciousor unresponsive), by allowing each party to unilaterallyclose the escrows without the help of the other party.

    3.4 Closing on-blockchain escrows.Once an escrow is closed, the balance of coins owned

    by the user is released into the user’s wallet, and the bal-ance of coins owned by exchange is released into the ex-change’s wallet. For instance, consider Figure 1, where(1) the user escrow was initially funded with 5 BTC,and (2) the exchange escrow was initially funded with500 LTC, (3) Alice performed two RFQ trades selling 3BTC in order to buy 300 LTC, and then (4) decided toclose both the user escrow and exchange escrow. Whenthe user escrow is closed, 2 BTC will be transferred intoAlice’s wallet, and 3 BTC will be transferred into theexchange’s wallet. When the exchange escrow closes,300 LTC will be transferred to the user’s wallet, and200 LTC will be transferred to the exchange’s wallet.

    Cooperative close. In typical situations, whereneither the exchange nor the user is malicious or com-promised, then the user escrow and the exchange escrowcan be closed at any time, even before they expire. Each

    6

  • escrow is closed via a cooperative exchange of messagesbetween the user and exchange. The output of this co-operation is a single cashout transaction, posted to theblockchain, that reflects the balance of the escrow andis doubly-signed by (1) the user’s trading key and (2)the exchange’s trade key.

    Uncooperative close. The Arwen Trading Proto-col is secure atomic swap protocol because it allows theuser to unilaterally recover from the two unlikely situa-tions which may occur if the exchange is compromisedor unresponsive:

    The exchange refuse to close an open escrow. In thiscase, the user can unilaterally close the escrow.

    The exchange aborts a trade. An escrow is frozenwhenever an exchange improperly aborts a trade againstthat escrow. A frozen escrow cannot be used for trad-ing and must be closed. If the exchange refuses to co-operatively close a frozen escrow, Alice can unilaterallyrecover coins from the frozen escrow by connecting herArwen Daemon to the Internet during a specific coin-recovery time period. The Arwen Daemon notifies theuser about the coin recovery time period at the momentthe Arwen Daemon detects that the exchange improp-erly aborted a trade.

    Similarly, Arwen allows the exchange to unilaterallyclose escrows when the user is malicious or unrespon-sive.These unilateral recovery procedures are the maintechnical contribution of the Arwen protocols, and arespecific to each of Arwen’s trading instruments. Seee.g., Sections 5.5,5.6,8.48.5 for the procedures used inArwen’s unidirectional RFQ trading protocol.

    3.5 Arwen’s escrow fee mechanism.When an exchange funds an exchange escrow for a

    specific user Alice (e.g., the 500 LTC exchange escrow inFigure 1), the exchange is locking coins in an escrow thatcan only be used by Alice. These coins can come out ofthe exchange’s own inventory. Alternatively, they couldbe coins deposited by custodial users that the exchangeuses to fund escrows, in exchange for earning intereston those deposits.

    For this reason, when Alice requests an exchange es-crow, she first pays an escrow fee to compensate theexchange for locking up its funds. Arwen’s escrow feesare an in-band mechanism that avoids the introductionof out-of-band payments or of a superfluous fee token.

    The escrow fee mechanism. The escrow fee is pro-portional to the amount of coin locked in the exchangeescrow, and to the expiry time of the exchange escrow.Alice pays the escrow fee upfront, before she opens theexchange escrow. Alice receives a rebate of a portion ofthe escrow fee if she closes the exchange escrow early,before it expires.

    Alice pays the upfront escrow fee via a fast off-blockchaintransfer out of the coins locked in one of her user es-crows. Alice receives the rebate out of the exchangeescrow, once that exchange escrow is closed.

    Paying escrow fees. This is best illustrated with anexample. Consider the situation in Figure 1, and sup-pose that Alice has an open user escrow with a balance

    of 5 BTC owned by Alice. Alice then asks the exchangeto open a 500 LTC exchange escrow for her that ex-pires two days later, and indicates that she can pay theescrow fee out of her BTC user escrow.

    Suppose the escrow fee for the requested exchangeescrow is 1 LTC/day and Alice decides to pay the up-front escrow fee using her BTC user escrow. First, theexchange performs a currency conversion of the escrowfee, converting it from 2 LTC into 0.02 BTC. Next, theexchange quotes an escrow fee of 0.02 BTC to Alice. IfAlice accepts this fee, Alice sends the exchange a 0.02BTC off-blockchain payment from her user escrow thatalters the balance in the user escrow so that the ex-change owns 0.02 additional BTC and Alice owns 4.98BTC. Once the exchange receives this payment, the ex-change funds an exchange escrow for Alice for 500 LTC.

    Escrow fee rebate. Now suppose that Alice hasmade trades that alter the balance in the exchange es-crow so that 300 LTC is owned by Alice and 200 LTC isowned by the exchange. Alice then decides to closes herexchange escrow one day early, so she is entitled to aescrow-fee rebate of 1 LTC. Alice is paid the rebate outof the closed exchange escrow. Thus, the exchange es-crow is closed with a balance of 301 LTC sent to Alice’swallet and 199 LTC sent to the exchange’s wallet.

    4. SECURITY MODEL.Arwen assumes that the exchange is almost always on-

    line, while the user is usually not online. Atomic swapsecurity for users of Arwen follows from five assump-tions.

    1. The traded coins’ native blockchain is secure. Thatis, when trading bitcoins we assume that the Bit-coin blockchain is secure.

    2. The user’s Arwen Daemon has not been compro-mised. (Note that the Arwen Daemon is open-source and therefore can be audited.)

    3. The user correctly deposits coins in her user es-crow. (This is exact same assumption on user be-havior that is made whenever a user deposits coinsat a cryptocurrency exchange.)

    4. The user correctly informs the Arwen Daemon ofthe wallet addresses where she wants her coinstransferred to upon closing each escrow. (Thisis exact same assumption on user behavior thatis made whenever a user withdraws coins from acryptocurrency exchange.)

    5. The user remembers to come online in order to re-cover coins from frozen escrows during their coin-recovery time period, and to close escrows in a“timely manner”. Each Arwen protocol has a spe-cific definition of what it means to close escrowsin “timely manner”. (The users coins are at riskonly if the exchange is compromised or malicious,and the user forgets to close escrows in a timelymanner or to recover coins from frozen escrows.)

    7

  • These assumptions only related to the blockchain (as-sumption 1), the user’s computing environment (assump-tion 2) and the user’s behavior (assumption 3-5). Secu-rity for the user makes no assumptions about the se-curity or correctness of the cryptocurrency exchange orany other party.

    Atomic-swap security for the exchange analogouslyfollows from five analogous assumptions, and analogouslymakes no assumptions about the security or correctnessof the user or any other party.

    5. UNIDIRECTIONAL RFQSThe following protocol is unidirectional [32] because

    it only allows Alice to sell coins from her user escrow,and buy coins from her exchange escrow. Arwen’s morecomplex bidirectional RFQ protocol is described in Sec-tion 8. This unidirectional protocol is for“Bitcoin-derived”blockchains, including those without SegWit, and thuswithstands transaction malleability attacks for the rea-sons explained in Section 7. Section 6 explains how toport this protocol to Ethereum and ERC-20 tokens.

    Each off-blockchain RFQ trade is backed by a userescrow (with expiry time twA) and an exchange escrow(with expiry time twB). The protocol for opening theseescrows is in Section 3.2. Both escrows must be openduring a trade (rather than expired, frozen, or closed).

    Each new trade generates a pair of timelocked puz-zle transactions for puzzle y, along with correspond-ing solution x where x is chosen by the exchange andy = H(x). One puzzle transaction spends the outputof the user escrow and has timelock τA, and the otherspends the output of the exchange escrow and has time-lock τB. Each pair of puzzle transactions reflect thenew balance of coins in the escrows after the trade, and“overwrites” the pair of transactions generated by theprevious trade. The puzzle transactions and solution xand allow each party to unilaterally close escrows withthe correct balance of coins, even if the other party be-comes malicious.

    5.1 Security assumptions.Timelocks. The security of this protocol follows be-cause we set the timelocks to be

    τA = twA τB = max(twB, τA + 2%) (1)

    where % is the time required for transaction be reliablyconfirmed on the blockchain. Importantly, notice thatthere is no relationship between the escrow expiry times(twA, twB), which means we can pair any user escrowand exchange escrow, regardless of their expiry time.

    Closing escrows in a timely manner. To with-stand attacks by a compromised or malicious exchange:

    The user must close her exchange escrow be-fore it expires at time twB.

    If the user forgets to do this, an honest exchange willclose the escrow on the user’s behalf, but a maliciousexchange may be able to steal coins from the escrow.This requirement is for exchange escrows only; there isno requirement that the user close her user escrows in

    a timely manner. Similarly, to withstand attacks by acompromised or malicious user:

    The exchange must close its user escrow be-fore it expires at time twA.

    Finally, the time period in which the user can unilater-ally recover coins from frozen escrows is (twA, τB).

    5.2 Off-blockchain RFQ trades.This exposition below follows Figure 1. We suppose

    that the user Alice wants to do a trade, selling 2 bitcoinsfor 200 litecoins. We also assume that, in all previoussuccessfully-completed trades, Alice has sold at total 1BTC from the user escrow and 100 LTC from the ex-change escrow that are backing the current trade. EachRFQ is an off-blockchain four-message protocol com-prising the following four messages.

    Request. Alice requests a quote to sell 2 BTC inorder to buy LTC.

    Quote. The exchange responds with the quote—“2BTC can be sold for 200 LTC, open for time δ”. Theexchange has now committed to executing the trade,should Alice choose to place an order before the quoteexpires at time δ. To align incentives, the quote reflectsthe current market price at the exchange, plus an addi-tional spread that compensates the exchange for pricefluctuations between the moment the quote is provided,and the moment the trade is executed.

    To commit to the quote, the exchange chooses a se-cret solution x and computes a puzzle y = H(x). Theexchange sends Alice the following Litecoin puzzle trans-action for the Litecoin blockchain. The puzzle transac-tion (1) is signed by the exchange’s ephemeral key, (2)spends the output of the exchange escrow, and (3) re-flects the current balance in the LTC exchange escrow,except that 200 LTC is locked in an HTLC smart con-tract stipulating that

    ”The coins may only be unlocked via a trans-action that contains the solution to puzzle yand is signed by the user’s ephemeral key,ORafter time τB, the exchange can unilaterallyunlock coins from the escrow by signing atransaction using its ephemeral key.”

    In other words, the puzzle transaction sends 100 LTCto Alice’s wallet, locks 200 LTC in an HTLC smart con-tract under puzzle y, and sends the remaining 200 LTCto the exchange.

    (Notice that Alice could sign this puzzle transactionand post it to the Litecoin blockchain. This would re-lease all coins locked in the user escrow, except those 200LTC locked under the puzzle y. However, Alice does notsign or post anything to the Litecoin blockchain untilshe is ready to close her exchange escrow.)

    Order. If the user decides not to place the order,then the escrows remain open and can be used for othertrades. (This follows because only the exchange knowsthe secret solution x. Without x, the Litecoin puzzletransaction is useless to Alice. Nevertheless, if Alice

    8

  • does decide to post the puzzle solution to the Lite-coin blockchain, the exchange can reclaim the 200 LTClocked under the puzzle after its timelock expires at τB.)

    To place an order, Alice signs and sends the exchangea new Bitcoin puzzle transaction using the same puzzley chosen by the exchange. The puzzle transaction (1) issigned by Alice’s ephemeral trading key, (2) spends theoutput of the user escrow, and (3) reflects the currentbalance in the user escrow, except that 2 BTC is lockedin an HTLC smart contract stipulating that

    ”The coins may only be withdrawn via atransaction that contains the solution to puz-zle y and is signed by the exchange’s ephemeralkey, ORafter time τA, the user can unilaterally with-draw coins from the escrow by signing a trans-action using its ephemeral key.”

    At this point in the protocol, Alice cannot abort theorder, because the exchange can now unilaterally decidewhether or not the trade executes. (This follows becausethe exchange can use this puzzle transaction, and thesolution x to unilaterally close the user escrow as if thistrade was executed.)

    Execute. If the user placed the order before timeδ, then the exchange is expected to execute the tradeby sending the solution x to the user. This executesthe atomic swap, because now both the user and theexchange hold transactions that allow them to unilater-ally close their escrows, reflecting the new balance afterthe trade. (Specifically, the user can unilaterally closethe exchange escrow, and the exchange can unilaterallyclose the user escrow.) However, in most situations theuser will prefer to keep trading against her open es-crows. In this case, no transactions are posted to theblockchain, and the user escrow and the exchange es-crows remain open.

    What if the exchange does not properly execute thetrade by releasing x? In this case, Alice will freezethe user escrow and exchange escrow that backed theaborted trade and launch a procedure for recovering hercoins, as described in Section 5.6.

    5.3 The magic of unidirectionality.The security of our protocol follows, in part, from

    an observation first made by Spilman [32]. This is aunidirectional protocol, which means that the user canonly use the exchange escrow to buy coins from the ex-change. Thus, each subsequent trade changes the bal-ance of coins in the exchange escrow such that the userholds more litecoins and the exchange holds less lite-coins. For this reason, the user will always prefer to postthe transactions resulting from the most recent trade tothe Litecoin blockchain. This is why the Litecoin trans-actions resulting from a new trade will “overwrite” theLitecoin transactions resulting from the previous trade.

    In other words, the user is incentivized to close theexchange escrow before it expires using the transactionsresulting from the most recent trade. If the user goesrogue and closes the exchange escrow using transactionsfrom a prior trade, she only hurts herself (because she

    will have fewer coins), not the exchange (because theexchange will have more coins)!

    Similar reasoning explains why the exchange prefersto close the user escrow before it expires using the trans-actions from the most recent trade.

    Paying escrow fees. The magic of unidirectionalityalso makes it easy for the Alice to pay escrow fees out ofher user escrow. Suppose that, after the second trade inFigure 1, Alice wishes to pay an 0.02 BTC escrow fee inorder to open a new exchange escrow. To do this, Alicesigns and sends the exchange a cashout transaction thatreflects the current balance of the user escrow, with anadditional 0.02 BTC allocated to the exchange. Specif-ically, the cashout transaction (1) spends the output ofthe user escrow, (2) sends 3.02 BTC to the exchange’swallet, and 1.98 BTC to the user’s wallet. The sameunidirectional argument means that the exchange is in-centivized to have this cashout transaction “overwrite”the puzzle transaction received from the previous trade.This cashout transaction could then be signed by theexchange and posted to the blockchain if the exchangeneeds to unilaterally close the user escrow.

    5.4 Closing escrows.Cooperative close. If neither the user nor the ex-change is unresponsive or malicious, escrows are closedprior to their expiry using the cooperative close proce-dure outlined in Section 3.4. Specifically, the user sendsthe exchange a signed cashout transaction reflecting thefinal balance in the escrow. The exchange then signsthat transaction and posts it to the blockchain. For ex-ample, to cooperatively close the user escrow after thetrade described above, the cashout transaction would(1) spend the output of the user escrow, (2) send 3 BTCto the exchange’s wallet, and 2 BTC to the user’s wallet,and (3) be signed by both the user and the exchange.

    Incentives for a cooperative close. Coopera-tively closing an escrow is in the interest of both parties,because it allows them to reduce mining fees by clos-ing their escrows using a one transaction, rather thantwo (i.e., the puzzle transaction and a solve transac-tion that contain the solution x to puzzle y). Moreover,because the puzzle transaction is generated in advance,it must include a highly conservative blockchain min-ing fee. This is necessary to cope with unpredictablefluctuations in mining fees between the time the puz-zle transaction was created during the RFQ trade, andthe time it might get posted to the blockchain to uni-laterally close the escrow. A cooperative close of theexchange escrow also allows the user to earn a rebateon her escrow fees, as described in Section 3.5.

    Unilateral close. However, if one of the partiesrefuses (or forgets) to engage in a cooperative close, ourprotocol ensures that their counterparty can unilater-ally close the escrows and obtain at least those coinsthey rightfully hold according to the final balance inthe escrow. (In fact, there are cases where a unilat-eral close allows the counterparty to obtain additionalcoins beyond those coins that they rightfully hold ac-cording to the final balance in the escrow.) Each party’sprocedure for closing an open escrows when the coun-

    9

  • user escrow

    5 BTC

    puzzle transaction y

    2 BTC 1 BTC 2 BTC

    solvex where y = H(x)

    2 BTC

    puzzle refund

    2 BTC

    cashout

    2 BTC 3 BTC

    Uwallet

    Ewallet

    (Etrade Ʌ Utrade) or (Urefund Ʌ twA)

    (x Ʌ Epuzz) or (Urefund Ʌ τA)

    Uwallet Ewallet

    Utrade Etrade

    Epuzz

    Uwallet

    Urefund

    Utrade Etrade

    Ewallet

    refund

    2 BTC 3 BTCUwallet Ewallet

    Urefund

    Uwallet

    Figure 2: Diagram of transactions pointing to the user escrow for the unidirectional RFQ protocolof Section 5. Per Figure 1, we suppose that the user has already received 1 BTC and is engagingin a trade for an additional 2 BTC. Transactions in color are only posted to the blockchain if aparty becomes uncooperative. The ⊕ symbol is an XOR: only one of the transactions from the ⊕can be posted to the blockchain. The lock symbol represents a signature. The transactions shownin green and blue are posted by the exchange to unilaterally close the escrow if the user becomesuncooperative, or forgets to close the escrow before time twA. The transaction in purple is used bythe user to unilaterally close the user escrow after it expires at time twA; here we depict the casewhere all trades properly complete but the exchange did not cooperate to close the escrow, so theuser benevolently transfers 2 BTC to the exchange’s wallet, rather than “stealing” these BTC forherself. The transaction in magenta is used by the user to unilaterally release coins locked in puzzletransaction, after the puzzle expiry time of τA; this transaction is only used when the exchange postsa puzzle transaction but fails to post the corresponding solve transaction.

    exchange escrow

    500 LTC

    puzzle transaction y

    200 LTC 100 LTC 200 LTC

    solvex where y = H(x)

    200 LTC

    puzzle refund

    200 LTC

    cashout

    200 LTC 300 LTC

    Ewallet

    Uwallet

    (Etrade Ʌ Utrade) or (Erefund Ʌ twB)

    (x Ʌ Upuzz) or (Urefund Ʌ τB)

    Ewallet Uwallet

    Etrade Utrade

    Upuzz

    Ewallet

    Erefund

    Etrade Utrade

    Uwallet

    Ewallet

    refund

    200 LTC 300 LTCEwallet Uwallet

    Erefund

    Figure 3: Diagram of transactions pointing to the exchange escrow for the unidirectional RFQ protocolof Section 5. Per Figure 1, we suppose that the user has already received 100 LTC and is engagingin a trade for an additional 200 LTC. Transactions in color are only posted to the blockchain if aparty becomes uncooperative. The transactions shown in green and blue are posted by the user tounilaterally close the escrow if the exchange becomes uncooperative. The transaction in purple isused by the exchange to unilaterally close the exchange escrow after it expires at time twB; here wedepict the case where all trades properly complete but the user forgets to close the exchange escrowbefore it expired, so the exchange benevolently transfers 200 LTC to the user’s wallet, rather than“stealing” these LTC for itself. The transaction in magenta is used by the exchange to unilaterallyrelease coins locked in puzzle transaction, after the puzzle expiry time of τB; this transaction is onlyused when the user posts a puzzle transaction but fails to post the corresponding solve transaction.

    10

  • terparty is malicious or uncooperative is in Section 5.5.The user’s procedure for recovering coins from a frozenescrow is in Section 5.6.)

    5.5 Unilaterally closing an open escrowWhat happens if the user and exchange fail to co-

    operatively close an escrow before it expires? Here weconsider only the case where the escrow is open, i.e.,where all trades against that escrow have properly com-pleted. Recovery from an escrow that is frozen due toan aborted trade is described in Section 5.6. There arefour relevant cases.

    5.5.1 Exchange refuses to close exchange escrow.In this case, Alice’s Arwen Daemon can unilaterally

    close the exchange escrow before it expires at time twB,by signing and posting the puzzle transaction and thensigning and posting the solve transaction that resultedfrom the latest trade. (See Figure 3.) This releases coinsto Alice’s wallet and the exchange’s wallet, according tothe balance in the escrow after the last completed trade.

    Alice’s coins are safe if she closes the exchangeescrow before time twB. This follows because onlyAlice can close the exchange escrow before twB, whichprotects her from race conditions with a malicious ex-change or any other party. To see why, recall fromSection 3.2 that, to close the exchange escrow beforeit expires, we require a transaction doubly-signed byboth the user and the exchange. The RFQ protocolabove ensures that only Alice has such a transaction—the Quote message provides the user with a puzzle trans-action, signed by the exchange, that spends the outputof the exchange escrow. Alice can unilaterally sign thispuzzle transaction to create the required doubly-signedtransaction, and unilaterally post this transaction to theLitecoin blockchain. Meanwhile, the exchange does notthe ability to create such a doubly-signed transaction,because Alice never sends the exchange a signed trans-action that spends the output of the exchange escrow.

    Once the puzzle transaction is confirmed by the blockchain,Alice can use the corresponding solution x to sign andpost a solve transaction to he blockchain, releasing thecoins locked in the HTLC smart contract in the puzzletransaction to Alice’s wallet. Also, Alice is protectedfrom race conditions because only Alice can spend thecoins locked in the HTLC before twB. This follows be-cause equation (1) is such that the HTLC’s timelock τBexpires after time twB .

    5.5.2 User forgets to close exchange escrow.What happens if Alice forgets to close her exchange

    escrow before it expires? Alice’s coins are at risk onlyif the exchange becomes malicious.

    This follows because an exchange can unilaterally closean exchange escrow after it expires at time twB using arefund transaction (see Figure 3). The refund transac-tion (1) is signed by the exchange, and (2) spends theoutput of the exchange escrows. An honest exchangewill (3) form the refund transaction so that it releasescoins to Alice’s wallet and the exchange’s wallet accord-ing to the final balance of in the escrow. However, a

    malicious exchange could instead have the refund trans-action release all coins to the exchange’s wallet; this iswhy we say the user’s coin are risk if she forgets to closeher exchange escrow before it expires.

    Meanwhile, an malicious user Alice cannot steal theexchange’s coin even if the exchange decides to close theexchange escrow significantly after time twB. This fol-lows because even if Alice decides to race the exchange’srefund transaction, Alice can only attempt to close theescrow with a puzzle transaction that either (1) reflectsthe final balance of in the escrow (i.e., at the same bal-ance at which the honest exchange is attempting to closethe user escrow) OR (2) reflects the balance of in theescrow after any earlier completed trade (i.e., a balancewhere the exchange holds more coins than it does in thefinal balance of the escrow, which is worse for Alice andbetter for the exchange!)

    5.5.3 User forgets to close user escrow.Suppose the user forgets to cooperatively close a user

    escrow before it expires at time twA. Here, the ex-change must unilaterally close the user escrow beforetime twA. To do this, the exchange signs and posts thepuzzle transaction, and then signs and posts the solvetransaction, both of which resulted from the latest com-pleted trade (see Figure 2). (If the final off-blockchaintransfer against this escrow was due to Alice paying anescrow fee, then the exchange would instead close theescrow using the cashout transaction used to pay theescrow fee; see Section 5.3.) This releases coins to Al-ice’s wallet and the exchange’s wallet, according to thefinal balance in the escrow. The exchange must do thisbefore time twA in order to avoid race conditions witha malicious Alice. This follows from reasons analogousto those given in Section 5.5.1.

    5.5.4 Exchange refuses to close user escrow.If the exchange refuses to cooperatively close a user

    escrow, the user’s coins are not at risk. The user justneeds to wait until the user escrow expires, at whichpoint her Arwen Daemon will automatically and unilat-erally close the user escrow using a refund transaction(see Figure 2). This follows because the user escrowsmart contract allows the user to unilaterally unlock thecoins in the user escrow after time twA. Alice is in norush to unilaterally close this user escrow—her ArwenDaemon can do this at any time after the user escrowexpires at time twA. This follows for reasons analogousto those in Section 5.5.2.

    5.6 Recovering coins from frozen escrows.Suppose that during the last trade, the user placed

    an order against a quote provided by the exchange, butthe exchange failed to properly execute the order byreleasing the preimage x. This is an unlikely case, be-cause the exchange is supposed to execute any ordersplaced against any of its quotes. This last trade is con-sidered to be improperly aborted. Whenever the ArwenDaemon detects an improperly aborted trade, it pro-tects the user’s coins by freezing the user escrow andexchange escrow that backed this trade. Frozen escrowscannot be used for trading.

    11

  • Next, the user’s Arwen Daemon immediately asks theexchange to cooperatively close the user escrow (on theBitcoin blockchain) and exchange escrow (on the Lite-coin blockchain) that backed this trade, under the as-sumption that the balance in these escrows is as it wasprior to the final, improperly-aborted trade. If the ex-change agrees to close both escrows, then no furtheraction is required from the user.

    However, suppose that the exchange refuses to closethe frozen exchange escrow. In this case, the user’s Ar-wen Daemon will immediately and unilaterally close theexchange escrow by posting the puzzle transaction fromthe aborted trade. Doing this, however, means that thecoins in the exchange escrow, that were involved theaborted trade, are still locked in the puzzle transaction’sHTLC smart contract until time τB. We call these coinsthe outstanding coins. The outstanding coins rightfullybelong to Alice if the exchange sneakily executed theaborted trade on the Bitcoin blockchain without tellingAlice; otherwise, the outstanding coins rightfully belongto the exchange. The remainder of this procedure is al-lows Alice to claim the outstanding coins whenever theyare rightfully hers.

    What happens next depends on whether the exchangealso agreed to cooperatively close the user escrow. If so,no further action is required from Alice. This followsbecause the user escrow was closed according to thebalance before to the aborted trade, so the outstandingcoins rightfully belong to the exchange. The exchangecan unilaterally claim the outstanding coins once thetimelock τB expires by posting a puzzle-refund transac-tion, signed by the exchange, that sends the outstandingcoins to the exchange’s wallet.

    Otherwise, the exchange refused to cooperatively closethe user escrow. Alice must come online during timewindow (twA, τB) to allow her Arwen Daemon to claimthe outstanding coins. Thus, the Arwen Daemon scansthe Bitcoin blockchain looking for transactions that spendthe user escrow. There are several cases:

    • User escrow closed using a successful trade. Theexchange closed the user escrow on the Bitcoinblockchain via a puzzle transaction for any tradeprior to the aborted trade. No further action isneeded from the Arwen Daemon. This follows be-cause the outstanding coins rightfully belong tothe exchange, and the exchange can unilaterallyclaim them once the timelock τB expires via apuzzle-refund transaction.

    • User escrow closed using the aborted trade. Theexchange closed the user escrow on the Bitcoinblockchain via a puzzle transaction for the abortedtrade, as well as its corresponding solve transac-tion. The Arwen Daemon learns the solution xfrom solve transaction on the Bitcoin blockchain.The Arwen Daemon then uses x to form and signthe solve transaction for the Litecoin blockchain,claiming the outstanding coins for Alice. Impor-tantly, the Arwen Daemon must complete this ac-tion before τB, because the outstanding coins canbe unilaterally claimed by the exchange after τB,which puts Alice’s coins at risk.

    • User escrow partially closed. The exchange postedthe puzzle transaction for any trade made againstthis user escrow, but the coin locked in this puzzletransaction on the Bitcoin blockchain are unspent.In this weird case, the exchange has not executedthe aborted trade without telling the user, and sothe user will not be able to claim the outstandingcoins on the Litecoin blockchain. Nevertheless, theArwen Daemon must still recover the coins lockedin the puzzle output from the user escrow on theBitcoin blockchain and send them back to the Al-ice’s wallet. The user can unilaterally do this afterthe timelock on puzzle transaction expires at timeτA, by posting a puzzle-refund transaction to theBitcoin blockchain that sends locked coinsback toAlice’s wallet. Note that τA = twA for all tradesmade against this user escrow, which means thatArwen Daemon can take this action during thetime window (twA, τB).

    • User escrow not closed. Here the output of theuser escrow is unspent. This again means that ex-change has not executed the aborted trade, so theuser cannot claim the outstanding coins. How-ever, the Arwen Daemon must still recover thecoins locked in the user escrow. The Arwen Dae-mon will post the refund transaction that releasescoins to Alice’s wallet and the exchange’s wallet,according to the balance in the escrow prior tothe aborted trade. The can be done anytime af-ter time twA when the user escrow expires, whichmeans that Arwen Daemon can take this actionduring the time window (twA, τB).

    Once this process is complete, both the user escrow andthe exchange escrow are closed.

    6. ETHEREUM UNIDIRECTIONAL RFQSWe now describe how to port the unidirectional RFQ

    protocol of Section 5 to Ethereum and ERC-20 tokens [36].We use an escrow smart contract that mimics the UTXOtransaction paradigm that is used on Bitcoin.

    Ethereum Smart contract. Each user escrow andexchange escrow is a smart contract that can be in oneof three states: (OPEN, PUZZLE, CLOSED). Coins arelocked when the escrow is OPEN, and released when theescrow is CLOSED. The PUZZLE state is for trading.

    The user escrow can move from the OPEN state tothe CLOSED state via a:

    1. refund transaction which is signed by the user andposted to the blockchain after time twA, (thus ful-filling the timelock condition of the Arwen escrow)

    2. cashout transaction which is doubly-signed by theuser and by the exchange, (thus fulfilling the 2-of-2multisig condition of the Arwen escrow)

    Meanwhile, the escrow smart contract moves from theOPEN state to the PUZZLE state when a puzzle trans-action, that calls a method in the escrow smart contract,is confirmed on the Ethereum blockchain. The puzzletransaction is doubly-signed by the user’s ephemeral key

    12

  • and the exchange’s ephemeral key (thus fulfilling the 2-of-2 multisig condition of the Arwen escrow) and con-tains a puzzle y and an puzzle timelock τ (which areused for atomic swap trading). Then, a user escrow canmove from the PUZZLE state to the CLOSED state via:

    3. solve transaction which contains solution x and issigned by the exchange

    4. puzzle-refund transaction which is signed by theuser and posted to the blockchain after time τA

    The exchange escrow can be analogously arrive in theCLOSED state in four ways (i.e., via solve, puzzle-refund, refund, or cashout transaction).

    The RFQ protocol is essentially identical to that ofSection 5. The four ways that the user escrow can beclosed are identical to the four ways that an escrow canbe closed in the protocol of Section 5 (see also Figure 2).As in Section 5, the cashout transaction is used for co-operatively closing an escrow, while the puzzle, solve,refund, and puzzle-refund transactions are used to uni-laterally close escrows per Section 5.5, 5.6.

    ERC-20 smart contract. Our ERC-20 implemen-tation of Arwen is identical to the Ethereum implemen-tation, with the following key modification.

    The ERC-20 implementation of the Arwen escrowsmart contract includes an additional state, UNFUNDED,which is used to lock ERC-20 tokens in Arwen escrows.(Recall that an ERC-20 token is created via the im-plementation of a single standard ERC-20 smart con-tract on the Ethereum blockchain, where the state ofthe ERC-20 contract tracks the number of tokens heldby each account holder of the token. Thus, the Arwenescrow smart contract must alter the state of the ERC-20 smart contract in order to lock coins in escrow.)

    To see how this is done, we describe the three-stepprocess used by Alice to lock 5 tokens in a user es-crow. First, Alice posts the user escrow smart contractto the Ethereum blockchain; at this point, the escrowis in the UNFUNDED state. Second, Alice call the ap-prove method in the token’s ERC-20 smart contract, in-dicating that she approves the transfer of 5 tokens fromAlice’s address to the user-escrow smart contract’s ad-dress. Third, Alice calls the fund-escrows method inthe user escrow smart contract, which interacts withthe ERC-20 smart contract to transfer the required 5token into the user escrow smart contract. Similarly,when the user escrow is CLOSED, it interacts with theERC-20 smart contract to release the balance of tokensfrom the user-escrow smart contract address into bothAlice’s address and the exchange’s address.

    7. TRANSACTION MALLEABILITYArwen withstands transaction malleability attacks on

    “Bitcoin-derived‘’ blockchain that do not have SegWit.We now explain the transaction malleability problem,discuss why it affects layer-two blockchain protocols,and explain how Arwen avoids it. Withstanding trans-action malleability allows Arwen to support more Bitcoin-derived blockchains.

    Transaction malleability. Consider a transac-tion T2 that spends the output of a transaction T1. T2

    therefore contains a pointer to T1, called the TXID.This TXID is malleable: the TXID can be changed(“mauled”) by anyone, without affecting the validity orcontents of transaction T1.

    We explain why as follows. The TXID on T1 is thehash of (essentially) the entire T1, including any sig-natures on T1. Most “Bitcoin derived” blockchains useelliptic curve digital signatures, which are not determin-istic. (That is, a random value r is used to compute thesignature σ on message m.) This means that a partythat holds the secret signing key can easily produce mul-tiple valid signatures σ, σ′, . . . on a single message m.Worse yet, even a party that does not know the secretsigning key can take a valid signature σ on a messagem, and maul σ to obtain a different valid signature σ′

    on m. Now, because TXID is the hash of (essentially)the entire T1, mauling the signatures on T1 results in acompletely different TXID for T1. Additionally, someparts of the transaction that are included in the TXIDhash are not covered by the signature on the transac-tion, which creates an additional malleability problem.

    SegWit. With SegWit [39], the TXID hash is notcomputed over the signatures on the transaction. Thissolves the malleability problem, because now maulingthe signature has no effect on the TXID. SegWit also re-moves other malleability vectors (i.e., parts of the trans-action that are not covered by the signature).

    Impact on layer-two protocols. If T1 is alreadyreliably confirmed on the blockchain, the security of theblockchain ensures that no one call maul the signatureson T1, and transaction malleability is irrelevant.

    Now consider a layer-two protocol where Alice holdsT1, an off-blockchain transaction that spends an on-blockchain transaction T0. Next suppose that Alicetransfers coins to Bob by sending Bob an off-blockchaintransaction T2 that is signed by Alice and contains apointer to T1. Transaction malleability means that Al-ice’s signature on T2 is completely useless. This fol-lows because Alice can break the TXID pointing fromT2 to T1 by mauling the signatures on T1; this meansthat T2 becomes an invalid transaction but T1 remainsvalid. Thus, Bob could not use T2 to claim coins fromT0. (This is exact reason why the Lightning Network,as currently designed, only works with blockchains thatsupport SegWit, see Appendix A of [25].)

    How Arwen avoids this problem. To avoid thisproblem, Arwen ensures that parties never need to sendeach other signatures on off-blockchain transactions thatpoint to other off-blockchain transactions. Instead, par-ties only send each other signatures on off-blockchaintransactions that point directly to the Arwen on-blockchainescrows. This further implies that if an off-blockchaintransaction comes with a smart contract (e.g., like theHTLC smart contract on the off-blockchain puzzle trans-action), then each clause on that smart contract mustrequire the signature of only one party. If a singleclause required the signature of more than one party,then parties would need to send each other signatureson off-blockchain transactions that point to other off-blockchain transactions, which is vulnerable to transac-tion malleability. The reader is invited to check that

    13

  • Arwen is robust to transaction malleability, by checkingthat each clause on a smart-contract in an off-blockchaintransaction only requires the signature of a single party;see Figures 2,3,4.

    This is also why we can not use relative timelocks i.e.,CheckSequenceVerify [9] in Arwen. CheckSequenceVer-ify (which is used extensively in Lightning) provides atimelock which is relative to the time another transac-tion is confirmed on-blockchain. CheckSequenceVerifyis therefore not safe to use on blockchains vulnerableto transaction malleability attacks, like BCH or ZEC.Instead, Arwen can only use absolute timelocks i.e.,CheckTimeLockVerify [35].

    8. BIDIRECTIONAL RFQSThe following Arwen RFQ protocol is bidirectional,

    because it allows Alice to both buy and sell coins fromher user escrow, and to both buy and sell coins fromher exchange escrow. A bidirectional protocol is usefulfor high-frequency trading strategies, where the traderquickly moves coins back and forth.

    Like the unidirectional protocol of Section 5, each off-blockchain RFQ trade in the bidirectional protocol isbacked by a user escrow (with expiry time twA) and anexchange escrow (with expiry time twB). The protocolfor opening these escrows remains identical to the onein Section 3.2. Both escrows must be open during atrade (rather than expired, frozen, or closed). In whatfollows, we first overview the technical tools used in ourbidirectional protocol, describe the off-blockchain trad-ing protocol, and explain how escrows can be securelyclosed when one party becomes malicious or uncooper-ative. The transaction diagram for the user escrow andexchange escrow is in Figure 4.

    8.1 Technical toolsWe continue to execute trades using HTLCs, where a

    trade is executed by revealing the solution x to a puzzley, where y = H(x). However, but there are several othertechnical tools needed in order to make this protocolbidirectional. We outline some tools below.

    Four puzzles transactions. In the unidirectionalprotocol, there was only a single type of puzzle transac-tion that could spend the output of each escrow. In thebidirectional protocol, there are four puzzle transactionsper escrow: payU postU, payU postE, payE postU, andpayE postE. This is true for both the user escrow andthe exchange escrow. The only difference between thepuzzles for the user escrow puzzles and the puzzles forthe exchange escrow is that user escrow puzzles havetw = twA and exchange escrow puzzles have tw = twB.The user will only post a puzzle transaction if the ex-change aborts a trade. The exchange will post a puzzletransaction if the user aborts a trade or if the user failsto cooperatively close an escrow before it expires.

    payE and payU puzzles. By having both payE andpayU puzzles for each escrow, each escrow can be usedto both buy and sell coins. In a payE puzzle, the puzzlelocks coins that pay to the exchange once the exchangereveals x in a solve transaction, before time τA. ThepayE puzzle transaction has an HTLC smart contract

    that is similar to the one in Figure 2 of our unidirectionalprotocol, using timelock τA and puzzle y. In a payUpuzzle, the puzzle locks coins that pay to the user, oncethe user reveals x in a solve transaction before timeτB . The payU puzzle has an HTLC smart contract thatis similar to the one in Figure 3 of our unidirectionalprotocol using timelock τB and puzzle y.

    If the user is doing a trade that buys coins from theuser escrow while selling coins from the exchange es-crow, we would use a payU puzzle that spends the userescrow and a payE puzzle that spends the exchange es-crow. Meanwhile, to buy coins from the exchange es-crow while selling coins from the user escrow, we usea payE puzzle that spends the user escrow, and payUpuzzle that spends the exchange escrow.

    postU and postE puzzles. A postU puzzle transactioncan only be posted to the blockchain by the user. ThepostU puzzle transaction is initially formed and signedby the exchange, and then sent to user; the user canlater post this transaction to the blockchain if the ex-change becomes uncooperative. The analogous postEpuzzle transaction can only posted by the exchange

    Two cashout transactions. The postU cashout issigned by the exchange and sent to the user, and is usedto unilaterally close an escrow when all trades againstthe escrow completed successfully. The postE cashout,which is signed by the user and sent to the exchange, isused to cancel RFQ quotes.

    Cancelling transactions. Arwen’s bidirectionalRFQ protocol no longer relies on “the magic of unidirec-tionality” (Section 5.3). Instead, we “overwrite” trans-actions resulting from old trades by cancelling them,adapting the idea of justice transactions from the Light-ning Network [29].

    Every postE-type transaction, which is first signed bythe user and then sent to the exchange, can be cancelledby the exchange using the cancel value CE . The cancelvalue CE is randomly chosen and kept secret by the ex-change. To cancel the postE transaction, the exchangereveals CE to the user. The cancel value CE protects theuser if the exchange posts a canceled postE transactionto the blockchain, as follows. The postE transactioncontains a value jE such that jE = H(CE), and everyoutput on the postE transaction that pays out to theexchange also includes the following smart contract:

    “The coins may only be paid to the exchangeafter time tw , OR the coins return to theuser if the user reveals the cancel value cor-responding to jE .”

    Then, if the exchange misbehaves by posting a can-celled transaction, the user has can retaliate via a justicetransaction anytime before tw . The justice transactionreveals CE and is posted unilaterally by the user, allow-ing her to claim all the coins in the canceled transactionanytime before time tw (see Figure 4).

    Previous transactions. The following notationis useful for our protocol description and analysis. Letpay∗ postE be a puzzle transaction from the currenttrade (where ∗ is either U or E). For convenience, we use

    14

  • the notation prev(pay∗ postE) to indicate the transac-tion from a previous trade that is (a) held by the ex-change and (b) spends the same escrow as the pay∗ postE.Differences from the Lightning Network. Ourbidirectional protocol has many things in common withthe payment channel design of the lightning network.However, there are some important differences. To sup-port coins that don’t have a transaction malleabilityfix, e.g., SegWit, additional constraints are placed onour design. Unlike lightning we can not use the rel-ative timelocking mechanism CheckSequenceVerify [9],instead we can only use the absolute timelocking mech-anism CheckLockTimeVerify [35]. Thus, our escrows al-ways have a fixed time before they must be closed. Ad-ditionally, as discussed in Section 7, due to the threat oftransaction malleability any transactions which requiresignatures from both parties must spend from a trans-action which is already confirmed on-blockchain. Thisrequirement results in a slightly different breach remedymechanism. Unrelated to malleability, our protocol isfocused on trading cross-chain at centralized exchanges,rather than on peer-to-peer payments, so we have theescrow fee mechanism to enable traders to open escrowseven when they do not already hold any of those coins(see Section 3.5).

    8.2 Security assumptions.Timelocks. The security of this protocol follows be-cause we set the timelocks to be

    τA > max(twA, twB) + 2% τB > τA + 2% (2)

    where % is the time required for transaction be reliablyconfirmed on the blockchain. Importantly, notice thatthere is no relationship between the escrow expiry times(twA, twB), which means we can pair any user escrowand exchange escrow, regardless of their expiry time.

    Closing escrows in a timely manner. To with-stand attacks by a compromised or malicious user:

    The exchange must close its user escrows be-fore they expire at time twA, and its ex-change escrows before they expire at twB.

    To withstand attacks by a compromised or unresponsiveexchange:

    The user must close her user escrows beforethey expire at time twA, and her exchangeescrows before they expire at twB.

    If the user forgets to do this, an honest exchange willclose the escrow on the user’s behalf, but a maliciousexchange may be able to steal coins from the escrow.Also, if a trade aborts or the exchange refuses to coop-eratively close an escrow, the user must sometimes comeonline at a later time in order to recover her coins. Thiscoin recovery periods are only required if the exchangebecomes unresponsive or hacked, and the user will al-ways learn exactly what the coin recovery period is atthe time she attempts to close her escrows.

    8.3 Off-blockchain RFQ trades.Before each RFQ begins, we have the following off-

    blockchain setup step. This setup could happen at anytime (even immediately after the previous trade).

    Setup. The exchange chooses random solution x,computes y = H(x), and sends the puzzle y to theuser. The exchange also chooses a two random cancelvalues CE,A and CE,B, computes jE,A = H(CE,A) andjE,B = H(CE,B), and sends jE,A and jE,B to the user.The solution x and cancel values CE,A, CE,B are kept se-cret by the exchange. The user responds by choosing arandom secret cancel value CU , computing jU = H(CU ),and sending jU to the exchange.

    Then, each RFQ is an off-blockchain protocol com-prising the following four steps. In the following pro-tocol description, we assume that Alice specifies theamount of coin she wishes to buy in the Request stage.1

    Request. Alice requests a quote, indicating whatescrow she wants to sell coins from, and what escrowshe wants to buy coins from, and the amount of coinsshe wants to buy. If Alice is selling from the user escrow,this protocol uses payE puzzles on the user escrow andpayU puzzles on the exchange escrow. If Alice is buyingfrom the user escrow, we use payU puzzles on the userescrow and payE puzzles on the exchange escrow.

    Alice then sends the exchange the following:

    1. a payU postE puzzle transaction that (a) locksthe amount of coins she is buying under puzzley. If Alice is buying coins from the user escrow,this payU postE puzzle transaction (b) spends theoutput of the user escrow and (b) can be cancelledunder CE,A. If Alice is buying coins from the ex-change escrow, this payU postE puzzle transac-tion (b) spends the output of the exchange escrowand (b) can be cancelled under CE,B.

    As an example, refer again to Figure 1, and supposeafter the second trade in the Figure Alice requests aquote “Buy 2 BTC for some LTC.” In this case, Alicewould send the exchange a payU postE puzzle transac-tion that (a) locks 2 BTC under puzzle y, (b) spendsthe output of the user escrow, and (c) can be cancelledusing cancel value CE,A.

    Quote. The exchange responds with the quote—“2BTC can be bought for 200 LTC, open for time δ”. Tocommit to the quote, the exchange signs and sends Alicethe following three items.

    1. A payU postU puzzle transaction that (a) locksthe amount of coins Alice is buying under puzzley, and (b) can be cancelled using cancel value CU .If Alice is buying coins from the user escrow, thispayU postU puzzle transaction (c) spends the out-put of the user escrow. Otherwise, this payU postEpuzzle transaction (c) spends the output of the ex-change escrow. (This puzzle is analogous to the

    1For a sell-side RFQ, we could prefix the flow describedhere with two additional messages: (1) the user indi-cates an amount of coin she wishes to sell and requestsa quote, and (2) the exchange provides the user withthe quote with the amount she can buy.

    15

  • user escrow

    payU_postE

    justice

    refund

    (U Λ E)

    U-Wallet

    (E Λ tw

    A ) (U Λ C

    ε,A )

    (U Λ E) (U Λ tw

    A )

    U-Wallet

    E-Wallet

    (U Λ E)

    U-Wallet

    E-Wallet

    payU_postU

    justice

    (U Λ E)

    E-Wallet

    (U ΛX Λ tw

    A ) (E Λ C

    u )(E Λ τ

    B )

    solve

    E-Wallet

    U-Wallet

    postU cashout(U Λ E)

    E-Wallet

    U-Wallet

    U-Wallet

    U-Wallet

    (U Λ X ) (E Λ τ

    B ) solve(U Λ X)

    U-Wallet

    puzzle refund

    E-Wallet

    E-W

    allet

    payE_postE

    justice (U Λ E)

    U-Wallet

    U-Wallet

    E-Wallet

    payE_postU

    justice

    (U Λ E)

    E-Wallet

    solve

    E-Wallet

    U-Wallet

    (E Λ X)

    E-Wallet

    solve0070C0ff

    U-Wallet

    U-W

    allet

    exchange escrow

    payU_postE

    justice

    refund

    (U Λ E)

    U-Wallet

    (E Λ tw

    B ) (U Λ C

    ε,B )

    (U Λ E) (E Λ tw

    B )

    (U Λ Cε,B )

    (E Λ twB )

    U-Wallet

    E-Wallet

    (U Λ E)

    U-Wallet

    (E Λ tw

    B ) (U Λ C

    ε,B ) (E Λ tw

    B ) E-W

    allet

    (E Λ twB )

    payU_postU

    justice

    (U Λ E)

    E-Wallet

    (U Λ X Λ twB )

    (E Λ Cu )

    (E Λ τB )

    solve

    (E Λ Cu )

    (U Λ twB )

    E-Wallet

    U-Wallet

    (U Λ X Λ twB )

    (U Λ E)

    E-Wallet

    (U Λ tw

    B ) (E Λ C

    u )

    (U Λ twB )

    U-Wallet

    E-Wallet

    U-Wallet

    (U Λ X) (E Λ τ

    B )

    (U Λ twB )

    (E Λ Cu )

    solve(U Λ X)

    U-Wallet

    (E Λ τ

    B )

    E-Wallet

    (E Λ τB )

    E-Wallet

    payE_postE

    justice (U Λ E)

    U-Wallet

    (E Λ twB )

    U-Wallet

    E-Wallet

    payE_postU

    justice

    (U Λ E)

    E-Wallet

    (E Λ X) (U Λ τ

    A ) solve

    (U Λ twB )

    E-Wallet

    U-Wallet

    (E Λ X) E-W

    allet

    (E Λ X Λ twB )

    (U Λ Cε,B )

    (U Λ τA )

    solve(E Λ X Λ tw

    B ) E-W

    allet

    (U Λ τA )

    (U Λ τ

    A )

    U-Wallet

    U-W

    allet

    (U Λ twA )

    (U Λ X Λ tw

    A )

    (B Λ X Λ twA )

    (U Λ tw

    A )

    (U Λ twA )

    (E Λ Cu )

    (E Λ X Λ tw

    A ) (U Λ C

    u )(U Λ τ

    A )

    (U Λ twA )

    (E Λ Cu)

    (U Λ twA )

    (E Λ Cu )

    (U Λ twA )

    (E Λ tw

    A )

    (E Λ twA )

    (E Λ twA )

    (U Λ Cε,A )

    (E Λ twB )

    (U Λ Cε,B )

    (U Λ Cε,B )

    (E Λ C

    u )

    (U Λ twB )

    (E Λ Cu )

    (U Λ Cε,A )

    (E Λ C

    u )

    (U Λ Cε,A )

    (U Λ τA )

    (U Λ τ

    A )

    (E Λ τB )

    (E Λ τ

    B )

    (E Λ X) (U Λ τ

    A )

    (E Λ Cu )

    (E Λ twA )

    (U Λ Cε,A )

    postE cashout

    postU cashoutpostE cashout

    puzzle refundpuzzle refund

    puzzle refund

    puzzle refundpuzzle refund

    puzzle refundpuzzle refund justice

    E-Wallet

    (E Λ Cu )

    justice

    U-Wallet

    (U Λ Cε,A )

    justiceU-W

    al