Masaryk University Faculty of Informatics

P2P Exchange and Size Reduction

Ph.D. Thesis Proposal

Michal Zima

Advisor: Eva Hladká

Brno, Autumn 2017 Signature of Thesis Advisor Contents

1 Introduction 1

2 Preliminaries in Blockchain 4 2.1 Blockchain ...... 4 2.2 Merkle Trees ...... 7 2.3 Transaction Structure ...... 8 2.4 Scripting ...... 9 2.5 Simple Payment Validation ...... 10 2.6 Spendability of Transactions ...... 10

3 State of the Art 12 3.1 Exchanging without Intermediaries .... 12 3.2 Pruning of Merkle Trees ...... 14 3.3 Pruning with UTXO Set ...... 15 3.4 Redactable Blockchain ...... 16 3.5 Mini-blockchain ...... 16 3.6 UTXO Set Commitment ...... 18 3.7 Merged Mining ...... 19

4 Aims of the Thesis 21 4.1 Objectives and Expected Results ...... 21 4.2 Plan of Work ...... 22

5 Achieved Results 24 5.1 Decentralisation of Cryptocurrency Exchange ...... 24 5.2 Scheme of Sustainable Blockchain ...... 25 5.3 Hash Reduction ...... 27

6 Author’s Publications 29

Bibliography 30

A Publications 35 A.1 Cryptography Enhanced Ad-Hoc Approach to P2P Overlays 36 A.2 Coincer: Decentralised Trustless Platform for Exchanging Decentralised Cryptocurrencies ...... 42

i 1 Introduction

Digital money was for a long time a goal of many efforts. Indistin- guishability of originals from copies served as the most challenging point. There had to be a central database system that allowed verifi- cation of money and execution of transfers. Naturally, this approach caused concerns about users’ privacy. David Chaum in 1990 addressed this issue by introducing a cryptographic approach to anonymous digital money [1]. Nonetheless, it was not until invented Bitcoin in 2008 that anonymous digital money came into general use. Using a novel combination of several known cryptographic primitives and P2P networking he devised trustless digital money which lacks any central authority or centralised database. Being a new approach to digital money, Bitcoin also brought new challenges. One of them has been its scalability in recent years. As of early 2017 Bitcoin’s distributed database (called blockchain) is capable of storing 1MB of data per 10 minutes on average, which translates into approximately 3–4 transactions per second1. For comparison, PayPal processed 200 transactions per second on average in 2016 [2] and Visa 2,600 transactions per second [3]. Since popularity of Bitcoin rises (evidenced also by its rising ex- change rate to traditional fiat currencies [4]), this throughput limitation becomes more visible. There are also SPAM attacks against Bitcoin [5] that cause transaction fees to rise for ordinary users to get their transactions verified. Proposals for scaling Bitcoin in general revolve around increasing the main limit of 1MB per 10 minutes (either di- rectly [6, 7, 8, 9, 10, 11, 12] or only effectively [13]), although this is not the only proposed measure. While this may lessen current issues, it may as well worsen other aspects. The Bitcoin blockchain is designed as an ever growing storage that contains all transactions since Bitcoin’s inception. Due to this fact, the blockchain size is at 119GiB as of July 2017. The aforementioned limit restricts the growth to approximately 49GiB per year. Growth of blockchain size can be observed on Fig. 1.1 and while it may seem to grow exponentially, the 49GiB limit says that it is in fact on linear

1. Given the average size of a transaction in 2016 of 515 bytes. 1 1. Introduction

140 Bitcoin blockchain size 120

100

80 GB 60

40

20

0 2010 2011 2012 2013 2014 2015 2016 2017 Time

Figure 1.1: Cumulative size of the raw blockchain data.

growth trajectory in 2017. Yet the steepness of the linear curve slowly starts to change as of August 2017 with deployment of a new scaling approach called Segregated Witness [13]. While it is said [14] that Bitcoin nodes may only store small block- chain metadata (amounting to 36MiB as of July 2017) and not the whole data, there is a trade-off between the size of the stored data on one side and security and privacy on the other. Moreover, these lightweight nodes cannot exist on their own—they depend on other nodes (so called full nodes) that do store the full blockchain data. However, with such a growth it becomes increasingly costly to run a full node. Besides the storage itself, among rising demands are bandwidth, computational resources (due to the need to verify all the data) and time for initial synchronisation with the . As a result, less nodes can afford to be full nodes, thence decentralisation suffers. An obvious way towards solving this issue is through pruning the blockchain data from data that should not be needed anymore, i. e., data of already spent transactions as described in Sect. 7 of [14]. This

2 1. Introduction

approach serves as a basis for further approaches, nonetheless, it does not stop the blockchain from unbounded growth in size. There are many transactions that we know cannot be ever spent (for instance [15]), but from computational point of view it is an undecidable prob- lem. Besides centralisation risks stemming from blockchain growth, cryptocurrencies suffer from centralisation on a level of entry and exit points for users—cryptocurrency exchanges [16]. Success of the Bitcoin model led to emergence of countless alternative cryptocur- rencies following the principles of Bitcoin. A natural consequence was demand of their users to exchange and trade these cryptocurren- cies which further led to a rise of many exchange platforms focused specifically on cryptocurrencies. Centralisation to a limited number of exchanges attracts attackers who successfully exploit vulnerabilities in the platforms, which accounts for more than 26 million USD of losses as of 2017 [17]. To date, various approaches were developed. There are methods for exchanges to easily prove their solvency [18, 19], but neither they were widely adopted nor they could solve the aforementioned prob- lem. Different approach is to completely remove intermediaries from the process of exchanging cryptocurrencies. However, even though the first solution was proposed in 2013 [20], due to its real-world limi- tations it has never had any practical, decentralised implementation. Aim of my work is focused on two important challenges that can improve decentralisation of cryptocurrencies ecosystem. First, I plan to develop a set of network and cryptocurrency protocols for safe decentralised trading of different cryptocurrencies. My second goal is to propose both technical and incentive mechanisms for maintaining a blockchain with a bounded size. The remainder of this thesis proposal is organised as follows. In- troduction to the area of blockchain and cryptocurrencies is given in Chap. 2. Chapter 3 describes state-of-the-art decentralised cryptocur- rency exchange and blockchain minification approaches. Chapter 4 sets goals of my work and outlines a time plan for them. An overview of achieved results is provided in Chap. 5, followed by a list of publi- cations in Chap. 6. The proposal concludes with a bibliography and a selection of my published papers.

3 2 Preliminaries in Bitcoin Blockchain

This chapter introduces the terminology and the basics of Bitcoin and blockchain.

2.1 Blockchain

Blockchain is a database of transactional data. It is a decentralised system without any central coordinator where all data are distributed over a network of interconnected nodes. This eliminates the need for trusted parties as each node can independently verify integrity and validity of all stored data by themselves. Since contents of blockchain are shared among all nodes in its network, it is important that it converges to a single shared state. This is achieved by grouping transactions into blocks every 10 minutes on average. Hence, the blocks fulfil a role of synchronisation points. Blocks form a chain by being linked into a hash chain: each block (except the first one, so called genesis block) includes a link (i. e., hash) of the previous block, as illustrated in Fig. 2.1. An important property inherited from a regular hash chain is immutability of stored data. To change a block inside a hash chain, it is required to also update all links to previous blocks inside blocks following the changed block. The change is therefore easily detectable.

2.1.1 Mining/ Practical immutability of blockchain data is secured by a condition that each block’s hash1 has to meet requirements for a proof of work.

1. In this work all mentions of “hash” mean output of a cryptographic hash function, e. g., SHA-2.

h(root) h(node 1) h(node 2) root node 1 node 2 node 3 (node 0) Figure 2.1: Illustration of the hash chain/blockchain structure: hash of each node in the chain is influenced by contents of all preceding nodes through their direct predecessor’s hash.

4 2. Preliminaries in Bitcoin Blockchain

Proof of work is a mechanism that certifies that a certain amount of computational work was performed. In Bitcoin, the proof of work consists of a double SHA-256 hash of a block header. The bitcoin protocol computes in a decentralised manner a difficulty of the required proof. The difficulty is a parameter that sets a constraint on the value of the proof of work hash. Every 2016 blocks the difficulty gets adjusted by the network so that the interval between blocks is on average 10 minutes, regardless of the computational power dedicated for mining. Mining is a process of finding a valid proof of work hash by iterating through anonce space in the block header.

2.1.2 51% attack Security of Bitcoin lies to some extent on economic incentives. Miners are motivated to behave honestly and work on a single, longest chain of blocks. As long as these honest miners form an honest majority, the longest chain will contain a truthful version of transaction history. In a 51% attack an attacker outweighs everyone else’s cumulative mining power by ignoring other blocks than their own. Having more mining power than everyone else allows them to mine their own version of the blockchain. While the attacker cannot force their own consensus rules, they can easily deploy a double spending attack or censoring arbitrary transactions. While the attack is historically called “51% attack,” it has been shown several times that in real setting it may be needed even less than 51% of mining power to mount a double spending attack. [21, 22] Some variants allow only a small-scale attack, meaningful mainly for unfair increase of market share of the attacking miner. [23, 24]

2.1.3 Blockchain Reorganisation Miners compete with each other in a race for finding a solution for the next block hash. When two miners mine a block at a roughly same time, part of the network may receive one of them earlier than the other, while the rest of the network receives the second one earlier (as illustrated in Sect. Blockchain Forks of Chap. 8 in [25]). At that moment the blockchain is forked into two branches, each with a different set

5 2. Preliminaries in Bitcoin Blockchain

of miners. This should be resolved as soon as a second block in either branch is mined. This block creates new longest chain and the part of the network with the orphaned block will reorganise their to this branch. Reorganisation is done by unwinding all blocks from the depre- cated blockchain branch and gradually applying all blocks from the new longest one.

2.1.4 Measuring Volume of Data For the context of this work it is important to introduce a consistent notion for measuring volume of data. Otherwise numbers might not be mutually comparable and it may be difficult to infer conclusions upon them. There are two possible approaches: to measure volume of raw data or volume of data stored by client software. The raw data comprise only the actual blockchain data that are exchanged over the P2P network. On the other hand, the stored data consist of multiple additional components:

∙ orphan blocks—blocks that ended up not being in the block- chain,

∙ block indices—operational data for fast lookup of blocks on disk,

∙ reverse blockchain data—needed for fast reorganisations of the blockchain,

∙ records about all unspent money—used every time a transaction or a block is to be validated.

Exact size of the additional data may vary, depending on imple- mentation and particular instance of a client. For example, a Bitcoin Core node I run stores 153GiB of data as of September 2017, while the raw blockchain volume is only 122GiB. Therefore, to provide unambiguous and stable reference, for the rest of the work all volumes represent the raw data unless explicitly stated otherwise.

6 2. Preliminaries in Bitcoin Blockchain

'$abcc ¨¨ HH ¨ H &% '$ab'$ cc

@@ &% &% a b c

   Figure 2.2: Example of a Merkle tree.

2.2 Merkle Trees

Transactions in a bitcoin block are logically organised into a crypto- graphic data structure called Merkle tree [14]. In this authenticated binary tree all non-leaf nodes contain a hash of concatenated contents of its descendant nodes [26]:

nodex,y = H(nodex ⊕ nodey) In case there is only one descendant node, it is concatenated with itself for the purpose of construction its parent node:

nodex,− = H(nodex ⊕ nodex) Where H is a cryptographic hash function. Bitcoin stores hashes of individual transactions in leaves. The Merkle tree root hash is then stored in a block header, thus authenti- cating the whole set of transactions included within the block.

2.2.1 Leaf Authentication In a Merkle tree it is possible to authenticate any leaf in the tree. We use “authentication path” for this purpose. This path comprises transaction hashes in the authenticated and its neighbouring leaf (if there is such a leaf) and content of every top node of adjacent branches that are hashed with nodes from the branch of the authenticated leaf. For

7 2. Preliminaries in Bitcoin Blockchain

instance in the tree depicted in Fig. 2.2 the authentication path for a nodeb consist of contents of nodes nodeb, nodea and nodecc. The subtree of nodecc is not needed. Thence, size of an authentication path is logarithmic with respect to the tree size.

2.3 Transaction Structure

The structure of transactions in Bitcoin loosely follows an analogy of a —there is a money inflow side and a money outflow side ofthe transaction. In Bitcoin’s terminology, these are called inputs and out- puts, respectively. Inputs reference outputs of other transactions, i. e., the money they spend. Outputs, on the other hand, specify “spending conditions” on the money. These conditions are expressed in a general way in form of scripts. Inputs also provide proofs that the spending conditions of referenced outputs are satisfied [25]. For instance, an output may specify a public key of the intended recipient of the money and all operations (functions) needed to be executed in order to authorise a potential spender. Then, an input would provide a signature by a corresponding private key, hence proving the ownership and the prerogative to spend the money.

2.3.1 Transaction

The so called coinbase transaction is a transaction with a special set of rules. It is present in every block and only once—it is the very first transaction in a block. Its purpose is to award a miner withnew emission of money and transaction fees collected from transactions in that block. This is done with a special input that does not reference any previous output. Besides that, coinbase transaction also fulfils non-monetary func- tions. It allows 100B of arbitrary data to be stored in place of an input script. [27] This is used for various purposes, notably for extending a nonce field in the block header. It is also leveraged as a backward compatible method of adding new functionality and structures to the blockchain. [13]

8 2. Preliminaries in Bitcoin Blockchain OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG

Figure 2.3: Most used bitcoin script called pay-to-pubkey-hash [28].

2.4 Scripting

As explained in Sect. 2.3, Bitcoin and derived cryptocurrencies make an extensive use of scripting in transactions. Scripts are written in a stack- based language with postfix notation. The language includes usual programming constructions and functions. Besides those, there is a range of cryptographic functions, including hash functions and digital signature verification functions. Every script execution is guaranteed to finish in a finite time since the language does not provide cyclesnor user-defined functions. A typical script shown in Fig. 2.3 is placed within an output. Its input counterpart only pushes required data to the stack, after which the output part of the script is executed—from left to right. If the execution is aborted or ends with a false return value then the transfer was not authorised and the whole transaction is invalid. A reference list of Bitcoin script functions and operations can be found in [28]. The script in Fig. 2.3 is mostly straightforward: an input places on a stack a signature and a public key. The output script then duplicates the public key on the stack and the top copy is hashed. Another hash is placed on the stack, after which both hashes are compared for equality—if they are not equal, the script execution is aborted. Then the second copy of the public key and the signature are used as input arguments for signature verification. Should the verification succeed, the script also successfully ends its execution by returning a true value. Such programmability can be leveraged for building advanced protocols and “smart” transactions—transactions that can be spent only when a complex condition is fulfilled. We make use of it in the work introduced in Sect. 5.1.

9 2. Preliminaries in Bitcoin Blockchain 2.5 Simple Payment Validation

Bitcoin nodes can be in general differentiated as “full” nodes and “lite” nodes. Here, full nodes are those nodes that maintain a full copy of the blockchain, validate all blocks and transactions and provide them to the rest of the network. In contrast, lite nodes make use of the full nodes which provide them necessary data from the blockchain. Lite nodes do not store the blockchain—only a chain of block headers. While a block may be 1MB in size (or even bigger since August 2017), block headers have a fixed size of 80 bytes. For comparison, size of the full blockchain as of August 2017 is 122GiB (plus operational data, see Sect. 2.1.4), while the size of only the chain of block headers is 37MiB. When a lite node requests transaction data for their bitcoin ad- dresses, they conceal the exact addresses using a probabilistic data structure called bloom filter [29]. The full node that is asked for the data does not know which of the retrieved transactions actually belong to the asking node, because the transaction set is bigger than what is actually relevant for the lite node, i. e., still preserving at least a limited level of privacy. The transactions are provided together with their authentication paths (see Sect. 2.2.1), making it possible to the lite node to verify their authenticity against the chain of block headers. Therefore, it is not possible to forge transactions. However, lite nodes have no guaranteed mechanism to verify that a full node is providing truthful data. If a full node claims that there is no relevant transaction, the claim comes with no proof (unlike claims that there are such transactions). The only way for a lite node to defend against a transaction withholding attack is to query multiple full nodes and compare their answers.

2.6 Spendability of Transactions

The question whether a transaction can ever be spent, i. e., whether all of its outputs can be spent can be reduced to a question whether for each output there exists such an input script that the output script ends with a true return value. Each output script can require only a finite number of finite input data elements and its execution is finite by definition of the scripting

10 2. Preliminaries in Bitcoin Blockchain

language (see Sect. 2.4). Therefore it is theoretically possible to algo- rithmically decide whether a script is spendable simply by finding the valid input values. Nonetheless, this approach is not practically feasible since the input values may be even as large as 32 bytes, render- ing 2256 of possible values. Moreover, the security of cryptocurrency and cryptographic systems is built on the fact that it is practically unfeasible to find hash preimages or private keys to public keys. An example of a practically unspendable output is a pay-to-public key-hash script with a hash that encodes to a Bitcoin address 1Bit- coinEaterAddressDontSendf59kuE (first character is a version, last 6 char- acters are a checksum). [15] There are more classes of unspendable outputs. Another obviously unspendable outputs are outputs with erroneous scripts, e. g., a script encoding a formula 1 + 1 = 5 which is clearly unsatisfiable. However, there are also outputs technically spendable, but with low to no probability that they will ever be spent. The former are un- profitable outputs whose value is negligibly small so that a transaction fee needed for spending them would be much higher. [30] The latter are outputs with (hashes of) public keys for which corresponding private keys are lost. [31] One category of output scripts is special—it is provably unspend- able. What makes a script provably unspendable is a use of a special script operation: OP_RETURN [32]. It always evaluates the whole script to false.

11 3 State of the Art

This chapter describes state of the art in decentralised cryptocurrency exchange, followed by various approaches to blockchain downsizing and related technologies. Finally, the chapter describes the purpose, principles and challenges of merged mining.

3.1 Exchanging Cryptocurrencies without Intermediaries

There are multiple different approaches to decentralising exchange of cryptocurrencies.

3.1.1 Bisq Bisq platform employs transactions together with secu- rity deposits and arbitrators. [33] An arbitrator is passively involved in every trade—each trading party has one key and the arbitrator has the third, while two are required to execute a transfer. The second party is required to pay down a security deposit as an incentive to complete the trade. If the party refuses to cooperate, the arbitrator awards the first party this security deposit as a compensation for aborted trade. Communication within Bisq is carried out in P2P fashion over hidden services in Tor network (i. e., each participant creates a hidden service to obtain an identifier and to be reachable).

3.1.2 Escrow and Tokens Another approach, taken, e. g., by Multigateway [34] or B&C Exchange [35], is to let users deposit all cryptocurrencies into a multiparty es- crow (formed by a fixed number of independent servers) that requires a threshold number of signatures to execute a transfer out of it. For every asset in the escrow, a special token-equivalent of the cryptocur- rency is issued to the user. These tokens can then be easily traded in a decentralised fashion over a single blockchain. While these platforms remove a single central entity from the exchange process, they only move to multiple central points. There is a

12 3. State of the Art

risk of collusion of servers operators or of an attack against a sufficient number of servers.

3.1.3

TierNolan devised a method of exchanging different cryptocurrencies without a third party, leveraging solely the power of transaction scripts (this approach is also sometimes called a smart contract). [20] His cryptocurrency protocol allows atomic transactions across two distinct cryptocurrencies/blockchains. The main idea behind TierNolan’s protocol is to divide the ex- change process into two consecutive phases. In the first phase, both parties exchanging their cryptocurrencies create two transactions: a commit transaction and a rollback transaction. The commit transac- tions lock funds to the exchange (for a limited time) in such a way that it is only possible to withdraw them by proceeding in the exchange or with the rollback transactions (after the lock expires) that have to be pre-signed by both parties. To keep the transactions synchronised over two independent block- chains, the first party generates a secret number which servers asa password for unlocking the commit transactions. This password is temporarily concealed and only its hash is put into the transaction scripts. As soon as both parties commit their money to the exchange, the first party uses plain text of the password to claim exchanged funds, followed by the second party when they notices the password in the blockchain (which is public). However, Bitcoin and derived cryptocurrencies cannot properly execute this protocol, because of one particular property of digital signatures. Due to modular arithmetic it is possible to represent a single signature using multiple forms. Therefore, it is possible that a malicious actor alters a transaction from the protocol after it is sent to the network but before it is included into the blockchain (this is called transaction malleability attack [36]). Although content is (bytewise) changed, validity of signatures is preserved. Atomicity of the protocol is therefore effectively broken since it relies on unchanged hashes of involved transactions.

13 3. State of the Art

'$푎푏푐푑 '$푎푏푐푑 . . ¨¨ . . ¨¨ . . ¨ . . ¨ . . &% &% '$푎푏 '$푎푏

@@ &% 퐻(퐻(&%푡푥1) 퐻(푡푥2)) 푎 푏 ⊕

퐻(푡푥1) 퐻(푡푥2)

(a) Unpruned Merkle tree, possibly (b) Pruned Merkle tree—both tx1 with one of tx1 or1 tx2 removed. and tx2 were removed.1

Figure 3.1: Demonstration of Merkle tree pruning.

3.2 Pruning of Merkle Trees

The very first proposal for managing blockchain growth was already presented by Satoshi Nakamoto in his Bitcoin design paper [14]. Naka- moto observed that old blocks would contain an increasing number of transactions full of spent outputs. Therefore, these spent transactions would be no longer needed for construction of new transactions and could be consequently deleted from local storage. However, a deletion is normally a modification that changes the output of a hash function. This would break the chain of blocks, im- peding the possibility to verify integrity of stored data. To overcome this issue, Nakamoto leveraged properties of Merkle Trees in which all transactions are organised (see Sect. 2.2). Given how authentication works within a Merkle tree, it is possible to remove a transaction and yet not affect the resulting root hash of the tree: it is only neededto keep the hash of the transaction. Moreover, when all transactions in a branch are removed, the branch and all its internal hashes can be removed, again retaining only the branch top hash that is needed for authentication of other leaves in the tree. This is illustrated in Fig. 3.1. The verifiability of integrity of all data after pruning is a significant advantage since it keeps the system as trustless as the original one without pruning. On the other hand, in order to reach the final pruned state, a node storing the blockchain data needs to already have the

14 3. State of the Art

data in question so that it can verify them during the bootstrapping phase before the pruning can happen. From the view of blockchain size reduction this approach is not perfect. The reduction ratio depends on several factors: position of pruned transactions within block’s Merkle tree and within the block- chain itself, to what extent the transactions are spent and on amount of unspendable transactions in the blockchain. The higher the ratio of unspendable transactions, the worse long-term pruning ratio for the blockchain. Ideal pruning ratio occurs when pruned transactions contribute to pruning of the same branch since this way a number of needed hashes of pruned branches is minimised.

3.3 Pruning with UTXO Set

Due to the disadvantages of Merkle tree pruning, bitcoin client called Bitcoin Core [37] implements a more aggressive approach. Its goal is to store only the very minimum of data, plus what a user allows it to store to support the network and to secure safe functioning of the client. Therefore, the client primarily stores a “UTXO set” [38]—a set of all unspent transaction outputs. Additionally, a set of at least 288 latest blocks is stored. These are used for handling potential reorgan- isations of the blockchain and for providing them to other nodes in the network. These data allow a node to validate all new blocks, because inputs may reference only unspent outputs, which are all contained in the stored UTXO set. Security level of a pruning node is therefore as strong as of a full non-pruning node. It has a complete view of the current state and does not rely on other nodes for information about transactions, unlike an SPV node (for more information on SPV see Sect. 2.5). This also means full privacy properties—no additional information about possessed money is leaked to node’s neighbours. However, such pruning approach comes with a set of limitations. In order to reach a pruned state, nodes still need to download and verify all blockchain data. The benefit of pruning hence lies in reduced storage requirements.

15 3. State of the Art

Pruning nodes are also sensitive to changes in their wallets. While generation of new keys is handled gracefully, imports of unrelated keys or using whole wallets from other instances of Bitcoin Core always require new processing of the blockchain, i. e., downloading it all over again. Nonetheless, blockchain reorganisations are not such a serious issue—default parameters ensure that a two-day long branch of blocks can be reorganised (for more details on reorganisations see Sect. 2.1.3), which should be more than sufficient in real setting. If more blocks need to be reorganised, the blockchain needs to be re-downloaded in order to validate the new branch.

3.4 Redactable Blockchain

A very recent concept of a redactable blockchain allows making au- thorised modifications to the data stored in a blockchain. [39] Such modifications include change, deletion, compaction or even insertion of data. All while maintaining correct hash chains among both blocks and transactions. Redactable blockchains leverage a special class of hash functions called chameleon hash functions. Under normal circumstances they be- have as standard cryptographic hash functions. Nevertheless, chame- leon hash functions are built on top of a secret key. This key allows its holder to easily generate collisions, i. e., to make changes in data and find the same hash for them as was the original. The holdermay be either a centralised entity or a fixed set of independent entities (in this case, the redaction would be done within a secure multiparty computation). However, general reception of this proposal in cryptocurrency com- munity is rather negative [40], because it introduces trusted elements into the blockchain concept, which is in contrary with the original properties of blockchains.

3.5 Mini-blockchain

Mini-blockchain [41] is a technology derived from a standard block- chain (as defined earlier in Sect. 2.1) and it is used, e. g., in a cryptocur-

16 3. State of the Art

rency Cryptonite [42]. Its goal is to reduce impact of blockchain bloat on users and to this problem related long synchronisation times. Mini-blockchain system is composed of 3 components: a proof chain, a mini-blockchain and an account tree. A proof chain is a mini- malist chain—it is formed by block headers of the mini-blockchain, but without any block header pruned, i. e., all since the very first block. Burden put on users by requiring them to maintain a copy of a proof chain is therefore minimal in comparison with the standard blockchain. A mini-blockchain itself is formed from standard blocks of trans- actions. However, only a limited number of blocks is stored by nodes. In Cryptonite, this number is 10,000, corresponding to a period of one week. All excessive blocks are meant to be deleted. This would allow Cryptonite to maintain a dynamic upper limit on size of individual blocks, unlike static limits in most other cryptocurrencies. However, automatic block removal is not yet implemented in Cryptonite as of 2017, although during the initial mini-blockchain download only the last 10,000 blocks are obtained. Transactions are fundamentally different in mini-blockchain sys- tems from those in Bitcoin. The concept of a transaction has been very simplified. While there are still used digital signatures for authorising transfers, the whole scripting facility is removed, making transactions explicit transfers from a set of accounts to a different set of accounts. Such a simplification enables the creation of the concept ofan account tree. From a data structure point of view, an account tree is a Patricia prefix trie. Keys in this tree are account identifiers, while values are account balances and their withdrawal limits. Nonetheless, for this work only balances are of any interest. Balances may never be negative and empty accounts (i. e., those with zero balances) are automatically deleted from the tree. An account is created by receiving funds. On the other hand, this brought a new challenge—transaction replay attack. Since transactions move money between accounts, they could be replayed to repeat the transfer as long as the source account contains (at least) the transferred amount of money. This attack could happen at least every time a block with the transaction is deleted, wherefore nodes could not detect it being replayed.

17 3. State of the Art

To alleviate this major attack vector, every transaction is made with “expiration date.” This “date” is simply a current block number + k, where k is a number smaller than the number of blocks every node is required to store (i. e., 10,000). A transaction is valid only if it is included in a block with number less or equal than the expiration date of the transaction.

3.6 UTXO Set Commitment

Commitment of the UTXO set is a technique that in commits current state of the UTXO set. It is a redundant confirmation for nodes that they have the same UTXO set data as the rest of the network.

3.6.1 Commitment Creation To produce a UTXO set commitment the UTXO set first needs to be serialised—each UTXO is therefore placed into a Merkle tree. The Merkle tree is constructed in the same way as the Merkle tree for transactions. The root hash of this UTXO Merkle tree then constitutes the UTXO commitment.

3.6.2 Applicability of UTXO Commitment for Blockchain Size Reduction If the commitments are placed by block creators in a standard way into a blockchain and properly enforced by the network, it may be leveraged for various purposes. Any node can request a UTXO set for any point in history and verify whether the received data are valid, given that the particular block is deep enough in the longest chain. No other historical data are needed for this process. This may lead to a significant improvement over pruning with UTXO set as described in Sect. 3.3. Nodes would no longer need to download full blockchain history – only the chain of block headers, the UTXO set and the most recent number of blocks. There is one notable consideration regarding security of nodes relying on UTXO set commitments. By not verifying the whole block- chain, a node has no guarantee to be on a valid chain with respect to the node’s set of consensus rules. There might have been, e. g., a block

18 3. State of the Art

exceeding its size limit or a transaction spending more money on its output than there was on its input. These cases cannot be detected by said nodes. Nonetheless, this issue can be viewed as a special case of a 51% attack. Under this attack it is possible for an attacker to take over the blockchain if they possesses more than a half of overall com- putational power (see Sect. 2.1.2). Also, if there is another conflicting blockchain branch with greater length, it can be easily detected. Another potential issue is that in a network of nodes using this kind of pruning by default, there can be expected only a limited num- ber of nodes storing deeper blockchain history. Also, these nodes are potentially susceptible to DoS attacks. An attacker could keep request- ing UTXO sets for different points in blockchain history. Since typically only the current UTXO set is stored, every historical set needs to be computed ad-hoc by reversing all blocks that are on top of the one for which UTXO set is requested.

3.7 Merged Mining

Small cryptocurrencies generally face a challenge of low amount of mining power and thus a risk of the 51% attack (for details see Sect. 2.1.2), which might render the cryptocurrency useless or untrustwor- thy during the attack. There are two main possible solutions. A cryptocurrency may choose to implement an exotic and/or particularly expensive proof-of- work function to make such attacks more costly. Another possibility is to reuse mining power of another cryptocurrency. Miners then can opt into mining both of them. Merged mining was first used in a cryptocurrency called . The main goal of deploying merged mining was to solve fluctuation of miners between Namecoin and Bitcoin depending on their profitability at each moment, which was causing issues with bursts of blocks when profitability was high and very sparse blocks when profitability was negative compared to Bitcoin. [43] On the other hand, merged mining might contribute to central- isation risks. [44] Each deployment should be therefore carried out carefully.

19 3. State of the Art

In merged mining, there is always one main (“parent”) cryptocur- rency to which other (“auxiliary”) cryptocurrencies are tied. Hash of an auxiliary cryptocurrency block is placed into the coinbase transac- tion of the parent cryptocurrency (for details on coinbase transaction, see Sect. 2.3.1). The parent cryptocurrency block is then the one mined. When a miner finds a hash of the parent block that satisfies proof- of-work requirements of the auxiliary cryptocurrency (it may or may not satisfy these requirements of the parent cryptocurrency), the par- ent cryptocurrency block header is attached to the auxiliary cryptocur- rency block as a proof. [45]

3.7.1 Double Proof Attack It can be easily seen that merged-mined auxiliary cryptocurrencies are susceptible to attacks against their parent cryptocurrency blockchains. Moreover, merged mining poses a new challenge: double proof attack. Under this attack, attacker creates a chain of blocks in the auxiliary cryptocurrency and merged-mines all of them at once with the same mining power. There are two known countermeasures [46]. One is to prohibit reuse of the proof for more than one block. The second one is more complicated, but does not require checking of proofs of previous blocks. The auxiliary cryptocurrency may explicitly specify position of its block hash within the set of all merged-mined cryptocurrency hashes. This may be both given as a fixed position or as a pattern (formula).

20 4 Aims of the Thesis

Main motivation of this thesis is to enhance decentralised nature of blockchain-based systems—primarily cryptocurrencies. I focus on two most urgent subareas: enabling trustless exchange of cryptocurren- cies without any third parties and a scheme for upper-bounded-size blockchain.

4.1 Objectives and Expected Results

4.1.1 Trustless Exchange of Cryptocurrencies There are hundreds of cryptocurrencies, but only a handful of ex- change services where these cryptocurrencies can be traded. Each of them impose certain restrictions on registration of new users and on accounts of existing users. Centralisation places an artificial limitation on otherwise decentralised cryptocurrency ecosystem. My goal in this area is to develop a set of network and cryptocur- rency protocols for safe decentralised trading of different cryptocur- rencies. Practicality of the chosen approach will be shown with an implementation of a decentralised P2P platform for safe trading of cryptocurrencies directly between participants—without any interme- diary holding their money.

4.1.2 Blockchain with Upper-bounded Size Blockchains—especially those of Bitcoin and —are grow- ing fast in size, causing an increasing burden for the blockchain data download and verification; both in time, and network and computa- tional resources. As a result, less users can afford to run a node with full blockchain. My aim is to devise a scheme that would allow a blockchain to keep its total size below a certain limit under any circumstances. This scheme shall not introduce any new requirements on trust while main- taining the original scripting capabilities as they are present in Bitcoin. Since this will be a decentralised system, a proper functioning will depend on right incentives for system participants. I will conduct a

21 4. Aims of the Thesis

study on incentives already existing in Bitcoin with respect to the new system. Incentives broken in the new settings will be modified or re- placed so that a balanced system is maintained. Apart from incentives themselves, important role will be played by analysis of possible attack vectors. The proposal will include appropriate counter-measures and their justification.

4.2 Plan of Work

Spring 2018 ∙ Formalisation of the hash reduction proposal. Submitting a pub- lication to Crypto Valley Conference on Blockchain Technology (CVCBT), IEEE.

∙ Work on archive blocks.

∙ Thesis proposal defence and state doctoral exam.

Autumn 2018 ∙ Developing an improved variant of merged mining, better suited for this work.

∙ Finalising work on archive blocks.

∙ Submitting a publication to the journal Ledger or Future Gener- ation Computer Systems.

∙ Working out expiration of transactions.

Spring 2019 ∙ Developing incentives for keeping the system functioning with- out central interventions.

∙ Implementing a prototype of the upper-bounded blockchain scheme.

∙ Writing the Ph.D. thesis.

22 4. Aims of the Thesis

Autumn 2019 ∙ Exploring further possible optimisations.

∙ Finishing the prototype.

∙ Finishing the Ph.D. thesis.

Spring 2020 ∙ Submitting the Ph.D. thesis. Defence.

23 5 Achieved Results

5.1 Decentralisation of Cryptocurrency Exchange

Decentralised exchange depends on two major parts: an efficient way of communication and the actual exchange process. The platform fails if either of these cannot be accomplished in a decentralised fashion. Currently, a P2P overlay network has already been designed and published (see Chap. 6), followed by a publication on a 2-party cryp- tocurrency protocol allowing safe exchange of cryptocurrencies. Since 2017 I manage a team of students who work on an imple- mentation of the protocols into an application called Coincer. [47]

5.1.1 P2P Overlay with Efficient Communication For the communication part, we aimed for a peer-to-peer approach. However, during a design phase of the decentralised exchange plat- form, we found out lack of available designs of suitable P2P overlays to carry out communication among peers. The goal was to deliver all messages through the overlay efficiently, so that the network could scale with number of users, yet sustain sudden departures of peers. The P2P overlay we developed has comparable properties as the overlay used in cryptocurrencies—it allows dissipation of messages throughout the whole network while maintaining a certain level of privacy (message originator is not known). On top of that, it is capable to efficiently deliver messages between any two peers over the overlay without direct connection between them.

5.1.2 Two Party Cryptocurrency Protocol The main functionality of the platform is trustless exchange of various cryptocurrencies directly between users—without involvement of any intermediary or trusted third party. Using state-of-the-art scripting capabilities of cryptocurrencies we designed a cryptocurrency protocol that in an elegant way fulfils described goals. Unlike its predecessors, this protocol is secure even in real settings. It gives participants a guarantee that their money is

24 5. Achieved Results

always in their hands or locked in a trade, from which they cannot be stolen.

5.2 Scheme of Sustainable Blockchain

Work in this area, motivated in Chap. 1, is developed around two observations. The first one is that most of the data stored in block- chains are not needed for their core functionality (i. e., facilitating value transfers in cryptocurrencies). The second observation is that there are many transactions in unspendable state [48, 30] (this issue is described in better details in Sect. 2.6), therefore only consuming available resources. When these two observations are combined with constrained block- chain growth (which is the standard in cryptocurrencies), we can obtain a scheme with upper-bounded blockchain size. Similarly as in mini-blockchain (see Sect. 3.5) we can discard all blocks of age beyond a certain threshold. However, unlike the mini- blockchain, here we want to preserve the versatility of standard cryp- tocurrency transactions—the scripting facility. Therefore, a new ap- proach is needed. An inspiration can be drawn from UTXO commit- ments (see Sect. 3.6) while improving on resources requirements. In- stead of maintaining a running commitment, we create a special archive block that will contain all unspent outputs from k blocks which it re- places. This archive block follows most rules that already apply on normal blocks, with an addition of several new ones:

∙ it requires substantially more computational power to mine1,

∙ it is referenced from standard block headers,

∙ it does not mine any new money, and

∙ it always references the genesis block.

1. This is not an issue; standard and archive block may be mined simultaneously with the same computational power. As a result, archive block takes much longer to mine, which is desirable. To achieve this, merged mining can be used (see Sect. 3.7) with some additional improvements.

25 5. Achieved Results

G 1 2 k k+1 k+2 (a) Before creation of an archive block.

G archive block ? k+1 k+2 k+3

(b) After creation of an archive block and a block k + 3.

Figure 5.1: Creation of an archive block in place of blocks 1 to k in a time span between blocks k + 2 and k + 3 in a way that chaining of blocks is preserved.

To form a chain, the archive block includes a hash of the last block it archives. Security of archive blocks is maintained by the proof-of-work mech- anism and longest-chain property (see Sect. 2.1.1). Therefore, the attack surface is at least comparable with standard cryptocurrencies. Next to the archive blocks, that conserve space by discarding no more needed data, we employ limitation on the lifespan of transaction outputs (definition of which is in Sect. 2.3). This way we ensure that unspendable outputs (including those provably unspendable as well as outputs, whose recipients lost the ability to spend them, e. g., by losing their private keys) will be stored only for a finite amount of time. Put together, these two proposals guarantee that the blockchain size will be maintained below a certain upper bound M:

M = (tutxo/tblocks) * (sblock − sheader) + (cab + cnot_archived) * sblock Where:

∙ tutxo – maximum lifetime of unspent transaction outputs (in seconds)

∙ tblocks – average interval between individual blocks (in seconds)

∙ sblock – maximum size of a single block (in bytes)

∙ sheader – normal block header size (in bytes)

26 5. Achieved Results

∙ cab – average interval between archive blocks (in number of normal blocks)

∙ cnot_archived – average interval between archive blocks (in number of normal blocks)

In M we assume that no transactions are spent – only those that would expire anyway – and blocks are full, i. e., the worst-case scenario.

5.3 Hash Reduction

Since a complementary goal is to reduce blockchain size, it is worth exploring possible optimisations in the stored data themselves. Cryptocurrency transactions form a directed acyclic graph by ref- erencing other transactions with their hash (in inputs). Here the hash serves only a purpose of a unique identifier—nothing cryptographi- cally significant. For instance in Bitcoin, typical small transaction contains 1 input and 2 outputs. That means one 32B hash—14% of the transaction size. Large transactions may contain tens of inputs – in such transactions hashes-identifiers make up around 20% of the transaction size. Since the purpose of these hashes is only to uniquely identify transactions, we can replace them with anything that preserves this property. What we propose is a unique prefix of the hash. Length of the prefix is such that the transaction can still be unambiguously identified by the reduced hash. When applied on first 100,000 blocks of the bitcoin blockchain, which are 57MiB in total (i. e., relatively small with a small number of transactions), we can achieve reduced size 52.4MiB which is 8% smaller than the original blockchain. With more transactions and bigger transactions (due to money fragmentation) we expect reduction ratio to further grow, making this a worthy optimisation. In order to create transactions with reduced hashes, users need to know the existing set of unspent outputs (UTXO set). Otherwise the network protocol would have to be extended to support query- ing nodes for UTXOs matching a certain prefix. This seems to bean acceptable compromise for the benefits of reduced hashes.

27 5. Achieved Results

Nevertheless, hash reduction is backward compatible. If there is a need to create a transaction with a full hash, it is still possible—the prefix would be simply set to the full length of the hash. Hash reduction may be implemented separately to increase the number of transactions that fit into a single block. Furthermore, com- bination with archive blocks and lifespan limitation of transaction outputs can be either leveraged to bigger total capacity of such sys- tem or to decrease overall storage requirements without negatively affecting the number of transactions the system could process.

28 6 Author’s Publications

∙ ZIMA, Michal. Coincer: Decentralised Trustless Platform for Exchang- ing Decentralised Cryptocurrencies. In Zheng Yan, Refik Molva, Wojciech Mazurczyk and Raimo Kantola. Network and System Security. Springer International Publishing, 2017. p. 672–682, 11 pp. ISBN 978-3-319-64700-5 978-3-319-64701-2. doi:10.1007/978- 3-319-64701-2_53.

∙ ZIMA, Michal. Sending Money Like Sending E-mails: Cryptoad- dresses, The Universal Decentralised Identities. In Jan Bouda, Lukáš Holík, Jan Kofroň, Jan Strejček and Adam Rambousek. Proceed- ings 11th Doctoral Workshop on Mathematical and Engineering Meth- ods in Computer Science, Telč, Czech Republic, 21st–23rd October 2016. Open Publishing Association, 2016. p. 52–60, 9 pp. ISSN 2075- 2180. doi:10.4204/EPTCS.233.5.

∙ ZIMA, Michal and HLADKÁ, Eva. Cryptography Enhanced Ad- Hoc Approach to P2P Overlays. In Waleed W. Smari. Proceedings of the 2016 International Conference on High Performance Computing & Simulation. IEEE, 2016. p. 517–522, 6 pp. ISBN 978-1-5090-2086-7. doi:10.1109/HPCSim.2016.7568378. My contribution was 95%. I authored most of the proposal and of the text. I was also the presenting author at the conference.

29 Bibliography

1. CHAUM, David; FIAT, Amos; NAOR, Moni. Untraceable electronic cash. In: Proceedings on Advances in cryptology. Springer-Verlag New York, Inc., 1990, pp. 319–327. Available from DOI: 10.1007/0-387- 34799-2_25. 2. PAYPAL HOLDINGS, INC. PayPal Reports Fourth Quarter and Full Year 2016 Results [online]. 2017 [visited on 2017-07-31]. Available from: https://investor.paypal-corp.com/releasedetail.cfm? ReleaseID=1009339. 3. VISA INC. Annual Report 2016 [online] [visited on 2017-07-31]. Avail- able from: http://s1.q4cdn.com/050606653/files/doc_financials/ annual/Visa-2016-Annual-Report.pdf. 4. COINMARKETCAP, LLC. Bitcoin (BTC) price, charts, market cap, and other metrics [online] [visited on 2018-01-12]. Available from: https: //coinmarketcap.com/currencies/bitcoin/. 5. PARKER, Luke. Bitcoin ‘spam attack’ stressed network for at least 18 months, claims software developer. New Coin [online]. 2017 [visited on 2018-01-12]. Available from: https://bravenewcoin. com/news/bitcoin- spam- attack- stressed- network- for- at- least-18-months-claims-software-developer/. 6. ANDRESEN, Gavin. BIP 101: Increase maximum block size [online]. 2015 [visited on 2017-12-18]. Available from: https : / / github . com / bitcoin/bips/blob/master/bip-0101.mediawiki. 7. GARZIK, Jeff. BIP 102: Block size increase to 2MB [online]. 2015 [visited on 2017-12-18]. Available from: https://github.com/bitcoin/ bips/blob/master/bip-0102.mediawiki. 8. WUILLE, Pieter. BIP 103: Block size following technological growth [on- line]. 2015 [visited on 2017-12-18]. Available from: https://github. com/bitcoin/bips/blob/master/bip-0103.mediawiki. 9. T.KHAN. BIP 104: ’Block75’ – Max block size like difficulty [online]. 2017 [visited on 2017-12-18]. Available from: https : / / github . com / bitcoin/bips/blob/master/bip-0104.mediawiki.

30 BIBLIOGRAPHY

10. BTCDRAK. BIP 105: Consensus based block size retargeting algorithm [online]. 2015 [visited on 2017-12-18]. Available from: https:// github.com/bitcoin/bips/blob/master/bip-0105.mediawiki. 11. CHAKRABORTY, Upal. BIP 106: Dynamically Controlled Bitcoin Block Size Max Cap [online]. 2015 [visited on 2017-12-18]. Available from: https://github.com/bitcoin/bips/blob/master/bip- 0106. mediawiki. 12. SANCHEZ, Washington Y. BIP 107: Dynamic limit on the block size [online]. 2015 [visited on 2017-12-18]. Available from: https:// github.com/bitcoin/bips/blob/master/bip-0107.mediawiki. 13. LOMBROZO, Eric; LAU, Johnson; WUILLE, Pieter. BIP 141: Segregated Witness (Consensus layer) [online]. 2015 [visited on 2017-12-18]. Avail- able from: https://github.com/bitcoin/bips/blob/master/bip- 0141.mediawiki. 14. NAKAMOTO, Satoshi. Bitcoin: A Peer-to-Peer Electronic Cash System [online]. 2008 [visited on 2016-12-30]. Available from: https://www. bitcoin.org/bitcoin.pdf. 15. Bitcoin Address 1BitcoinEaterAddressDontSendf59kuE [online] [visited on 2017-11-06]. Available from: https://blockchain.info/address/ 1BitcoinEaterAddressDontSendf59kuE. 16. MOORE, Tyler; CHRISTIN, Nicolas. Beware the Middleman: Empiri- cal Analysis of Bitcoin-Exchange Risk. In: HUTCHISON, David et al. (eds.). Financial Cryptography and Data Security. Berlin, Heidelberg: Springer Berlin Heidelberg, 2013, vol. 7859, pp. 25–33. ISBN 978-3- 642-39883-4 978-3-642-39884-1. Available from DOI: 10.1007/978- 3-642-39884-1_3. 17. ZIMA, Michal. History of Cracks [online] [visited on 2017-11-22]. Avail- able from: https://www.coincer.org/history-of-cracks/. 18. WILCOX, Zak. Proving Your Bitcoin Reserves [online]. 2014 [visited on 2017-12-17]. Available from: https://iwilcox.me.uk/2014/ proving-bitcoin-reserves.

31 BIBLIOGRAPHY

19. DAGHER, Gaby G.; BÜNZ, Benedikt; BONNEAU, Joseph; CLARK, Jeremy; BONEH, Dan. Provisions: Privacy-preserving Proofs of Sol- vency for Bitcoin Exchanges. In: [online]. ACM Press, 2015, pp. 720– 731 [visited on 2017-12-16]. ISBN 978-1-4503-3832-5. Available from DOI: 10.1145/2810103.2813674. 20. TIERNOLAN. Re: Alt chains and atomic transfers [online]. 2013 [visited on 2017-12-17]. Available from: https://bitcointalk.org/index. php?topic=193281.msg2224949#msg2224949. 21. ROSENFELD, Meni. Analysis of hashrate-based double spending. arXiv preprint arXiv:1402.2009 [online]. 2014 [visited on 2017-03-30]. Available from: https://arxiv.org/abs/1402.2009. 22. GRUNSPAN, Cyril; PÉREZ-MARCO, Ricardo. Double spend races. CoRR. 2017, vol. abs/1702.02867. Available also from: http://arxiv. org/abs/1702.02867. 23. EYAL, Ittay; SIRER, Emin Gün. Majority is not enough: Bitcoin mining is vulnerable. In: International Conference on Financial Cryptography and Data Security [online]. Springer, 2014, pp. 436–454 [visited on 2016-12-03]. Available from: http://link.springer.com/chapter/ 10.1007/978-3-662-45472-5_28. 24. KIAYIAS, Aggelos; KOUTSOUPIAS, Elias; KYROPOULOU, Maria; TSELEKOUNIS, Yiannis. Blockchain mining games. In: Proceedings of the 2016 ACM Conference on Economics and Computation [online]. ACM, 2016, pp. 365–382 [visited on 2016-12-03]. Available from: http://dl.acm.org/citation.cfm?id=2940773. 25. ANTONOPOULOS, Andreas M. Mastering Bitcoin. First edition. Se- bastopol CA: O’Reilly, 2015. ISBN 978-1-4493-7404-4 978-1-4919- 0260-8. 26. MERKLE, Ralph C. Method of providing digital signatures. US Patent 4309569. 1982-01. 27. BITCOIN PROJECT. Coinbase, Coinbase Field [online] [visited on 2018-01-19]. Available from: https://bitcoin.org/en/glossary/coinbase. 28. BITCOIN WIKI. Script [online] [visited on 2017-03-11]. Available from: https://en.bitcoin.it/wiki/Script.

32 BIBLIOGRAPHY

29. BLOOM, Burton H. Space/time trade-offs in hash coding with allow- able errors. Communications of the ACM. 1970, vol. 13, no. 7, pp. 422– 426. ISSN 00010782. Available from DOI: 10.1145/362686.362692. 30. DELGADO-SEGURA, Sergi; PÉREZ-SOLA, Cristina; NAVARRO-ARRIBAS, Guillermo; HERRERA-JOANCOMARTI, Jordi. Analysis of the Bit- coin UTXO set. In: International Conference on Financial Cryptography and Data Security (to appear). 2018. 31. ROBERTS, Jeff John; RAPP, Nicolas. Exclusive: Nearly 4 Million Bit- coins Lost Forever, New Study Says. Fortune [online]. 2017 [visited on 2017-12-27]. Available from: http://fortune.com/2017/11/25/ lost-bitcoins/. 32. BITCOIN WIKI. OP_RETURN [online] [visited on 2017-12-27]. Avail- able from: https://en.bitcoin.it/wiki/OP_RETURN. 33. KARRER, Manfred. Bisq – The peer-to-peer bitcoin exchange [online]. 2016 [visited on 2017-12-26]. Available from: https://github.com/bisq- network/docs/blob/master/exchange/whitepaper.adoc. 34. KOMODO PLATFORM WIKI. MultiGateWay [online] [visited on 2017-12-26]. Available from: https://wiki.komodoplatform.com/wiki/MultiGateWay. 35. LEE, Jordan. Blocks & Chains . Available also from: https : / / bcexchange . org / assets / Blocks _ & _ Chains _ Decentralized_Exchange.pdf. 36. BITCOIN WIKI. Transaction Malleability [online] [visited on 2016-12-03]. Available from: https : / / en . bitcoin . it / wiki / Transaction _ Malleability. 37. Bitcoin Core [online] [visited on 2018-01-12]. Available from: https: //bitcoincore.org/. 38. BITCOIN PROJECT. Block file pruning [online]. 2015 [visited on 2017-03-10]. Available from: https://bitcoin.org/en/release/v0.11.0# block-file-pruning. 39. ATENIESE, Giuseppe; MAGRI, Bernardo; VENTURI, Daniele; AN- DRADE, Ewerton R. Redactable Blockchain – or – Rewriting History in Bitcoin and Friends. In: 2017 IEEE European Symposium on Secu- rity and Privacy, EuroS&P 2017, Paris, France, April 26-28, 2017. 2017, pp. 111–126. Available from DOI: 10.1109/EuroSP.2017.37.

33 BIBLIOGRAPHY

40. MCCURTIS, Brian. “Redactable Blockchains” are not Blockchains! [online]. 2017 [visited on 2017-12-31]. Available from: https://medium.com/ brian-mccurtis/redactable-blockchains-are-not-blockchains- 914b91569e62. 41. BRUCE, J. D. The mini-blockchain scheme [online]. 2014 [visited on 2016-12-17]. Available from: http://cryptonite.info/files/mbc- scheme-rev2.pdf. 42. MINI-BLOCKCHAIN PROJECT. Cryptonite [online] [visited on 2016-12-17]. Available from: https://www.cryptonite.info/. 43. WIRDUM, Aaron van. Why Bcash Mining Shouldn’t Affect Bitcoin Much (But Bitcoin Mining Could Ruin Bcash). [online]. 2017 [visited on 2017-12-03]. Available from: https:// bitcoinmagazine.com/articles/why-bcash-mining-shouldnt- affect-bitcoin-much-bitcoin-mining-could-ruin-bcash/. 44. VOYIATZIS, Artemios G.; WEIPPL, Edgar. Merged Mining: Curse or Cure? In: Data Privacy Management, Cryptocurrencies and Blockchain Technology: ESORICS 2017 International Workshops, DPM 2017 and CBT 2017, Oslo, Norway, September 14-15, 2017, Proceedings. Springer, 2017, vol. 10436, p. 316. 45. BITCOIN WIKI. Merged mining specification [online] [visited on 2017-12-03]. Available from: https://en.bitcoin.it/wiki/Merged_mining_ specification. 46. BITCOIN WIKI. Alternative chain [online] [visited on 2017-12-03]. Avail- able from: https://en.bitcoin.it/wiki/Alternative_Chain. 47. ZIMA, Michal. Coincer [online] [visited on 2017-12-07]. Available from: https://www.coincer.org/. 48. BARTOLETTI, Massimo; POMPIANU, Livio. An Analysis of Bitcoin OP_RETURN Metadata. In: BRENNER, Michael et al. (eds.). Finan- cial Cryptography and Data Security: FC 2017 International Workshops, WAHC, BITCOIN, VOTING, WTSC, and TA, Sliema, Malta, April 7, 2017, Revised Selected Papers. Cham: Springer International Publish- ing, 2017, pp. 218–230. ISBN 978-3-319-70278-0. Available from DOI: 10.1007/978-3-319-70278-0_14.

34 A Publications

This part of my thesis proposal includes a selection of my published papers.

35 Cryptography Enhanced Ad-Hoc Approach to P2P Overlays

Michal Zima Eva Hladka´ Faculty of Informatics Faculty of Informatics Masaryk University Masaryk University Brno, Czech Republic Brno, Czech Republic E-mail: xzima1@fi.muni.cz E-mail: eva@fi.muni.cz

Abstract—We address the problem of a secure direct com- The remainder of this paper is organised as follows. Section munication of two arbitrary peers in a P2P network without II presents previous work related to the problem. In Section III knowing each other’s IP addresses. An efficient solution to this we discuss in more details general requirements on our over- problem will provide a practically usable way of communication to privacy-sensitive P2P applications. Traditionally, P2P archi- lay, with elaboration on the actual overlay design in Section IV. tectures view this problem as a problem of mutual anonymity Section V discusses how the proposed overlay behaves when of a message sender and receiver, but usual solutions suffer it is under different kinds of attacks. An example of a real- from various inefficiencies or complexities. By looking at the world application being built on top of our work is presented problem from a perspective of an ad-hoc network, we are able in Section VI. Section VII provides final conclusions. to apply a familiar approach of multihop communication and ad-hoc routing algorithms to a P2P overlay. Introduced usage of a public key as a node’s identifier adds further security features, II.RELATED WORK including data integrity through digital signatures, or end-to-end encryption. Proposed P2P overlay has been successfully used for There are several different approaches to anonymous P2P building a decentralised cryptocurrency exchange Coincer. overlays. One common approach is to form groups of peers within which messages are delivered via broadcast to achieve 5 I.INTRODUCTION anonymity of their receiver, as in P [3] or Hordes [4]. Similarly, for anonymity of a sender a probabilistic forwarding Many applications need arbitrary two peers to be able is used in Crowds [5]. In every step a forwarding peer to communicate with each other, nonetheless some of them randomly decides with a given probability whether to forward extend this requirement to also minimising a risk of exposure the message to another randomly-chosen forwarding peer or of peers’ IP addresses (identities). The motivation might be whether to deliver it to its final destination. AP3 [6] further just to tackle privacy concerns or to prevent targeted attacks uses this method to build anonymous channels for accessing against users of the application. In our case, we develop a Pastry DHT [7]. decentralised exchange of cryptocurrencies: Coincer [1]. By A similar approach to broadcasting is the usage of epidemic hiding IP addresses we want to provide users with a similar (or gossip) protocols. MuON [8] achieves higher bandwidth level of privacy as cryptocurrencies usually offer. Moreover, efficiency while preserving the level of anonymity of broad- as Coincer’s trading protocol may span from tens of minutes casting. (due to inherent properties of the cryptocurrencies in order to Another extensively used approach is onion routing [9]. maintain security of the trade) up to several hours (depending A-Kad [10] adds anonymity to the Kademlia overlay [11]. on degree of cooperation between the respective users) it In A-Kad a peer sets up anonymous channels using onion is very beneficial to conceal IP addresses of peers, since it routing over chosen sets of onion routers. Subsequently, they hinders efforts of attackers to prevent their trading partner from uses these channels for publishing information into DHT. A finishing the trade or even directly attacking them. peer who wants to obtain a resource they found via DHT In this paper we propose a simple unstructured anony- then communicates with the resource provider over these mous P2P overlay with efficient communication. We treat anonymous channels, thence neither of them knows the other an unstructured P2P network as an ad-hoc network. Hence, peer’s identity. we modify for this purpose a simple ad-hoc routing algo- Pecan [12] further improves onion routing by relaxing a rithm DSDV [2], which provides the overlay with an any- requirement to establish circuits before a communication can to-any anonymous communication channel with low setup, take place. A sender chooses for every request two sets of maintenance and communication overhead. By using space routers—one for delivering the request itself and one for efficient elliptic curve cryptography (ECC) public keys as peer anonymous routing of the response. The responding peer identifiers we obtain security against message tampering and therefore receives with the request also information necessary ability to establish end-to-end encrypted channels. for delivering the response. The issue with onion routing is a requirement for a peer the user to be attacked. Therefore, we strengthen our former to know routers in the network in order to either establish requirement of anonymity in the network also to anonymity circuits or to select path for their packets (in the case of Pecan). towards neighbours. Not only there is reliance on central directory server, but the communication is also sensitive to churn. To improve these B. Efficient Communication Between Peers properties while avoiding overhead of broadcast in a mutually Generally, communication in a P2P network can be divided anonymous 2-party communication we employ features of ad- into two categories: globally-relevant and private. Messages hoc routing algorithms DSDV [2] and Babel [13]. belonging to the globally-relevant category define and main- DSDV is a simple loop-free routing algorithm. Although tain the state of the network (e.g., market orders in Coincer), not designed for anonymous communication, it well handles while private messages are part of a communication between communication between any two nodes by maintaining infor- two specific peers, which includes transmission of a file in a mation what is a next hop on the shortest path towards each file sharing application or an execution of a cryptocurrency other node. Babel enhances DSDV and other ad-hoc routing trade in Coincer. Based on this division we also distinguish protocols and for usage in overlay network it replaces TTL- between ways each of these two categories is delivered over based routing metric with a delay-based routing metric [14]. the network: while globally-relevant can be broadcast (or, Aside from anonymity features, we improve in our routing more efficiently, disseminated by a gossip protocol), flooding algorithm the usage of inherently present redundancy and try the network with private messages addressed to a single to minimise communication overhead. peer is not only very inefficient (although it is indeed very anonymous), but also forms a scalability bottleneck for the III.OUR REQUIREMENTS network. Therefore, we seek for a more ingenious routing Motivated by our application, a cryptocurrency exchange, mechanism for the purpose of direct communication between we impose several requirements we want the P2P overlay to peers. accomplish. First, a connection between a peer’s identifier and their IP address must not be made known—not even to peer’s C. Possibility of Full Participation neighbours if possible. Thereby users will experience up to P2P overlays often rely on the ability of peers to receive the same level of privacy as in cryptocurrencies themselves. incoming connections from the Internet, otherwise they cannot Second, even under this condition, we still need a way for fully participate in the overlay and their resource utilisation is unicast-like communication between any two peers with any of limited (e.g., in file sharing overlays). However, in real world them being able to initiate the communication. Third, we want there are many users for whom this assumption is not true, to be as efficient in message delivery as possible, therefore be it for any possible reason—a NAT due to a lack of IPv4 eliminating a highly anonymous, but also very inefficient addresses, a restrictive firewall, or other potential cause. broadcasting mechanism. Fourth, for Coincer it is important Our goal is therefore to ensure that any peer can initiate that any user is able to participate in the network, even if they communication with any other peer without limitations or a is behind a NAT. Fifth, a P2P network witnesses continuous need for explicit path-building. This requirement also includes churn. On the other hand, its topology is implicitly redundant all peers connecting to the network via Tor or other proxy which is desirable to use for improving reliability. And finally, networks. as a network of unknown nodes forms an inherently untrust- worthy environment, we need reasonable ways for operating D. Redundancy in such an environment. Churn belongs to natural phenomena of P2P networks. Peers In this section we elaborate on these requirements. join and leave the network or just change their location within it. While graceful departures are usually preceded by notices A. Anonymity of Peers and the network can adjust its paths, sudden disconnections Disconnecting peer’s identifier from their IP address servers of peers, e.g., because of a failure of the underlying network two basic goals. First, it is unlinkability of information or infrastructure, take time to detect and recover from, causing actions to their real originator, which includes resource pos- broken routes and local disruptions of the overlay operation. session, its provision or retrieval. It provides privacy to the P2P networks contain peers with multiple connections, user. Second, it hinders situation of an attacker, because they forming a mesh. This inherent redundancy can be leveraged for does not know who is who in the network and where. Beyond better routing resilience and fault-tolerant overlay connectivity, simple network attacks, a user of Coincer might be a target of therefore providing a quick recovery of overlay operation in a money heist which is significantly more difficult to execute case of any failure. when the attacker does not know victim’s IP address. In cryptocurrency networks it is usual that a user who IV. DESIGNOFTHE OVERLAY sends a transaction is indistinguishable from a user who only Unstructured P2P overlays resemble ad-hoc networks— forwards this transaction to other peers. This property ensures peers connect to the overlay at random points and there is that not even a direct connection of an attacker to their lack of any inner structure in the network, all peers are intended victim gives them the information that this is actually equivalent. In order to avoid reliance on the ability to receive new connections from other peers, we carry all communication participation is to be initiated by broadcasting a message, over existing connections among peers. Therefore, utilising an this message also serves the purpose of establishing routes. ad-hoc routing algorithm, messages are delivered on hop-by- However, for unicast-like communication, an announcement hop basis, similarly to IP packets. For redundancy, each peer of presence needs to be broadcast first, otherwise there will maintains a set of connections to the network. be only a single path back. Some approaches equip messages with a time-to-live (TTL) Each peer tracks announcements of presence (or first broad- field to limit potential flooding of the network. However, we cast messages) for each other peer. When a peer receives drop it, because this overlay uses either one-hop messages, such a message, they saves the information which neighbour messages supposed to reach all peers or messages routed forwarded it to them. Neighbours are sorted by the order in towards a single destination. Moreover, TTL is easy to spoof, which the message is received from them. This order also it creates problems with maintaining anonymity [15] and we specifies a priority for selection of a route when delivering already employ other ways for detecting repeated messages. a message to this peer. This way each peer in the network All messages routed through the overlay carry an identifier knows where to forward messages for any other active peer of their sender. However, any message sent only to a neighbour in the network, although they does not know neither the path (whose identifier is never known) does not contain neither the towards this peer, nor whether any of their neighbours is that identifier of sender, nor the identifier of receiver. Hence, when corresponding peer. a peer sends a message with their identifier, no neighbour can tell whether the peer is the sender or whether they just C. Loop-free Routing forwards the message. Under normal circumstances the routing protocol does not form loops. However, it is possible that the optimal route A. Joining breaks (e.g., some peer on the path leaves the network) and Before a node connects to the network, they generates a key the rest of routing information in the network causes messages pair. The public key is used as their identifier in the network. on this route to loop. We recommend a new identifier to be used every time a node Solutions of other algorithms vary. DSDV [2] broadcasts joins the network. However, if the application establishes long- information about broken route on every node departure, lasting interactions, the previous identifier may be required which ignores available redundancy in the network and might for finishing open interactions. In such cases more identifiers generate large amount of traffic on high churn. In contrast may be used at the same time, nonetheless only the newest is to that, Babel [13] uses short intervals between consecutive allowed to establish new interactions. announcements of presence as a preventive measure against Having an identifier, a node starts the following joining both loops and general disruption of routing. Nonetheless, procedure: incurred overhead may become nonnegligible when number 1) They establishes a connection to a node known to be in of peers in the network is high. the network. Our solution is based on loop detection and last resort 2) The node asks this new neighbour for a list of addresses reaction. In order to detect a loop, each peer maintains a of known nodes in order to update their database of set of last n hashes of messages they forwarded in the last possible peers to connect to. minute with information about which neighbour forwarded 3) They repeats the procedure until it has enough of out- it to them. If a peer detects a message repetition from a going connections. neighbour different from the first forwarder, they detected a Initial seed addresses, used by nodes that have never before loop. To remove the loop, the peer deletes their best route for connected to the network, can be for instance hard coded in given destination (which now contains a loop) and forwards the application, provided manually by the user, served over the message via the second best (which is now the first best) HTTP or obtained from DNS. If DNS is used, served records route. When a peer has no route left, they broadcast a request need to have sufficiently low TTL (of the order of minutes) so for announcement of presence. Therefore, if the peer is still that if none of provided nodes is alive, the DNS can be queried connected to the network, they will receive the request and again after a while for a different set of records without hitting respond to it (again via broadcast), which refreshes routing a cache. information among all peers. Note that if a message comes for a second time from the B. Routing same neighbour, it only says that the neighbour sent it again Ad-hoc networks use various routing algorithms, of which (and the message is ignored). If there was to be a loop, this we select as a base a proactive DSDV algorithm [2] as it neighbour is supposed to detect it first. best accomplishes our requirements and fits in with achieving anonymity of peers. Algorithm with our modifications follows. D. Routing Table Updates When a peer wants to start actively participating in the There is no mechanism in the proposed overlay that could in network, they needs to let the network know how to reach a short time detect unannounced departures of peers. Not even them. Until this moment they is only a passive peer gathering neighbours are able to detect it as the network cannot establish information about resources offered by other peers. If their connection between nodes and their identifiers. Therefore, all routing table entries are assigned an expiration time. Hence, key between respective peers without any extra communication if a peer wants to preserve routability of messages towards overhead [16]. Besides, keys of ECC schemes have the benefit them, they has to periodically rebroadcast their announcement of being small in size. of presence. This must be one ahead of the expiration time, otherwise the peer risks becoming unreachable. V. ATTACK VECTORS Expiration ensures that peers do not store stale records and utilise their resources in an efficient manner. In this section we present an analysis of attacks deployable E. Graceful Departure against proposed overlay. Disconnection of passive peers is trivial and no other peer in the network needs to take any action. On the other hand, active A. Man-in-the-Middle Attack peers who propagate their presence, leave information in other This is the most obvious attack vector as messages to distant peers’ routing tables and possibly also in application-specific peers are always sent via other peers and certain messages data structures. However, sending an announcement about are even broadcast to everyone. Any peer could therefore departure and consequently disconnecting from neighbours monitor contents of communication between particular peers may lead to backward anonymity breach and exposure of or even tamper with them. To prevent deliberate modifications relation between peer’s identifier and IP address. or random corruption of messages, all messages must include If the application conditions allow it, we suggest abandoning digital signatures. To provide confidentiality, end-to-end en- the conception of graceful departure in favour of increased cryption of contents is used. In order to bypass complicated anonymity of peers. Nonetheless, in applications that could key exchange procedures, peers use their public keys as their greatly benefit from early knowledge of peers’ departures, identifiers. Therefore, any peer is able to address any other especially in terms of resource saving, a peer broadcasts this peer and to start sending them encrypted messages right away, announcement in advance of their actual departure, therefore and everyone is also able to verify signature of every message. making the possibility of raising correlations less likely. To save bandwidth and processing power, corrupted mes- F. Peers Exchange sages are not forwarded, but instead immediately silently Usually, peers exchange IP addresses either of their current discarded. neighbours or of a subset of all nodes they know. Giving Depending on a particular application, a peer acting as away a list of peer’s neighbours is sensitive and potentially a , but in fact carrying out this attack, could exploitable information. Therefore, the list must not in any way be easily detected. Real parties can produce a proof using indicate which addresses are possibly the node’s neighbours. their unique knowledge or possession which is very hard or Similarly, a receiver of such a list needs to exercise caution: impossible for the attacker to forge. In our application, a to randomly reorder addresses on the list and combine data cryptocurrency exchange, this proof consists of a signature from several neighbours. of both parties’ identifiers by respective party’s “coins” (these are identified by public keys in cryptocurrencies). Hence, the G. Cryptography attacker is quickly uncovered and the attack thwarted. An anonymous overlay forms a very untrusted environment. For safe and reliable communication over it we include several B. Replay Attack cryptographic elements. First of all, we use public keys in place of peers’ identifiers. Consequently, as every message to While modifying messages is prevented by digital signa- be forwarded has to contain an identifier of its sender (note tures, attackers could still keep forwarded messages and send that messages for neighbours do not), public keys of all active them later to the network again. This might easily create false peers are implicitly distributed over the network to all peers. state of affairs in the network, with severity varying depending With key distribution secured, we require all messages on a particular application. carrying the sender’s identifier to be signed by their key To eliminate potential replay attacks, every message sent corresponding to their identifier. Consequently, all peers are within the network carries a nonce. The nonce must be a required to perform signature verification of each received positive ever-increasing number. This nonce is unique within message before its processing. If the verification fails, integrity messages sent by one specific peer. If a peer reuses their of the message has been corrupted and the message is therefore identifier across restarts, they also must remember the value silently discarded. Only messages with valid signatures are of their last used nonce. Otherwise, it might occur that if a allowed to be forwarded through the network. peer uses some nonces again then (a) their messages might be For any unicast-like communication of two arbitrary peers discarded by some peers (possibly even by all of them), or (b) we require it to be encrypted in end-to-end fashion. To avoid an attacker might carry out a replay attack against this peer. any complicated shared key agreement protocol we suggest For peers with new identifiers this problem does not arise. usage of elliptic curve cryptography (ECC) that is able to make We distinct two types of nonces with regards to importance use of a very elegant ECDH algorithm for establishing a shared of messages that carry them: 1) Message for Announcement of Presence: This is a very the consequences stated above). Nonetheless, at that moment special message, because it ensures routability within the the attacker gains very little from carrying out a Sybil attack network and reachability of peers. Therefore, its nonce needs also against Coincer itself. to be stored separately so that it is not accidentally pruned D. Denial of Service Attack with stale nonces of other messages. A Denial of Service (DoS) attack can have many forms. Repetition of this message from a neighbour that has already Generally, its goal is to prevent user(s) from achieving the sent it is ignored. Delaying of the announcement by some purpose of the application or network. We cover only a neighbours only causes these neighbours to be assigned the generic attack scenario from the overlay perspective—flooding lowest priority for route selection. the network—, i.e., leaving out any application-specific DoS 2) Other Messages: Both kinds of messages—those that are variations. broadcast to every peer and those belonging to a communica- Peers injecting excessive amount of messages into the tion with a specific peer only—may arrive out of order, i.e., network are consuming available resources in bad faith and in different order than they were originally sent. Therefore, it need to be expelled out of the network. If a peer receives is not sufficient to remember only the last nonce, because that too many messages from a particular neighbour, first they could easily cause discarding legitimate messages that arrived should either limit forwarding of these messages or even later than expected. filter them based on their importance for the network. If the Proposed solution is to store nonces of messages received neighbour continues flooding, the peer closes its connection in recent moments (in Coincer we use one minute), which to this neighbour. is sufficient for legitimate traffic and still keeps associated storage overhead in reasonable bounds. If a newly arrived VI.APPLICATION message has a nonce lower than the oldest nonce in the list, The application described in this section has been our it is discarded. If it is higher than the oldest nonce, but still original motivation for development of the P2P overlay de- lower than the last one, the message is accepted, but its nonce scribed in this paper. Our use case is a decentralised exchange is not stored at the end of the list as normally, but—in order for cryptocurrencies—Coincer [1]. It leverages cryptographic to maintain the ever-increasing property of the nonce list—in features of cryptocurrencies to allow users to safely exchange the position it should be stored so that the list remains sorted. different cryptocurrencies directly between themselves without For its storage is then not used the real time of its reception, any third party. Cryptocurrency applications are generally but the same timestamp as of the nonce preceding it in its privacy-sensitive and attacks-attracting, therefore we strove to position in the list. Stale nonces are always removed from the achieve similar level of anonymity as cryptocurrencies usually list as soon as possible, except for the last one—at least one provide. nonce must always be remembered (only for newly connected Purpose of Coincer, from the perspective of this paper, is peers this list may be empty). to globally maintain a decentralised market of users’ sell/buy offers on top of the overlay and to provide an appropriate C. Sybil Attack communication channel for execution of trades between users. Under a Sybil attack, an attacker introduces into the network Therefore, it utilises both available communication patterns— many peers under their control [17]. The more peers, the market messages for distribution of offers are broadcast, while higher is the probability that a random new peer connects communication related to particular trade between some two solely to these malicious peers. Hence, the more outgoing peers is carried out in unicast fashion. The latter also makes connections a peer maintains, the lower is the probability it use of implicitly available means for encryption of messages, becomes a victim of this attack. which is important for privacy. Also very useful is the feature Sensitivity of each application to Sybil attacks needs to of integrity assurance of all messages through digital signa- be taken into account when considering a recommended tures, because it precludes the possibility of impersonating minimum number of outgoing connections. While possible honest users by an attacker. damage in a case of some applications might be negligible, Coincer itself does not extend the list of possible attacks on for others such an attack may pose a serious threat. Coincer is the overlay. It rather makes several of the described attacks an example of the first group; a representative of the second harder to execute, namely the man-in-the-middle attack and the group in general, not for this specific overlay, is Bitcoin. Sybil attack. In the case of the Sybil attack, an attacker has to In Bitcoin a user is provided with the transaction history also carry out a successful Sybil attack in the cryptocurrency of the whole network. Therefore, if they is connected only to network where the victim would like to buy coins from attacker’s nodes, they can be tricked into believing in incorrect the attacker. However, under such conditions it is no longer state of the history, e.g., that they received some transactions, necessary to execute a Sybil attack in Coincer’s network, although they did not in the real history. On the other hand, because it does not influence in any way the primary attack it is not possible to cause harm to a user of Coincer, because itself. the underlying cryptocurrency protocol for trading ensures that The proposed overlay enables Coincer to accomplish its the attacker would have to successfully carry out a Sybil goals, while providing good protection and level of anonymity attack against the user on at least one cryptocurrency (with to the users with a reasonably low overhead. Coincer is published as a free software and its development [6] A. Mislove, G. Oberoi, A. Post, C. Reis, P. Druschel, and D. S. version is already publicly available. Wallach, “AP3: Cooperative, decentralized anonymous communication,” in Proceedings of the 11th workshop on ACM SIGOPS European VII.CONCLUSION workshop. ACM, 2004, p. 30. [Online]. Available: http://dl.acm.org/ citation.cfm?id=1133578 We addressed a problem of safe mutually anonymous [7] A. Rowstron and P. Druschel, “Pastry: Scalable, decentralized communication in a P2P overlay. We leveraged similarities object location, and routing for large-scale peer-to-peer systems,” in Middleware 2001. Springer, 2001, pp. 329–350. [Online]. Available: between an ad-hoc network and an unstructured P2P overlay http://link.springer.com/chapter/10.1007/3-540-45518-3 18 in the design of our overlay in order to provide desired [8] N. Bansod, A. Malgi, B. K. Choi, and J. Mayo, “MuON: Epidemic anonymity properties. As a result, any peer in the overlay based mutual anonymity in unstructured P2P networks,” Computer Networks, vol. 52, no. 5, pp. 915–934, Apr. 2008. [Online]. Available: is able to initiate communication with another peer, without http://linkinghub.elsevier.com/retrieve/pii/S1389128607003349 knowing their real IP address—using only their identifier [9] M. Reed, P. Syverson, and D. Goldschlag, “Anonymous connections and within the overlay. Thanks to establishing peers’ public keys onion routing,” IEEE Journal on Selected Areas in Communications, vol. 16, no. 4, pp. 482–494, May 1998. [Online]. Available: as identifiers, every message is digitally signed and the usage http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=668972 of ECC provides an instant access to end-to-end encryption [10] Y. Ni, D. Nyang, and X. Wang, “A-Kad: an anonymous P2P protocol without any need for negotiation of a shared key. Usefulness of based on Kad network,” in Mobile Adhoc and Sensor Systems, 2009. MASS’09. IEEE 6th International Conference on. IEEE, 2009, pp. our proposal for privacy-sensitive applications is demonstrated 747–752. [Online]. Available: http://ieeexplore.ieee.org/xpls/abs all.jsp? on a decentralised cryptocurrency exchange Coincer. arnumber=5336924 [11] P. Maymounkov and D. Mazieres, “Kademlia: A peer-to-peer ACKNOWLEDGEMENT information system based on the xor metric,” in Peer-to-Peer Systems. Springer, 2002, pp. 53–65. [Online]. Available: http: The authors would like to thank all reviewers for their //link.springer.com/10.1007%2F3-540-45748-8 5 valuable feedback which helped improve the paper. [12] G. Xu, L. Aguilera, and Y. Guan, “Pecan: A circuit-less p2p design for anonymity,” in Global Communications Conference REFERENCES (GLOBECOM), 2012 IEEE. IEEE, 2012, pp. 820–825. [Online]. Available: http://ieeexplore.ieee.org/xpls/abs all.jsp?arnumber=6503214 [1] M. Zima, “Coincer.” [Online]. Available: https://www.coincer.org/ [13] J. Chroboczek, “RFC 6126: The Babel routing protocol,” 2011. [2] C. E. Perkins and P. Bhagwat, “Highly dynamic destination-sequenced [Online]. Available: http://tools.ietf.org/html/rfc6126 distance-vector routing (DSDV) for mobile computers,” in ACM SIG- [14] B. Jonglez, M. Boutier, and J. Chroboczek, “A delay-based routing COMM computer communication review, vol. 24. ACM, 1994, pp. metric,” arXiv preprint arXiv:1403.3488, 2014. [Online]. Available: 234–244. http://arxiv.org/abs/1403.3488 [3] R. Sherwood, B. Bhattacharjee, and A. Srinivasan, “P5: A protocol [15] R.-Y. Xiao, “Survey on anonymity in unstructured peer-to-peer for scalable anonymous communication,” Journal of Computer systems,” Journal of Computer Science and Technology, vol. 23, no. 4, Security, vol. 13, no. 6, pp. 839–876, 2005. [Online]. Available: pp. 660–671, 2008. [Online]. Available: http://link.springer.com/article/ http://content.iospress.com/articles/journal-of-computer-security/jcs245 10.1007/s11390-008-9162-7 [4] B. N. Levine and C. Shields, “Hordes — A Multicast Based Protocol for [16] L. Law, A. Menezes, M. Qu, J. Solinas, and S. Vanstone, “An Effi- Anonymity,” Journal of Computer Security, vol. 10, no. 3, pp. 213–240, cient Protocol for Authenticated Key Agreement,” Designs, Codes and 2002. Cryptography, Tech. Rep., 1998. [5] M. K. Reiter and A. D. Rubin, “Crowds: Anonymity for web [17] J. R. Douceur, “The Sybil Attack,” in Peer-to-peer Systems. Springer, transactions,” ACM Transactions on Information and System Security 2002, pp. 251–260. [Online]. Available: http://link.springer.com/chapter/ (TISSEC), vol. 1, no. 1, pp. 66–92, 1998. [Online]. Available: 10.1007/3-540-45748-8 24 http://dl.acm.org/citation.cfm?id=290168 A. Publications

Coincer: Decentralised Trustless Platform for Exchanging Decentralised Cryptocurrencies

Michal Zima

Faculty of Informatics, Masaryk University, Brno, Czech Republic E-mail: xzima1@fi.muni.cz

Abstract. We address the problem of a trustless decentralised exchange of cryptocurrencies. Centralised exchanges are neither trustworthy nor secure. As of 2017, there has been more than 25 million US dollars’ worth of cryptocurrencies stolen from (or by) centralised exchanges. With Co- incer we allow any two users to exchange their diverse cryptocurrencies directly between them, yet with no need to trust each other. Former ap- proaches either do not do without a server or rely on a trusted issuer of exchangeable tokens. Our approach is to fully eliminate any elements sus- ceptible to becoming a single point of failure. Coincer therefore leverages an efficient anonymous P2P overlay and an atomic protocol for exchang- ing money across different cryptocurrencies. It is implemented as free software and has been successfully tested with Bitcoin and .

1 Introduction

Since the early days of the first clones of the cryptocurrency Bitcoin there has been demand for exchanging one for another. Internet forums and IRC servers were soon superseded by specialised exchange servers. However, the advantage of fast and convenient trading was outweighed by a need to trust the platform and its operator. Unsurprisingly, many of such centralised platforms were success- fully cracked and users’ funds stolen or they were simply closed down by their operators without returning users’ money. As of 2017, losses from these events already exceed 26 million USD [11]. We expect this number to further grow. In our paper we elaborate on the problem of trustless exchange of cryptocur- rencies with a goal to eliminate the aforementioned issue. Present approaches centralise communication or build different structures that still require users’ trust in operators of the exchange platform. In contrast, our approach is for a platform to be as decentralised and trustless as possible. We call our platform Coincer. It leverages principles of atomic transactions across distinct cryptocur- rencies and deploys a custom P2P network to carry out decentralised market and communication between users. The remainder of this paper is organised as follows. Section 2 presents previ- ous work related to the problem of exchanging cryptocurrencies in a decentralised manner. Section 3 discusses our design goals and decisions for Coincer, followed by Sect. 4 in which we elaborate in detail on cryptocurrency exchange protocol,

42 A. Publications

the most important component of Coincer. Section 5 describes a way for estab- lishing decentralised markets, followed by a summary of Coincer’s limitations in Sect. 6. Section 7 provides final conclusions.

2 Related Work

The first alternative platform for trading cryptocurrencies was Multigateway [10] built on top of Asset Exchange [7]. It uses NXT1 tokens to transform arbitrary cryptocurrency to a tradeable asset on this platform. A user has to deposit their cryptocurrency to an escrow formed by 3 servers, each supposedly operated by a different (and independent) operator. These servers cannot ma- nipulate with the deposits on their own, unless at least two of them agree on a transaction. Therefore, to steal funds, two servers need to be cracked. NXT tokens can be easily exchanged as the trades happen on a single “database.” A similar approach has been taken by B&C Exchange [5]. On this platform 15 (independent) servers form the deposit escrow and at least 8 of them are needed for authorisation of a transaction. To use this platform, a user needs “credits” to pay fees for using the platform. All actions and transactions are recorded to a dedicated blockchain, which also eases coordination of the servers. Unlike the described platforms, a man with a pseudonym “TierNolan” in 2013 designed a protocol based purely on cryptographic and scripting capabilities of cryptocurrencies [2] that should have allowed atomic transactions across two distinct cryptocurrencies to take place [8]. Nonetheless, due to practical issues [3], the atomicity was not actually achieved. Still, there were several attempts at implementing this protocol [1, 6], but most of them reached only a proof-of-concept stage. So far the most advanced implementation is Mercury [1]. However, it has never progressed to a usable state and its development is now stopped. While it featured a good user interface, it did not offer any decentralised platform—both communication and market establishment were implemented using author’s server. For our work, we redesigned the idea of TierNolan’s protocol using today’s scripting capabilities of Bitcoin and other cryptocurrencies, and extended it with a decentralised marketplace.

3 Design of Coincer

The design goal is a decentralised platform for trustless exchange of cryptocur- rencies. Decentralisation allows to eliminate elements serving as single points of failure in traditional cryptocurrency exchange systems. By moving from a client-server model to a peer-to-peer architecture with inherent redundancy, we allow users to participate in communication and cryptocurrency trading without restraint, even in the presence of failures of parts of the system.

1 NXT is a cryptocurrency with a design partially different from Bitcoin.

43 A. Publications

Coincer follows a principle that other user’s actions or the system’s failures must not cause a user to lose their money, regardless of their state (idle or involved in a trade). This leads to two important features: first, a user never deposits their money anywhere in the system in order to be able to use the system or to place an order. Second, in case of a failure of the system in the middle of a trade or when the other trading party stops cooperating, there is always a fail-safe to retrieve either the original money back or to finish the trade. Designing a communication protocol for both the P2P layer and Coincer itself, we also take into account several practical aspects. These mainly include extensibility, simplicity (resulting in low overhead) and ease of implementation. In order to exclude trust from the trading process and not to involve any third party, we rely purely on the programmable nature of cryptocurrencies. We redesign an atomic protocol with modern features of cryptocurrencies, making use of time locks on spending transactions. The P2P architecture has already been described in our earlier paper [12]. In short, we designed an unstructured P2P network leveraging principles and algo- rithms from the area of ad-hoc networks. The result is a resilient and anonymous network that enables secure direct communication of any two participants. The platform would not be complete without a market where users could negotiate prices for their trades. Leveraging the P2P network we design a de- centralised marketplace for any cryptocurrency pair in Sect. 5.

4 Trustless Protocol for Exchanging Cryptocurrencies

Purpose of the protocol is to execute an atomic transaction between two distinct cryptocurrency transaction databases. This transaction transfers some amount of money in one cryptocurrency from one user to another user and at the same time some other amount of money in a different cryptocurrency from the other user to the first user. Atomicity in this context means that either both described transfers are fully executed, or none of them is. Figure 1 illustrates this situation on an example of hypothetical cryptocurrencies abbreviated as ABC and XYZ.

amount M of ABC iff amount N of XYZ

user A user B

Fig. 1. Atomic transaction of two transfers of different cryptocurrencies.

4.1 Protocol Flow The protocol comprises two main phases and one “zeroth” preparatory phase. Only the zero phase is interactive—the other two do not involve any communi- cation between the trading parties—all their actions are based solely on states

44 A. Publications

of respective cryptocurrencies’ blockchains. This distinction can be easily seen from a diagram in the Fig. 2. Two phases are needed, because blockchains are independent and we need to assure synchronisation between them. The first phase commits money from both cryptocurrencies into the trade, while the second phase releases money for redemption by their new owners. Until the second phase is started, the trade can be cancelled at any point using rollback transfers. As soon as the second phase begins, the trade can only be finished, but transfer to the new owner is independent of the other user. In the zero phase, the following data are exchanged2:

– public keys; – scripts that will be used for transactions in the first phase.

Public keys are needed for proper construction of the script for the second phase, i. e., claiming exchanged funds, and also for managing refund transfers in a case that the trade would be cancelled during the first phase. The scripts themselves are also important, because their knowledge is required in order to claim the funds—the original transactions contain only their hashes and it is up to the consecutive transactions to provide the scripts (this is the principle of P2SH transaction scripts). Let’s assume that Alice starts the protocol. In the first phase, she creates and broadcasts a funds locking transaction tx1 using a hash of the script that she sent to Bob in the previous phase. As soon as this transaction gets into her cryptocurrency’s blockchain and obtains a safe number of confirmations3, Bob detects this transaction and is able to confirm its correctness. Afterwards, he creates and broadcasts an analogous transaction tx2 for his cryptocurrency. By the time both transactions are safely stored in their respective blockchains, this phase ends and it guarantees that until time locks (which are specified in the scripts, see details in Sect. 4.2) expire no party can transact using their original money, making it safe to proceed with the second phase. In the second phase, Alice starts the process of claiming exchanged cryp- tocurrency funds. She creates a transaction tx3 that embeds Bob’s original script (which he transferred to Alice in phase zero) and its required parameters in order to satisfy its spending conditions. As soon as Alice broadcasts this transaction and Bob detects it, he proceeds with his claiming transaction tx4, reusing un- locking information from Alice’s transaction. Since there is no reason for him to wait for Alice’s transaction to get into the blockchain and confirmed, he broad- casts his transaction without any delay. When both transactions tx3 and tx4 are safely saved in their blockchains, the second phase formally ends.

2 Note that we expect that both parties already settled on cryptocurrency amounts and an exchange rate for their trade. Therefore, these two pieces of information are not included in our description of the protocol. 3 “Number of confirmations” is a way of expressing depth of a transaction within the chain of blocks. E. g., a transaction in the top block has 1 confirmation, a transaction in a block right below the top block has 2 confirmations and so on.

45 A. Publications

Alice Bob Public network/blockchains

Publishes an order

Reads the order Proposes a trade

Generates her keys Accepts proposal; sends public key

Generates his keys Sends his public key phase 0 Generates `x` Sends her script

Sends his script

Broadcasts `tx1`

`tx1` is verified and safely stored in its blockchain

Broadcasts `tx2` phase 1 `tx2` is verified and safely stored in its blockchain

Claims money from `tx2` by revealing `x` in `tx3`

Spots `tx3` and extracts `x`

phase 2 Claims funds from `tx1` using `x` in `tx4`

Fig. 2. Diagram of the protocol flow.

4.2 Protocol Scripts The protocol is built upon a cryptocurrency script that allows locking funds until a “password” is provided or until a time lock expires. The script for a transaction sent by Alice is detailed in the Fig. 3, nonetheless, for Bob the script looks the same, only with public keys swapped and with a different time lock.

OP_IF OP_HASH160 OP_EQUALVERIFY OP_ELSE OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF OP_CHECKSIG

Fig. 3. Cryptocurrency script for the atomic exchange protocol.

Value x is a locking secret which is known only to the party that sends their transaction first. Let’s suppose this is Alice. Then Bob knows only the double hash of x, and also sets his timeout value in OP ELSE branch to a lower value— usually a half, i. e., 12 hours in this example.

46 A. Publications

4.3 Semantics of the Script

Spender of this transaction chooses a branch to execute. Bob spends Alice’s transaction (i. e., claiming his money acquired from the trade) by executing the first branch and providing the value of x and a signature. The signature ensures that no other user can claim the money when the value of x becomes publicly known from the blockchain. For Alice, who executes the second branch, the main requirement is to set time lock of the spending transaction to at least the value given here. This ensures that her transaction will not be processed earlier than it should, giving Bob enough time to finalise the trade4. Again, Alice has to provide a signature to prove that she is the rightful owner of the funds.

4.4 Protocol Fail-safe Points

In any moment, the trade can be interrupted and either fully reverted or fully finished, depending on its momentary state. We examine each protocol block:

– the zero phase: trivial—nothing needs to be done; – the first phase after the first party sends their transaction: the second party does not send their transaction and the first party waits for their timeout to expire in order to reclaim their funds; – the first phase after both parties send their transactions: they both wait for their timeouts to expire and then reclaim their funds; – the second phase after the first party redeems the exchanged funds: as the value of x is revealed and the second party’s funds are already claimed, the second party can only redeem their exchanged funds.

4.5 Avoiding Race Conditions

While the protocol is designed as atomic, since it makes use of timeouts, there are certain unavoidable edge cases possibly leading to race conditions. For instance, if Alice waited with proceeding into the phase two till near the timeout of Bob’s transaction, she risks a race condition in which Bob may attempt to proceed into the rollback phase. If Bob won the race condition, he would hold his original money plus he would know the value of x (from Alice’s attempt to claim Bob’s money) which would enable him to also claim Alice’s money. Caution is needed not only with regard to absolute time, but also with regard to specifics of cryptocurrencies. Firstly, inclusion of a transaction into a block is not usually instant so some time should be accounted for possible delays. Sec- ondly, due to their decentralised nature, cryptocurrencies maintain a tolerance for time shifts of individual nodes in their networks and of individual blocks, too.

4 A reader of this paper who is not very familiar with cryptocurrency script languages may wonder about the use of OP DROP operation (which removes a top element from the stack). Its use relates to the definition of OP CHECKLOCKTIMEVERIFY, which leaves an extra item on the stack to be backward compatible with older clients that still interpret this operation as OP NOP2 (i. e., “no operation”) [9].

47 A. Publications

For example, Bitcoin allows time of a block to be shifted by up to two hours. A transaction with a time lock could be in this way included into a block up to two hours earlier than the time lock would in fact expire. To lessen this issue, Bitcoin compares time locks not against block’s time, but against a median time of last 11 blocks [4]. Nonetheless, a possibility of a time shift attack still exists. Thence, users should proceed with the protocol without unnecessary delays. If they are left with an insufficiently short time frame (e. g., due to a delay in inclusion of a transaction into the blockchain), a safer rollback is preferred.

4.6 Protocol Atomicity

In this section we show that the presented protocol is atomic and complete (i. e., does not allow any other than specified actions) by having these two properties:

Liveness. There always eventually exists a step each party can do either to make progress within the protocol, or to revert its effects.

Safety. The protocol never deadlocks, and neither party can acquire both parties’ money from the trade.

Liveness. For liveness, we want to disprove that one of the parties can perform such an action that the other party cannot perform any action in a finite time. Therefore, we will do an analysis for each step of the protocol. We assume that Alice starts the protocol. As the very first step, during the zero phase, Alice and Bob generate and exchange their public keys. If one of them does not send their public key, the protocol stops as the other party can trivially terminate it. If they send some- thing different than their public keys, they will lose their money sent into the exchange5. Alice then generates a cryptographically secure random number x and creates a script as shown in Fig. 3 and sends it to Bob. If she does not generate such a number, she may lose her money if Bob can figure its value out. If she does not send Bob a script he expects, he trivially terminates the protocol when he verifies its content. The same applies if Alice does not send anything. Afterwards, Bob extracts the hash of x and creates an analogical script using a lower timeout value and sends it to Alice. Similarly to the previous case, if he does not send Alice the expected script or does not send anything at all, she trivially terminates the protocol. Now, in the first phase, Alice broadcasts her transaction tx1 which consists of a hash of the script she previously sent to Bob. Bob knows the hash and monitors the blockchain for a transaction containing it. If Alice does not send the transaction at all6 or sends a different amount of money, Bob can trivially

5 Such an action violates the protocol, however, since this does not cause any harm to the other party, it does not break the given property. 6 If Alice alters the original script, its hash will differ and the transaction will not get recognised by Bob, therefore seeming as if it was not sent at all.

48 A. Publications

terminate the protocol. In such a case, Alice would need to wait until the timeout expires so that she can claim her money back. After Alice’s transaction is accepted into the blockchain and receives a safe number of confirmations7, Bob broadcasts his transaction tx2 which consists analogically of a hash of the script he previously sent to Alice. If the transaction is different than Alice expects or if Bob does not send it at all, Alice waits until the timeout of her transaction tx1 expires and terminates the protocol by claiming her money back. Bob would need to do the same with his transaction. As soon as Bob’s transaction tx2 is safely included in the blockchain, Alice starts the second phase. She claims Bob’s money in tx3 using Bob’s script (from the zeroth phase) and the value of x. When she broadcasts this transaction and Bob notices it, he constructs an analogical transaction tx4 with Alice’s script and the now-public value of x and broadcasts it. The protocol is then finished. If Alice decides not to carry on with the second phase, both Bob and Alice have to wait for timeouts of their transactions to expire and in time claim their funds back. If only Bob decides not to continue with the trade, he is likely to lose money as soon as the timeout of Alice’s transaction tx1 expires. At this point there is nothing he could do to affect Alice and cause her harm as she proceeded with the second phase and already claimed money from Bob’s transaction tx2.

Safety. Safety property says that the protocol should be deadlock-free and that no party can steal money of the other party. We already know that the protocol is deadlock-free from liveness. Therefore, it only needs to be shown that no trading party can lose their money while conforming to the protocol. Money is sent to the trade only via transactions with a hash of script detailed in Fig. 3. Spending money from such a transaction requires supplying such data that its script evaluates to true. This specific spending transaction requires the original script, that was hashed, which will execute exactly one of its branches and will always check a signature. The first branch performs an equality verification of the given hash with a hashed value of x that was provided in the spending transaction, and puts a requirement for a signature made by the party that is supposed to receive this transaction’s money, which is done by specifying a proper public key. The knowledge of the value of x alone is ergo insufficient for claiming the money. The second branch is controlled solely by the original sender. It guarantees that if the first branch is not executed within the time limit specified in the second branch, the second branch can be executed, but not earlier—executions before the specified time would fail and result into an invalid spending transac- tion. Therefore, it can only be used within the “rollback phase” of the protocol. If the money remains unclaimed (i. e., the trade is interrupted), this branch ensures that the original owners will receive their money back. To execute this branch the original owner needs to supply a signature with a private key corresponding to the specified public key. Therefore, no one else can execute this branch.

7 Number of confirmations that is considered safe is dependent on particular cryp- tocurrency. For Bitcoin this is usually 2–6 (based on context and amount).

49 A. Publications

In the beginning of the protocol, only Alice knows the value of x, but she can- not use it until Bob broadcasts his transaction in the first phase which happens iff Alice first broadcasts hers. While she can claim money from Bob’s transaction, she would have to wait until her transaction’s timeout expires—with Bob not following the protocol and not claiming money from Alice’s transaction using the value of x. Bob has no way to claim Alice’s money and to keep his money at the same time since his money is already claimed by Alice by the time he learns the value of x. Due to timeouts, race condition cannot happen. Therefore, we have shown atomicity of the protocol.

5 Decentralised Markets

Before a trade can even take place, two parties have to settle on terms of the trade first. Our goal is a resilient platform where each node is independent of the rest of the network and which is resistant to withholding information about asks and bids of other users from reaching a particular node. In order not to introduce a single point of failure, we avoid solutions involving servers or prominent nodes. Market information should be distributed among nodes all over the network.

Placing an order. Publishing an ask or a bid is performed by broadcasting a mes- sage with information about amounts and cryptocurrencies being sold/bought. Since the messages are broadcast, every node learns about every order. Nodes maintain multiple connections to the network, hence an incidental node that does not forward an order does not prevent its neighbours from receiving it.

Exploring a market. Nodes primarily gather data about markets from orders received from other nodes. Nevertheless, unless a node has been connected to the network for a certain time span, its view of the market state might be only partial. To retrieve missing orders, nodes ask their neighbours for orders related to a specific cryptocurrency pair—either when they connect to the network or when they need the orders in order to start a trade.

Market maintenance. To keep a list of orders useful, stale and out-of-date orders should be purged. A user may cancel their order explicitly. Otherwise, all orders are bound to expiration after 1 hour. If an order is still valid after 1 hour since its initial publishing, the user needs to rebroadcast it.

Identification of cryptocurrencies. When an order is sent, it needs to distin- guish individual cryptocurrencies. Since verbal descriptors might be sometimes ambiguous or even change (e. g., a cryptocurrency used to be called Dark- coin, but even before that it was named XCoin), we propose as a cryptocurrency identifier a hash of the first block within the cryptocurrency that differentiates it from the original cryptocurrency (if there is any—as in a case of a fork), which is most times the very first block in the chain. Each cryptocurrency is hence uniquely and consistently identified within the platform. Applications can then do a mapping and present users with the cryptocurrencies’ common names.

50 A. Publications

6 Limitations The most notable limitation of Coincer, when compared to centralised exchanges, is non-real-time nature of trades. A single trade can take from tens of minutes up to several hours, because for every trade a user has to perform a money deposit, while a centralised exchange requires only one deposit for arbitrary number of trades that may finalise nearly instantly. Besides that, from a technical nature of various cryptocurrencies, it is possible to find two cryptocurrencies with a different set of supported cryptographic operations. If two cryptocurrencies do not support the same operations that are needed by the atomic protocol, it is not possible to exchange them directly. Instead, an intermediary cryptocurrency must be used. 7 Conclusion All different kinds of cryptocurrencies are nowadays exchanged by people via centralised services. However, many such services have been either cracked or intentionally shut down, rendering more than 21 million USD in losses to users as of 2017 [11]. To prevent such events, several platforms try to decentralise exchanging services. Coincer is our fully decentralised solution for exchanging cryptocurrencies. Its trading layer is built using an atomic two-party cryptocurrency protocol, thence removing any intermediaries from the process and making the exchange safe and trustless. Communication and pairing of bids and asks are fully carried over a P2P network, making Coincer a serverless platform without any single point of failure.

References 1. Bell, M.: Mercury, https://github.com/mappum/mercury 2. Bitcoin Wiki: Script, https://en.bitcoin.it/wiki/Script 3. Bitcoin Wiki: Transaction Malleability, https://en.bitcoin.it/wiki/ Transaction_Malleability 4. Kerin, T., Friedenbach, M.: BIP 113: Median time-past as endpoint for lock- time calculations (Aug 2015), https://github.com/bitcoin/bips/blob/master/ bip-0113.mediawiki 5. Lee, J.: Blocks & Chains Decentralized Exchange, https://bcexchange.org/ assets/Blocks_&_Chains_Decentralized_Exchange.pdf 6. Nicoll, R.: Cate, https://github.com/rnicoll/cate 7. Nxt Wiki: Asset Exchange, https://nxtwiki.org/wiki/Asset_Exchange 8. TierNolan: Re: Alt chains and atomic transfers (May 2013), https:// .org/index.php?topic=193281.msg2224949#msg2224949 9. Todd, P.: BIP 65: OP CHECKLOCKTIMEVERIFY (Oct 2014), https://github. com/bitcoin/bips/blob/master/bip-0065.mediawiki 10. VanBreuk: Multigateway: Service Documentation v0.2 (Aug 2014), https:// multigateway.org/downloads/Multigateway_docs.pdf 11. Zima, M.: History of Cracks, https://www.coincer.org/history-of-cracks/ 12. Zima, M., Hladk´a,E.: Cryptography enhanced ad-hoc approach to P2P overlays. pp. 517–522. IEEE (Jul 2016), http://ieeexplore.ieee.org/document/7568378/

51