63
Transaction Fee Reduction in Coinblesk Sebastian Stephan Baden, Switzerland Student ID: 08-731-465 Supervisor: Thomas Bocek Date of Submission: May 17, 2017 University of Zurich Department of Informatics (IFI) Binzmühlestrasse 14, CH-8050 Zürich, Switzerland ifi MASTER T HESIS Communication Systems Group, Prof. Dr. Burkhard Stiller

Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Transaction Fee Reduction inCoinblesk

Sebastian StephanBaden, Switzerland

Student ID: 08-731-465

Supervisor: Thomas BocekDate of Submission: May 17, 2017

University of ZurichDepartment of Informatics (IFI)Binzmühlestrasse 14, CH-8050 Zürich, Switzerland ifi

MA

ST

ER

TH

ES

IS–

Com

mun

icat

ion

Sys

tem

sG

roup

,Pro

f.D

r.B

urkh

ard

Stil

ler

Page 2: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Master ThesisCommunication Systems Group (CSG)Department of Informatics (IFI)University of ZurichBinzmühlestrasse 14, CH-8050 Zürich, SwitzerlandURL: http://www.csg.uzh.ch/

Page 3: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Abstract

Während das Bitcoin Netzwerk an seine Kapazitätsgrenzen stösst, haben Transaktions-gebühren einen neuen Höchstwert erreicht. Stand Mai 2017 kostet eine durchschnitt-liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einerungeeigneten Währung, insbesondere für häufige kleinere Zahlungen. In dieser Arbeitwird ein neues Bezahlsystem vorgestellt, welches sogenannte micropayment channelsbenützt. Kleinere Beträge werden über einen zentralen Server geleitet. Dieses Modellwurde in Coinblesk, einem mobilen Bezahlsystem der Universität Zürich umgesetzt.Eine Simulation zeigt, dass es damit möglich ist Transaktionsgebühren für kleinereZahlungen um 96% zu reduzieren. Zusätzlich konnte eine existierede Sicherheitslückeim alten System behoben werden.

Recently transaction fees in the bitcoin network have risen to a new all-time high, as thenetwork is closing in on its capacity limit. A median transaction as of May 2017 costsmore than one US dollar, making it unfeasible to use bitcoin for everyday payments.In this thesis a new payment mechanism is presented, which uses micropayment chan-nels to route payments over a central server which reduces transaction fees for smallerpayments. The mechanism is implemented in Coinblesk, a mobile bitcoin paymentsolution developed at the University of Zurich. An evaluation shows that the newimplementation reduces transaction fees by 96% for smaller payments and removes apreviously existing security vulnerability based on transaction malleability.

i

Page 4: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 5: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Acknowledgments

I want to express my sincerest gratitude to my supervisor Dr. Thomas Bocek for histireless support during this thesis. With his immense knowledge and passion in thefield of cryptocurrencies, he was able to help me during all times of research and writ-ing.

Besides my advisor I would also like to thank Prof. Dr. Burkhard Stiller and the mem-bers of the Communication Systems Research Group for giving me the opportunity towork on such an interesting topic.

Last but not least I would like to thank my friends and family for their constant supportand encouragement.

iii

Page 6: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 7: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Contents

Abstract i

Acknowledgments iii

1 Introduction 1

1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Description of Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.3 Thesis Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Background and Related Work 3

2.1 Transaction Fees in the Bitcoin Network . . . . . . . . . . . . . . . . . . . 3

2.2 Transaction Malleability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2.3 Protocol Changes in Bitcoin . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.3.1 Bitcoin Unlimited . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.3.2 Segregated Witness . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.4 Micropayment Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.4.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.4.2 Micro Payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.5 The Lightning Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.5.1 Bi-directional Payment Channels . . . . . . . . . . . . . . . . . . . 11

2.5.2 Hashed Timelock Contracts . . . . . . . . . . . . . . . . . . . . . . 11

2.5.3 Adoption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

v

Page 8: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

vi CONTENTS

2.6 Coinblesk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.6.1 Payment Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.6.2 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3 Design 17

3.1 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3.2 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.3 Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.3.1 User Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.3.2 Server Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.4 Transaction Fees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Implementation 25

4.1 Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.1.1 Spring Boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.1.2 Token Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4.1.3 Signed Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.2 Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

4.3 REST Endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.3.1 /virtual-payment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.3.2 /payment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.3.3 /payout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4.4 Offline Payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.5 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.5.1 Full Integration Test . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.5.2 Load Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Page 9: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

CONTENTS vii

5 Evaluation 35

5.1 Transaction Fees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

6 Summary and Conclusions 39

Abbreviations 43

List of Figures 43

List of Tables 45

A Installation Guidelines 49

B Contents of the CD 53

Page 10: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 11: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 1

Introduction

Virtual currencies are on the rise. The global market capitalization of all cryptocur-rencies has more than doubled to over USD 55 billion in the last two months alone1.While new cryptocurrencies seem to emerge on a weekly basis, bitcoin remains theundisputed leader with a 56% market share, recently reaching an all-time high valueof USD 1850 1.

Yet the numbers are deceiving: as the number of bitcoin transactions rises, the networkis pushed to its limit [22]. Transactions on average take more than three hours to con-firm2. Meanwhile the pool of unconfirmed transactions grows larger and larger. Thishas pushed transaction fees to unseen heights – from a few cents back in 2015 to morethan one US dollar as of May 2017. While this not be a problem for larger transactions,using bitcoin to buy your daily coffee becomes a rather expensive choice.

The search for a solution to the scalability problem is ongoing. Developers and miners,however, seem unable to agree on how the future of bitcoin should look like. Whileone side pushes for more radical changes to the protocol, others advocate a simpleincrease of the block size. In the meantime a solution is needed that makes bitcoinagain a viable choice for smaller everyday payments.

1.1 Motivation

Coinblesk is a mobile bitcoin payment solution developed at the University of Zurich[2]. While originally intended to be used as a payment system for a cafeteria, it has seenmany improvements over the last years [31] [10] and can now be used as a general-purpose bitcoin wallet and payment solution. Coinblesk supports trust-less, zero-con-firmation transactions and mobile payments over Near Field Communication (NFC)and bluetooth, making it a great fit for a point-of-sale system. However, the increasingtransaction fees become a problem in such a scenario, as they make up a large portion

1Source: coinmarketcap.com as of May 15, 20172Source: blockchain.info as of May 15, 2017

1

Page 12: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2 CHAPTER 1. INTRODUCTION

of each payment. Therefore the main goal of this thesis is to find and implement asuitable solution to the problem of increased transaction fees in Coinblesk, while bal-ancing trade-offs between cost, trust and complexity. Additionally, as the codebase ofCoinblesk has become somewhat outdated, libraries should be upgraded to their latestversions and a general refactoring of the codebase should be performed to improve thequality and maintainability of the project for future iterations.

1.2 Description of Work

This thesis covers the design, implementation and evaluation of a new payment sys-tem for Coinblesk, which reduces transaction fees in an everyday payment scenario.Existing concepts such as micropayment channels are explained and relevant currentprotocol change proposals introduced. A new model for instant payments is devel-oped and compared against the previous version. The thesis also covers the refactor-ing of the existing codebase to improve the quality, stability and usability of the wholesystem.

1.3 Thesis Outline

The remainder of this thesis is structured as follows. Chapter 2 provides backgroundinformation on the scalability and security issues of bitcoin. Additionally, pendingprotocol changes and existing solutions to the problem are investigated. In Chapter 3a new protocol for payments in Coinblesk is designed, based on the previous findings.Chapter 4 explains the implementation details of the new payment model. The newsystem is tested and evaluated against the previous version of Coinblesk in Chapter 5and Chapter 6 concludes the thesis and outlines future work.

Page 13: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 2

Background and Related Work

2.1 Transaction Fees in the Bitcoin Network

Transactions in the bitcoin network have to be validated and confirmed by miners.Miners take all unconfirmed transaction and group them into blocks. This process isintentionally made resource intensive and costs money in terms of computing powerand electricity. The incentive to mine comes in the form of a coinbase transaction. Thistransaction is included by the miner and has no connected inputs, but sends a sum toan address chosen by the miner. This sum is defined to be a fixed block reward plusthe sum of all transaction fees included in a block.

The block reward is a fixed value of coins defined in the bitcoin protocol. At the be-ginning of the network 2009 it is set to 50 bitcoin and is halved every 210’000 blocks– or roughly every 4 years. As of May 2017 this reward is currently at 12.5 BTC. Theblock reward acts as a controlled money supply to the network. The halving of theblock reward will move the incentive for mining over time from the block reward totransaction fees.

The fee of a transaction is defined as the difference in value between inputs and out-puts. This amount is set by the creator of a transaction. Miners have a right to collectthe sum of all fees in a block by adding it to the coinbase transaction. Since blocks areby design of the protocol limited to 1 MB, miners optimize their profit by prioritizingtransactions with a higher fee per byte.

Fees have not played a large role in the beginning of bitcoin. As shown in Figure 2.1,besides a large exchange rate driven spike in 2014, they have risen almost constantlysince 2015. One major reason is the increase in transaction volume. As of May 2017,almost 100% of all blocks have reached the 1 MB limit, while around 100 MB of trans-actions are constantly waiting to be included in a block. Paying a low fee can resultin a transaction to take a long time to be confirmed. Therefore users include higherfees if they need a transaction to be included in the next block. As of May 2017 the fee

3

Page 14: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

4 CHAPTER 2. BACKGROUND AND RELATED WORK

2011 2012 2013 2014 2015 2016 20170

0.1

0.2

0.3

0.4

0.5U

SD

0

0.2

0.4

0.6

0.8

1

%fu

llbl

ocks

Transaction feeFull blocks (≈1MB)

Figure 2.1: Transaction fees and full blocks over time

needed to guarantee an inclusion in the next block is around 240 satoshis per byte 1.One satoshi is defined as one hundred millionth of a bitcoin. For the average transac-tion size of 226 bytes this means a required fee of 54’240 satoshis – or one US dollar2.

2.2 Transaction Malleability

Each transaction in the bitcoin network with the exception of the coinbase transactionuses the value of previous transaction outputs as inputs. The output being spent isreferenced by the identifier (ID) of the containing transaction and an index. The IDis calculated by applying a the hash algorithm SHA-256 twice over all parts of thetransaction.

Transaction malleability refers to the attack, where parts of a transaction are changed– possibly by a third party – without invalidating the transaction itself, but causingthe ID to change. This is possible from a broadcast until a transaction is included in ablock. A modified transaction remains valid with all general properties, such as howmany coins are moved to where. The changed ID, however, can be problematic, as de-pending transactions which use the ID in their inputs will be invalidated. Transactionmalleability gained notoriety in February 2014, when the major bitcoin exchange Mt-Gox suspended trading, claiming that 850,000 bitcoins were stolen due to a malleabilityattack [11].

1Source: bitcoinfees.21.co as of May 11, 20172Source: bitstamp.net as of May 11, 2017

Page 15: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.3. PROTOCOL CHANGES IN BITCOIN 5

One attack vector of malleability is caused by the usage of the Elliptic Curve DigitalSignature Algorithm or short ECDSA in the signatures of bitcoin transactions. TheECDSA signature consists of a tuple of integers (r, s) ∈ {1, N − 1}2 where N is a con-stant and defines the order of the used curve [14]. ECDSA signatures are inherentlymalleable, since replacing (r, s) with (r,−s (mod N)) produces an equally valid sig-nature [1]. This replacement can be performed by any relaying node or miner. BitcoinCore nodes since version 0.10.3 enforces the use of the lower s value when relayingor mining transactions [6]. However, transactions with high s values are still acceptedwhen they are received in a block, making it possible for miners to change transactionIDs at will. Recently this could be observed in the network when two blocks mined bythe mining pool BitClub contained modified transactions with high s values [3].

2.3 Protocol Changes in Bitcoin

Since the release of the original white paper by Satoshi Nakamoto in 2009 [19], bitcoinhas undergone several protocol changes. Due to the decentralized design of the sys-tem, those changes come with additional challenges: it is important that at any time amajority of all users agree on the same set of rules. Otherwise the system might endup in a state, where some blocks are accepted by certain users, while being rejected byothers, causing the block chain to fork into two different chains.

The conventional process to implement a change in the bitcoin reference implementa-tion Bitcoin Core [5] is to submit a standardized Bitcoin Improvement Proposal (BIP)[9] document, specifying the suggested changes. These proposals are then discussedopenly with the help of mailing lists. After enough consensus is reached, BIPs changetheir status to from draft to final or active. Accepted BIPs are included in the next releaseof the Bitcoin Core client. Some changes that require consensus from miners are onlyactivated when sufficient support from miners is reached. This again tries to reducethe risk of a forked chain. By setting predefined bits in the version header of a block,miners can voice their support for currently drafted proposals[32]. When a 95% major-ity of all blocks in a given 2016 block window are mined with support for a proposal,it will activate automatically.

Since the bitcoin software is open-source and free, it is also possible to fork the mainsource repository and release a modified version as a separate client. This client canthen also take part in the same network with other bitcoin implementations. The ben-efit of this approach is that it does not require the endorsement of the maintainers ofthe original bitcoin repository. However, it requires that a majority of users switch tothe alternative client. Currently there exist three forks of Bitcoin Core, namely BitcoinXT [8], Bitcoin Classic [4] and Bitcoin Unlimited [7]. Of those forks, so far none havegained the necessary support to impose protocol changes on the rest of the bitcoinnetwork.

Page 16: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

6 CHAPTER 2. BACKGROUND AND RELATED WORK

Oct 2016 Dec 2016 Feb 2017 Apr 20170

10

20

30

40

50Su

ppor

t%

SegWitBitcoin Unlimited

Figure 2.2: Miner support for SegWit and Bitcoin Unlimited

2.3.1 Bitcoin Unlimited

Bitcoin Unlimited is a fork of the original Bitcoin Core client and was released in Jan-uary 2016. It aims to solve the scalability issues of the current implementation of Bit-coin Core by increasing the maximum block size. In Bitcoin Unlimited the fixed blocksize limit of 1 MB is replaced by three configuration parameters, which can be set byall nodes running Bitcoin Unlimited.

The Maximum Generation (MG) parameter defines the maximum size of produced blocksand is set by the miners. The default value of MG is 1 MB, to achieve compatibility withthe current majority of Bitcoin Core clients. However, it is meant to be increased overtime. The Excessive Block Size (EB) defines the size of blocks that nodes accept. Blocksexceeding this limit are ignored and not relayed. The third option is the AcceptanceDepth (AD), which sets the maximum depth of blocks, after which the EB is ignoredand overruled. This implements a strategy in which consensus on the block size limitcan be found by all nodes in the network. Similar to the free market theory, BitcoinUnlimited supporters believe that this should lead to a scalable and healthy block sizeequilibrium [25].

Bitcoin Unlimited has gained more popularity in the last year. Currently around 40%of all miners (see Figure 2.2) and roughly 10% of all nodes3 run the Bitcoin Unlimitedclient. The produced blocks by the Bitcoin Unlimited miners are still capped at 1 MB,but when enough miners and nodes switch to Bitcoin Unlimited, this is expected to

3Source: coin.dance as of May 15, 2017

Page 17: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.3. PROTOCOL CHANGES IN BITCOIN 7

increase. However it is unclear when and if Bitcoin Unlimited will become the new defacto client. Even if a big majority of miners use Bitcoin Unlimited, mining a block withmore than 1 MB could be infeasible, as the incompatibility with Bitcoin Core wouldmost likely cause a fork in the chain and have a negative impact on the bitcoin networkas a whole.

2.3.2 Segregated Witness

Segregated Witness or short SegWit is a proposal to the bitcoin protocol made by Lom-brozo, Lau, and Wuille in 2015. SegWit is split into different proposals from BIP 141-147, covering different aspects of the change, such as activation design, network pro-tocol changes and API specification. SegWit is designed to be a backwards compatiblechange and is thus labeled as a soft-fork. SegWit aims to solve multiple issues with thecurrent bitcoin protocol design.

The core concept of SegWit is to move the transaction signatures from the transactioninputs into a separate structure called the witness, which will be located towards theend of a transaction (see Figure 2.3). The witness is not included when hashing thetransaction and therefore does not influence the transaction ID. This solves many issuesrelated to malleability as discussed in section 2.2.

Further, SegWit changes the maximum block size to 4 MB with a different calculationmethod. Every non-witness byte is counted with a weight of four and witness data isweighted with a factor of one:

size(data_witness) + 4 ∗ size(data_nonwitness) ≤ 4MB (2.1)

This block size limit change is backwards compatible, as a non-upgraded nodes willreceive a block without witness data, which can according to equation 2.1 be at most1 MB in size. The total of 4 MB can never be reached, as a block consists of othernon-signature data such as the block header, version bytes and transaction outputs. Inpractice a block containing mostly transactions in the new SegWit format is estimatedbe grow up to 2 MB [26].

The deployment of SegWit is defined by BIP 9 [32] and needs 95% of all blocks in a 2016block period to signal for its activation. After that limit is reached, it will automaticallybecome active in the next 2016 block period. However, so far SegWit has been met withresistance from mining companies who favor the deployment of Bitcoin Unlimited’sproposed changes. Currently as of May 2017 only 30% of all blocks signal support (seeFigure 2.2) and it is unlikely that SegWit will reach the 95% goal. Miners might fear adeclining income from transaction fees, as the activation of SegWit would allow easieroff-chain payment solutions.

On the alternative cryptocurrency Litecoin, which is similar to Bitcoin, SegWit was re-cently successfully activated [13]. It remains to be seen whether this has any impactfor bitcoin.

Page 18: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

8 CHAPTER 2. BACKGROUND AND RELATED WORK

Transaction

Version 4 bytes

Input Counter 4 bytes

List of Inputs

Prev Hash 32 bytes

Index 4 bytes

Signature length 1-9 bytes

Signature (variable length)

Sequence no. 4 bytes

Output Counter 4 bytes

List of Outputs

Value 8 bytes

Length of pubKeyScript 1-9 bytes

pubKeyScript var length

Locktime 4 bytes

SegWit Transaction

Version 4 bytes

Input Counter 4 bytes

List of Inputs

Prev Hash 32 bytes

Index 4 bytes

Signature length 0x00 1 byte

Sequence no. 4 bytes

Output Counter 4 bytes

List of Outputs

Value 8 bytes

Length of pubKeyScript 1-9 bytes

pubKeyScript var length

Witness data (variable length)

Locktime 4 bytes

Figure 2.3: Comparison of a standard transaction and a SegWit transaction. Shadedblocks are part of the transaction hash.

2.4 Micropayment Channels

Each transaction broadcast needs to be relayed through the network and then minedin a block. This takes a considerable time and has recently become costly due to hightransaction fees, as discussed in Section 2.1. For larger payments this might not bea problem, but for smaller, transactions this is very inefficient. In cases where smallpayments are made frequently to the same entity, a micropayment channel can be usedto decrease costs and processing time.

A micropayment channel is a construct using bitcoin transactions, which allows twoparties to exchange bitcoin securely in an incremental way, without needing to broad-cast each payment to the network. Instead of creating and broadcasting a transactionfor each payment, a single transaction is updated for each payment and the broadcastis deferred to a later time. This construct can be made in such a way that it does notrequire trust between both parties.

2.4.1 Setup

In the initial step of creating a micropayment channel, the sending entity transferssome funds to an address that both the sender and receiver control. These types of

Page 19: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.4. MICROPAYMENT CHANNELS 9

� Network Sender

2-of-2

Receiver

1) Create funding Tx T1

2) Create time-locked refund Tx T2

3) Send T2 for signing

4) Return signed T2

5) Broadcast T1

Figure 2.4: Micropayment channel setup using refund transaction

addresses are known as MultiSig addresses. A n-of-m MultiSig address needs n out ofm signatures to be spendable. In the case of a micropayment channel, a 2-of-2 addressis used, meaning that neither the sender nor the receiver can spend the money on theirown. The sender sets up the channel by sending money via a funding transaction tothe MultiSig address. However, there must be some mechanism that allows him toget that money back eventually. Otherwise the money might be lost forever, shouldthe receiver disappear. It would also be possible for the receiver to extort money fromthe sender by threatening to not sign any transactions from the newly created address.There are several ways to avoid this scenario.

One solution is to use a refund transaction. This process is illustrated in Figure 2.4. Ini-tially, a funding transaction T1 is created by the sender (1), which he keeps secret. Hethen creates a refund transaction which connects to the funding transaction and sendsall coins in the 2-of-2 MultiSig address back to himself (2). This refund transaction ad-ditionally has a time lock, which prevents a broadcast before some time in the future.This is possible by using the nLockTime field in a transaction [20]. The refund trans-action is then sent to the receiver (3), who signs it and sends it back to the sender (4).Now the sender owns a transaction which gives him the guarantee that he will even-tually get back his money, should the receiver stop collaborating. In the worst case hehas to wait until the lock time is reached. Knowing this, he can then safely broadcastT1 to the network, locking some moeny in the MultiSig address (5) and completing thesetup.

A better solution to a refund transactions exists since 2014, when the OP_CHECK-LOCKTIMEVERIFY command was added to the bitcoin scripting language [30]. Thiscommand allows for conditional script execution, depending on the current time. Itmakes it possible to construct a script, such that two signatures are only needed untila given time. After that only the signature of one entity – in this case the sender – isneeded. Similar to the previous setup, this gives the same guarantees for both enti-ties, but is much simpler in comparison to the refund transaction method. The currentCoinblesk implementation already uses time-locked-addresses with OP_CHECKLOCK-TIMEVERIFY for securely locking funds in a MultiSig address.

Page 20: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

10 CHAPTER 2. BACKGROUND AND RELATED WORK

Sender

Inputs Outputs

Sender: 9

Receiver: 1

Sender

Sender

Inputs Outputs

Sender: 7

Receiver: 3

Sender

SenderReceiver

Inputs Outputs

MultiSig: 10 Sender: 6

Receiver: 4

Signatures Time

Figure 2.5: Updates to an open micropayment channel

2.4.2 Micro Payments

After some initial money is locked in the MultiSig address, the sender make a firstpayment. He creates a new transaction that spends the money in the MultiSig addressand sends a small amount to the receiver and the rest back to himself. This channeltransaction is then signed by the sender. At this point the transaction is still not valid,as it needs the second signature from the receiver. After the sender sends the channeltransaction to the receiver, the payment is concluded.

The receiver now owns a transaction that when signed and broadcast, pays him someamount. The sender on the other hand is missing the receiver’s signature and is notable to broadcast on his own. As the receiver expects further payments, he will chose todefer the broadcast to a later time. The sender creates for the next payment an updatedversion of the last channel transaction, in which the balances to both parties is adoptedaccordingly: the output to the receiver is increased, while the output to the sender isdecreased. This updated transaction is sent to the receiver and the previous version ofthe channel transaction is discarded. The process is repeated for every payment with-out needing to broadcast to the network (see Figure 2.5). Only when the funds in theMultSig address are depleted is the last channel transaction broadcast and the channelclosed. However, the receiver must also broadcast the current transaction before that,should the lock-time of the MultiSig address run out. Otherwise the sender is be ableto spend the entire amount in the current micropayment channel by himself.

It is important to note that this micropayment channel can only be unidirectional,meaning it not possible to send money back with an updated transaction: a changeof the channel transaction in favor of the sender would not prevent the receiver tobroadcast an older transaction that is more beneficial for him.

Page 21: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.5. THE LIGHTNING NETWORK 11

2.5 The Lightning Network

The lightning network as proposed by Poon and Dryja is an decentralized overlay net-work that builds on top of bitcoin. Lightning uses micropayment channels betweennodes to enable highly scalable off-chain transactions [23]. Payments are routed overthe mesh network of payment channels until they reach the receiver. This design ismade in such a way, that avoids the need for trust. Assuming that participants coop-erate with each other, apart from the initial funding transactions and the final closingtransaction, payments can work outside the bitcoin network and can avoid high feesor delays for confirmation.

2.5.1 Bi-directional Payment Channels

Micropayment channels as discussed in section 2.4 only allow for transfers in one di-rection. The lightning network suggests a new construct, that allows payments to bemade in both directions without having to rely on trust. In comparison to plain mi-cropayment channels, such a channel is initially funded by both parties equally. Foreach update inside the channel a pair of revocable commitment transactions is generated,equivalent to channel transactions. Both entities own a different version of this trans-action, which allows to ascribe blame later in case of non-cooperation. A set of breachremedy transactions is used to invalidate prior channel transactions. These transactionsrevoke older commitment transactions by imposing a penalty upon a broadcast of anold commitment transaction. The penalty allows the other party to spend all funds in-side the channel, leaving the non-cooperative party with nothing. This makes it save tosend money in both directions, as no party has an incentive to broadcast an invalidatedtransaction [23].

2.5.2 Hashed Timelock Contracts

For the lightning network it is unfeasible to connect all nodes to a fully meshed net-work, as doing so would result in a quadratic increase of setup costs. Instead, usersneed to only have one open channel with a participating node. This requires paymentsto be routed across a network of payment channels. As intermediate nodes can not betrusted, this comes with with its own challenges.

Lightning solves this by introducing the concept of hashed timelock contracts (HTLC).An HTLC is a contract with two possible execution paths: coins sent to an HTLC arespendable either by the sending party after a fixed timespan has passed, or by thereceiver if he can provide a secret in form of a string. This construct can then be used tosend coins along a path in the lightning network, by making each payment to the nexthop contingent on the knowledge of the secret. This process works in the followingway:

Page 22: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

12 CHAPTER 2. BACKGROUND AND RELATED WORK

(1) Alice

H

Payment Channel

Alice 0.5Charlie 0.5

Charlie

Payment Channel

Charlie 0.5Bob 0.5

Bob

S H

(2) Alice

H

Payment Channel

Alice 0.4Charlie 0.5HTLC 2 days 0.1

Charlie

H

Payment Channel

Charlie 0.5Bob 0.5

Bob

S H

(3) Alice

H

Payment Channel

Alice 0.4Charlie 0.5HTLC 2 days 0.1

Charlie

H

Payment Channel

Charlie 0.4Bob 0.5HTLC 1 day 0.1

Bob

S H

(4) Alice

H

Payment Channel

Alice 0.4Charlie 0.5HTLC 2 days 0.1

Charlie

S H

Payment Channel

Charlie 0.4Bob 0.6

Bob

S H

(5) Alice

S H

Payment Channel

Alice 0.4Charlie 0.6

Charlie

S H

Payment Channel

Charlie 0.4Bob 0.6

Bob

S H

Figure 2.6: Routing payments with HTLC contracts

Page 23: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.5. THE LIGHTNING NETWORK 13

Assuming Alice wants to send 0.1 BTC to Bob via an intermediate node Charlie. Aliceis connected to Charlie and Charlie is connected to Bob each via a bi-directional pay-ment channels as explained in Section 2.5.1. After Alice made her intentions clear toBob and a suitable routing is found from Alice to Bob, the following procedure illus-trated in Figure 2.6 takes place:

1. Bob creates a secret string S and a corresponding hash H = hash(S), where hashis a cryptographic one-way hash function. Bob sends H to Alice.

2. Alice sends H to Charlie and they agree to update their payment channel byincluding a new 0.1 BTC HTLC output, which is redeemable after 2 days by Alice,or at any time by Charlie, if he can prove the knowledge of the secret S.

3. Charlie sends H to Bob, proving that he received a payment from Alice. Theyalso create a HTLC output in their channel, which is redeemable after 1 day byCharlie or by Bob if he can provide the secret S.

4. Bob sends S to Charlie, which gives Charlie the guarantee that he can get 0.1 BTCimmediately from Alice. Knowing that, Charlie agrees to update the channelwith Bob, sending him 0.1 BTC.

5. Charlie sends S to Alice, proving that he has paid Bob and they agree to updatetheir payment channel to send 0.1 BTC to Charlie.

6. The payment is concluded as the 0.1 BTC was successfully routed over the twopayment channels.

This routing design is fully trust-less, as no involved party is able to steal funds. Alsothe payment is atomic in that it either fully succeeds or is rolled back:

• If Charlie refuses cooperation after step 2, Alice can wait 2 days to get her moneyback.

• If Bob refuses cooperation after step 3, Charlie can wait 1 day to get his moneyback and then 1 day later Alice is paid back.

• If Bob does not send the secret to Charlie in step 4, he can not steal the BTC 0.1HTLC output without revealing the secret: Charlie can monitor the network andthen use the secret to retrieve the 0.1 BTC HTLC from Alice.

• If Charlie does not update the payment channel in step 4 after receiving the secret,Bob can use his secret to get the BTC 0.1 from the HTLC output with Charlie.

• If Alice refuses to update her channel with Charlie at step 5, he can use the secretto spend the 0.1 BTC HTLC output.

With this setup, Transactions are only broadcast to the bitcoin network when nodes areuncooperative. In case of cooperation no broadcast is needed. However, nodes mustmonitor the blockchain and time-locks must be large enough to give them the abilityto act in case of non-cooperation.

Page 24: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

14 CHAPTER 2. BACKGROUND AND RELATED WORK

2.5.3 Adoption

Even though the lightning network has many advantages, it has not yet been activatedon the bitcoin network. Since lightning heavily relies on chained off-chain transactions,malleability becomes a limiting factor. Although technically possible, lightning with-out malleability fix would be impractical as it would introduce further complications[21].

Recently an implementation of lightning was used on the bitcoin testnet [12] on whichSegWit has been activated since May 2016 [27]. The testnet is an alternative bitcoinblock chain which is mainly used for development purposes and in which coins do nothave financial value.

2.6 Coinblesk

Coinblesk is a mobile payment solution initially developed at the University of Zurichas part of a masters project [18]. It consists of a mobile android application and a centralserver providing payment services. The current version Coinblesk 3.0 is characterizedby the following features:

Trustless Design There is no trust involved in depositing money with the server. Fundsare secured by using time-locked 2-of-2 MultiSig addresses.

Zero Confirmation Transactions Payments between Coinblesk users are checked fordouble spends by the server and are confirmed in less than two seconds.

Wireless Mobile Payments Wireless payments are possible via Near Field Commu-nication (NFC) or bluetooth without requiring Internet connectivity from thesender.

2.6.1 Payment Mechanism

Payments in Coinblesk 3.0 involve the following steps:

1. Key exchange: The client generates a new key pair and sends his public key to theserver. The server also generates a new key pair and sends his public key back.The public key of the client is saved along with the server key pair on the server.This step is a requirement for all other operations with Coinblesk.

2. Create new address: The client creates a time-locked 2-of-2 MultiSig address andregisters it with the server. Funds from this address require signatures from boththe client and the server. A time lock on the address allows the client to spendany funds individually after a certain time, i.e. 3 months. This prevents extortionpossibilities from the server and puts a time limit on the validity of the address.Periodically the client has to generate a new address when the lock-time runs out.

Page 25: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

2.6. COINBLESK 15

3. Placing funds The user sends bitcoin to the the newly created address.

4. Verify transaction When the client wishes to make a payment he creates a newtransaction spending from the 2-of-2 MultiSig address created in step 2. He signsthe transaction and sends it to the server. The server then verifies the transactionand signs with his own key before broadcasting it to the bitcoin network. Pay-ments to other Coinblesk user’s MultiSig addresses can be immediately spendagain (instant payments). This is possible because the server keeps track of allpayments made to its users and checks for double spending.

2.6.2 Problems

The current system comes two main drawbacks:

Transaction Fees The user has to pay a transaction fee for each payment made withCoinblesk. This cost can be a significant, especially for smaller purchases: a min-imal transaction between two Coinblesk user currently costs at least USD 1.52 4.Transactions with more inputs are even more expensive. This makes Coinbleskinfeasible for point-of-sale purchases such as in the originally intended use-caseas a payment solution for a cafeteria.

Security When transactions are made between Coinblesk users, the resulting unspenttransaction outputs (UTXO) can be immediately spent again. Due to the cur-rently missing malleability fixes in the bitcoin protocol, this makes those chainedtransactions unsafe. A malleability attack such as the one observed in March 2017[3] would have caused all chained transactions to become invalid, as the changedtransaction ID would have broken the chain, resulting in lost funds for Coinbleskusers.

Other minor problems with the current system are:

Non-deterministic Signatures in Requests Coinblesk uses signatures in the data trans-fer objects (DTO) to verify the authenticity and integrity of a request. Currentlythis is done by signing the hash of the JSON encoded payload and then addingthe signature to the DTO as a separate field. However, in order to reproducethe same hash for signature validation, the system must currently transform theJSON to a canonical format by sorting the keys, removing whitespaces and forc-ing line breaks at specific positions. This process is error prone, as JSON objectserialization can vary significantly between frameworks. Currently this does notcause issues, as both the server and client share the same codebase for DTO gen-eration. But for the planned release of a web client, this could become an issue.

4Assuming one input and two outputs resulting in a transaction size of 342 bytes. Fee: 240satoshi/byte (bitcoinfees.21.com) Exchange rate: 1’850 USD/BTC (bitstamp.net) as of May 11, 2017

Page 26: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

16 CHAPTER 2. BACKGROUND AND RELATED WORK

Fixed transaction fees Currently Coinblesk uses a fixed hard-coded fee for transac-tions. However the required fee for a fast block inclusion is dynamic and canchange at any time. Requesting this fee from an external service would be thebetter option.

Outdated Codebase Coinblesk has seen many iterations over the last years. This hasleft the codebase in a sub-optimal state. There are outdated library dependen-cies and unused or untested code paths. Additionally some unit tests are non-deterministic as they rely on a given execution order. Also development setupand deployment are non-trivial, as a specific application server is needed.

Page 27: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 3

Design

In this chapter an improved protocol design for Coinblesk is presented, which solvesthe problems discussed in the previous chapter. The design focuses on reducing trans-action fees for payments between Coinblesk users and solves security issues related tomalleability. A high level overview of the new payment architecture is presented andthen formalized.

3.1 Architecture

The design leverages micropayment channels to reduce the transaction fees in subse-quent small payments. One obvious method of using micropayment channels wouldbe to connect all Coinblesk users in a fully meshed network. This however is not fea-sible, since the number of channels and the amount of locked funds would increasequadratic with the number of users.

Instead, all users open a unidirectional payment channel with a central server. Thechannels use 2-of-2 MultiSig addresses and are funded by the users. The server tracksa virtual balance for each user, which indicates the amount owed by the server. Smallpayments between users can be made by sending coins over the payment channel tothe server, which will then increase the virtual balance of the intended receiver. Userscan request to be paid their virtual balance. The server has an initial buffer of funds andcloses channels if needed, to ensure that payouts can be fulfilled at any time. The serveralso closes channels shorty before the lock-time of a MultiSig address runs out. Forlarger payments, the receiver’s address can be directly added to the current channeltransaction and then broadcast, closing any existing channel.

Figure 3.1 illustrates this concept. It shows the state of the system after the follwingsteps:

1. The server has an initial pot of 100 BTC

17

Page 28: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

18 CHAPTER 3. DESIGN

Server

User BalanceAlice 0Bob 3Carol 0Dan 5

Server Pot: 93

ChannelServer: 8Alice: 2

ChannelServer: 7Bob: 3

Channel<none>

Channel<none>

gAlice

gBob

gCarol

gDan

Figure 3.1: Users open micropayment channels with the server. The server has aninternal accounting for each user and a buffer to pay out balances.

2. Alice and Bob load 10 BTC to their MultiSig addresses.

3. Alice sends 3 BTC to Bob

4. Alice sends 5 BTC to Dan

5. Bob sends 7 BTC to Carol

6. Carol pays out her 7 BTC

3.2 Model

This section describes the formal model for all payment operations in the new system.

Definition 1. Let i denote a user in the system, bi the virtual balance of user i and ci the serveroutput value in the current payment channel of user i, with ci = 0 if no channel is open. Themaximum server output in a channel is given by cmax and the initial pot size of the server isdefined as pinitial and the current pot size as p. Further C = {c1, ..., cn} is the set of all paymentchannels and B = {b1, ..., bn} is the set of all virtual balances. The server state can be definedby the tuple S = (pinit, p, B, C, cmax)

A virtual payment transfers balance from one user to another. No actual bitcoin trans-actions are created. The balance of the sender is decreased and the balance of thereceiver increased. virtualPayment(i, j, a) transfers a coins from user i to user j:

Page 29: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

3.2. MODEL 19

virtualPayment(i, j, a) : S→ S′ with

virtualPayment(i, j, a) = (pinit, p, B′, C, cmax) for i 6=, a > 0

B′ = {b1, ..., bi − a, ..., bj + a, ..., bn}

A micropayment sends coins over the micropayment channel to the server and in-creases the receiver’s virtual balance. microPayment(i, j, a) sends a coins from user i touser j:

microPayment(i, j, a) : S→ S′

microPayment(i, j, a) = (pinit, p, B′, C′, cmax) for a > 0, ci + a ≤ cmax

B′ = {b1, ..., bj + a, ..., bn}C′ = {c1, ..., ci + a, ..., cn}

Closing the channel broadcasts the current channel transaction. closeChannel(i) resetsthe channel for user i and increases the server pot by the amount ci:

closeChannel(i) : S→ S′

closeChannel(i) = (pinit, p′, B, C′, cmax)

p′ = p + ci

C′ = {c1, ..., ci−1, 0, ci+1, ..., cn}

A payout sends coins from the server pot to an address chosen by the user. This de-creases the server pot and resets the virtual balance of the user to zero:

payout(i) : S→ S′

payout(i) = (pinit, p′, V′, C, cmax)

V′ = {v1, ...vj−1, 0, vj+1, ..., vn}p′ = p− a

Note that virtual balances are reflected by corresponding channel transactions untileither the channel is closed or a payout occurs. This can be used to derive a equationfor the equilibrium of the system which holds true at all times and can be used to checkcorrectness:

Page 30: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

20 CHAPTER 3. DESIGN

Lemma 1. At any time the difference between the sum of all virtual balances and the sum ofall pending channel transactions is equal to the difference of the current and the initial serverpot size:

n

∑i=1

vi − ci = c− cinit (3.1)

3.3 Protocol

The following sections describes the protocol for using the new payment model fromthe perspective of the user and the server. Implementation specific details are dis-cussed in Chapter 4.

3.3.1 User Operations

Coinblesk users are able to perform the following operations:

Key Exchange A user sends his public key to the server, which will then respond withhis own user specific public key. This is equivalent to the old system and acts asa registration process. The key exchange has to be done once per user.

Create Timelocked Address After the initial key exchange, the user creates a new bit-coin address. This address is a 2-of-2 MultiSig address that requires both signa-tures from the exchanged keys. It is also defined by a user-chosen lock-time, atimestamp set in the future, after which the client is able to spend funds in theaddress without the involvement of the server. This lock-time gives the user theguarantee that he will eventually be able to retrieve his funds in case of an un-cooperative server. The client then registers this new address with the server.After the lock-time is reached, he must create a new address, as the server willnot accept any payments involving an unlocked address. The process must berepeated every 1–2 months, depending on the chosen lock-time.

Funding of Address In order to make any payments, the user must load some fundsinto one of his time-locked addresses. The method of funding is left to the user.He can use any wallet or bitcoin exchange provider or be funded by a differentCoinblesk user. After a funding transaction was made, he must wait for at leastone block for the transaction to be confirmed. The server does not accept uncon-firmed transactions.

Micropayment to Coinblesk User Smaller payments to other Coinblesk users can beexecuted with a micropayment channel transaction. This requires some unspentand mined funds to be available in a time-locked address. It is possible to usemultiple previously created addresses as inputs, as long as they are all locked.

This operation depends on the existence of an open channel transaction:

Page 31: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

3.3. PROTOCOL 21

1a) There is no current channel transaction:

1. The user creates a new channel transaction with inputs from his time-locked addresses.

2. An output to the server is added with the amount he wants to transfer

1b) There exists a current channel transaction:

1. The user retrieves the current channel transaction (possibly saved offlineat the client or fetched from the server).

2. The output to the server is increased by the amount that should be trans-fered.

2) The transaction is signed by the user and sent to the server along with thereceiver’s public key.

3) The server adds his signature to the channel transaction and saves it for laterbroadcast. The receiver’s virtual balance is increased.

Virtual Payment to Coinblesk User A user that has received micropayments can usehis virtual balance to directly transfer funds to other Coinblesk users. This is avery cheap and efficient way to transfer coins, as it is a simple database changeand does not involve any bitcoin related operations.

1) The user creates a payment request that includes the amount to transfer andthe public key of the receiving Coinblesk user.

2) The request is sent to the server.

3) The server decreases the balance of the sender and increases the balance ofthe receiver.

External Payment Larger payments or payments to non-Coinblesk users also requireunspent and mined funds to be available in a time-locked address. Again, de-pending on the existence of an open channel transaction, the user performs thefollowing steps:

1a) There is no current channel transaction:

1. The user creates a new transaction with inputs from his time-locked ad-dresses.

2. An output to the receiver’s address is added with the desired amount

1b) There exists a current channel transaction:

1. The user retrieves the current channel transaction (possibly saved offlineat the client or fetched from the server).

2. The user adds an additional output to the transaction with the receiver’saddress and the desired amount. The output to the server remains un-changed.

2) The transaction is signed by the user and sent to the server.

3) The server adds his signature and broadcasts the transaction to the network.The sender’s account is locked until the transaction is mined in a block.

Page 32: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

22 CHAPTER 3. DESIGN

Closing a Channel The user may chose to close his channel at any time:

1) The user retrieves the current channel transaction (possibly saved offline atthe client or fetched from the server).

2) (Optional) The change address can be modified. This might be useful ifthe user wishes to send the change to a newer time-locked address, or if hewants to pay out the change to an external address.

3) The user signs the inputs and sends the channel transaction to the server.

4) The server adds his signature and broadcasts the transaction to the network.The sender’s account is locked until the transaction is mined in a block.

Payout If a user has a positive virtual balance he can request a payout:

1) He sends a payout request to the server with the desired destination address.

2) The server broadcasts a transaction sending the virtual balance of the userminus the required fee to the given address. The virtual balance of the useris reset to zero.

3.3.2 Server Operations

The server performs the following operations:

Closing of Channels The server can close a payment channel at any time. This is doneby broadcasting the latest saved channel transaction to the network and lockingthe user’s account until the transaction is mined in a block. The server closes achannel in the following cases:

• A payment channel is about to expire: The Server must close a channel be-fore any of the input’s time-locked addresses expires. Failing to do so wouldallow the user to spend the input, rendering the channel transaction invalidand result in lost funds for the server.

• The server pot is low: To retain the ability to meet payout requests, theserver closes channels whenever tho pot falls below a configurable limit.The server closes channels in decreasing order of value until the limit isreached again.

• Rising transaction fees: The server closes a channel if the fee of a channeltransaction becomes significantly lower than the current fee needed in thebitcoin network. This limits the risk of an unsuccessful broadcast due to lowfees, which could cause lost funds for the server.

Increasing/Decreasing Pot Size The server administrator might choose to increase thepot size for more liquidity in the system. Likewise coins can be taken out fromthe pot if they are needed elsewhere.

Page 33: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

3.4. TRANSACTION FEES 23

3.4 Transaction Fees

Transaction fees have to be paid for every transaction broadcast to the network. Feesfor the user occur during the following operations:

Funding The initial and any subsequent funding of time-locked addresses are paid bythe user. This process has to be repeated if the funds are depleted. The user cansave transaction fees by transferring a larger initial amount to his time-lockedaddress.

Micropayments The first channel transaction sent to the server must include a validfee. Subsequent transactions however are free for the user, as long as the channelstays open. If the network becomes more saturated, transactions might needlarger fees for faster confirmation. In this case the additional costs are passed onto the user, who is forced to increase the fee in the channel transaction in his nextmicropayment.

Payout When a users wants to retrieve his virtual balance, he has to pay the fee for therequired transaction. The server subtracts the fee from the virtual balance. Thisalso means that it is not possible to pay out very small amounts, lower than asingle transaction fee.

The server does not pay any transaction fees, except when increasing the server pot.

Page 34: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 35: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 4

Implementation

This chapter describes the specific details and design decisions of the implementedchanges to the current Coinblesk 3.0 server. The resulting system is from here on re-ferred to as Coinblesk 4.0.

4.1 Refactoring

Coinblesk has seen lots of iterations over time by many different developers. This hasleft the codebase in need for maintenance. Therefore, the initial focus of this thesis wasa major refactor of the existing codebase to reach a more maintainable state.

4.1.1 Spring Boot

The web framework used in the server part of Coinblesk 3.0 is Spring Framework [29].Spring Framework is very modular and provides packages for different needs. How-ever, there is a lot of configuration overhead involved when using Spring Frameworkdirectly. Especially for smaller projects a better solutions exists with the simplifiedFramework called Spring Boot [28], which uses the same libraries but hides a lot ofthe configuration overhead by using a set of default conventions. In the context ofCoinblesk, the switch from Spring Framework to Spring Boot came with the followingnotable benefits:

Better Dependency Management Future upgrades of the framework only require asingle version change in the dependency graph. Spring Boot handles the depen-dency management of the underlying Spring Framwork, which prevents acci-dentally using incompatible components. This will ensure an easier and saferupgrade plan for future Coinblesk releases.

25

Page 36: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

26 CHAPTER 4. IMPLEMENTATION

Simpler Development Setup The initial steps needed to start developing with SpringBoot is significantly lower. To run a basic version of Coinblesk, only a Java VirtualMachine is needed. Spring Boot provides an embedded database and applicationserver. This makes Coinblesk more attractive for outside contributions. Pleaserefer to Appendix A for instructions on how to install Coinblesk.

Simpler Deployment Spring Boot can produce a single build artifact in form of anexecutable JAR file. This makes it easier to deploy Coinblesk and can help insetting up a continuous integration pipeline.

Less Configuration The switch to Spring Boot resulted in less moving parts in thesystem, reducing the overall complexity. This can help to prevent bugs in thesystem, which is especially crucial in the context of a payment solution.

Easier Testing Spring Boot provides a lot of functionality for testing. Especially usefulin the case of Coinblesk is the ability to have transactional tests for better testisolation.

4.1.2 Token Security

Coinblesk 3.0 uses a session based authentication method based on HTTP cookies. Thiswas replaced by a token based authentication method using Java Web Tokens [15].

In a token based authentication model, the client sends his credentials to a authentica-tion server, which then checks them against a database. On success, a token containingclaims of the user, such as user name and role is generated and signed with a secretkey. The sever sends the token to the user, which uses it for all authenticated requests.The server checks for each request the claims in the token and validates its signature.There is no need for the server to keep a record of who is logged in. The process isillustrated in Figure 4.1.

This mechanism comes with several benefits for Coinblesk:

Stateless RESTful Endpoints The server does not keep a session in memory as withthe default cookie approach. Since RESTful endpoints should be stateless by de-sign [24], this makes it a good solution for Coinblesk. Additionally, no databasequeries have to be made in each request to fetch authorization information.

Horizontal Scaling The stateless designs allows for easy horizontal scaling. Multipleinstances of of the system can be started and requests load-balanced betweenthem. The authentication provider can be replaced by an external service.

Extensibility More information can be stored inside the token if needed. An inter-esting extension for Coinblesk could be to include the public key or an addressof the user in the token. This way the server could avoid costly requests to thedatabase.

Page 37: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

4.1. REFACTORING 27

Client Server Database)

usernamepassword

check(user, pass)

ok

/login/login

token

request params + token

validateToken()

ok

/auth/admin/events/auth/admin/events

ok

Figure 4.1: A simple token based authentication model

4.1.3 Signed Requests

By signing requests with the public key of the sender, any tampering by intermediariescan be detected. However, such signatures should be verifiable independent from theused technology and serialization framework (see discussion in Section 2.6.2). There-fore a new method was designed that removes any ambiguity of the signing process.Signatures are created and validated in the following way:

1. The payload is encoded into a JSON representation. As an example, a virtualpayment request would encode to the following string:

{"fromPublicKey": "03857fce5293d4e0e5374ce64...","toPublicKey": "02857fce5293d4e5374ce6d4e...","amount": 95300,"nonce": 1494186194575

}

2. The Base64 encoding [16] of the resulting string is generated:

ewogICJmcm9tUHVibGljS2V5IjogIjAzODU3ZmNlNTI5M2Q0ZTBlNTM3NGNlN...

Page 38: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

28 CHAPTER 4. IMPLEMENTATION

3. The ECDSA signature [14] is calculated by using the SHA-256 hash of the Base64string and the same curve parameters as the bitcoin network:

sig = (r, s) = ECDSASecp256k1(privateKey, sha256(base64)) = (936533 . . . , 768935 . . . )

4. The final Signed DTO is generated using the Base64 string and the two integersfrom the signature:

{"payload": "ewogICJmcm9tUHVibGljS2V5IjogIjAzOD...","signature": {"sigR": 936589533...,"sigS": 768935683...

}}

Decoding a Signed DTO works in the other direction: The payload is convertedback from Base64 to a JSON string, which is then decoded. The containing publickey is used to check the SHA256 hash of the payload Base64 string against thesignature.

Note that in this setup JSON encoding differences between sender and receivercan not cause the signature to become invalid. This is a prerequisite for futuresupport of non-Java clients.

4.2 Data Model

The relational data model of the previous Coinblesk system was used whenever pos-sible. Several new fields were added to the user accounts table:

Channel Transaction Holds the latest fully signed channel transaction in the bitcoinserializaion format. Can be empty if there is currently no open channel.

Locked Boolean flag indicating whether the account is currently locked. An accountis locked after a channel transaction is broadcast and unlocked after it is success-fully mined.

Nonce An integer value that holds the nonce from the latest successful request of auser. Payment related requests from the user contain a nonce, which must bestrictly larger than the current nonce. This guarantees that each request is onlyexecuted once and prevents a possible replay attack.

Broadcast Before A timestamp that indicates the latest time when the current channeltransaction must be broadcast to the network. This is equal to the first time-lockof the input addresses in the current channel transaction. The server uses thisfield to check for expiring payment channels.

Page 39: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

4.3. REST ENDPOINTS 29

4.3 REST Endpoints

To support the new protocol, several new endpoints were implemented. The previ-ously used endpoints /sign, /sign-verify and /verify were deprecated, as they areincompatible with the new system.

4.3.1 /virtual-payment

This endpoint performs a virtual payment and consumes a data structure, which issigned using the mechanism described in Section 4.1.3. The following parameters areincluded in the request:

Sender Public Key The public key of the sending user in hexadecimal format. Thesignature is checked against this key.

Nonce An integer valued number that must be strictly higher than in thelast successful request by the sender.

Receiver Public Key The public key of the receiving user in hexadecimal format.

Amount The amount in satoshi to tranfer from the sender’s virtual balanceto the receiver.

The server performs the following steps:

1. The signature and nonce of the request is validated.

2. The sender’s balance is checked for sufficient available funds.

3. The payment is executed by decreasing and increasing the balances of the senderand receiver.

4. The nonce field for the sender is set to the nonce in the request.

5. A signed response is returned, containing the new virtual balances of both users.

4.3.2 /payment

This endpoint is responsible for performing the following operations:

• Micropayment

• External Payment

Page 40: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

30 CHAPTER 4. IMPLEMENTATION

• Closing of Channel

A signed request is given with the following parameters:

Sender Public Key The public key of the sending user in hexadecimal format. Thesignature is checked against this key.

Nonce An integer valued number that must be strictly higher than in thelast successful request by the sender.

Channel Transaction The partially signed channel transaction in the bitcoin serializationformat.

For a micropayment, the request contains the following additional parameters:

Receiver Public Key The public key of the receiving user in hexadecimal format.

Amount The amount in satoshi that the user wants to send to the receiver.This value is redundant, as it could be derived by taking the dif-ference of the current and last channel transaction’s output to theserver. The explicit inclusion is used to protect the user from acci-dentally sending a wrong amount.

The server performs the steps shown in Figure 4.2.

4.3.3 /payout

This endpoint allows a user to pay out his virtual balance to a chosen address. Thesigned request includes the following parameters:

Sender Public Key The public key of the sending user in hexadecimal format. Thesignature is checked against this key.

Nonce A integer valued number that must be strictly higher than in thelast successful request by the sender.

Address A String containing the bitcoin address to which the coins shouldbe transfered to.

The server performs the following steps:

1. The signature and nonce of the request is validated.

Page 41: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

4.3. REST ENDPOINTS 31

Request cor-rectly signed? Failed

Sender ac-count locked?

Transaction isvalid and con-

tains enough fee?

Fresh nonce?

All inputs unspent,signed, mined andtimelocked for atleast 24 hours?

Channel amountminus previous

channel amount equalto requested amount?

Broadcast transaction Receiver in database?

Channel amountbelow maximum?

Save chan-nel transaction

Increase receiverbalance by amount

Save nonce

Return success

Lock accountTransaction mined

Unlock Account

[yes]

[no]

[yes]

[yes]

[yes]

[no]

[yes]

[else]

[no]

[no]

[no]

[yes && amount>0]

[yes]

[no]

[yes]

[no]

[yes && amount=0]

Figure 4.2: Server verification process for the /payment endpoint

Page 42: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

32 CHAPTER 4. IMPLEMENTATION

2. The server checks for enough funds in the pot. Should the server pot currentlynot contain enough funds to meet the request, channels are closed as needed andthe user must try at a later time.

3. The required fee is calculated and subtracted from the user’s virtual balance.

4. A transaction sending the resulting amount to the address given in the request isbroadcast.

5. The virtual balance of the sender is reset to zero.

4.4 Offline Payments

For a successful payment in a mobile scenario, only the sender or receiver needs net-work connectivity to the server. If the sender is offline, the payment request can be sentto the receiver via a wireless transmission protocol such as NFC or bluetooth, and thenrelayed to the server. The signatures and nonce included in the request guarantee thatthe request can not be modified by the relaying node and no replay attack is possibleby sending the request multiple times. As the response from the server is also signed,it can be forwarded back to the sender, confirming a successful transfer. An exampleof such a payment is shown in Figure 4.3.

4.5 Testing

The implemented changes where thoroughly tested by using the provided test frame-work of Spring Boot. The newly implemented features are covered by 56 new inte-grations tests. Another 34 tests covering previously existing operations were eitherwritten from scratch or heavily refactored. The Coinblesk 4.0 payment service classhas a 96% line coverage. A total of 124 tests currently run as part of the continuousintegration pipeline.

4.5.1 Full Integration Test

Some features of Coinblesk 4.0 required a more elaborate setup. Notably the inter-action with other bitcoin nodes was previously untested. A full integration test wasadded that connects to a local Bitcoin Core node running a private blockchain. Thetests covers a full payment scenario between two users and a merchant and uses allpayment operations available in Coinblesk. After each operation in the test, all bal-ances and transactions are checked to be in a valid state. The usage of an externalnode ensures that channel transactions are correctly relayed by the network and thatthe system adheres to the rules of the current version of Bitcoin Core. The test alsouses the integrated remote procedure call (RPC) features of Bitcoin Core to artificially

Page 43: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

4.5. TESTING 33

:Payee :Payer (offline) Server Database

requestForPayment()amount: <long>toPubKey: <hex>

MicroPaymentRequestDTOtransaction: <bytes>fromPubKey: <bytes>toPubKey: <bytes>amount: <long>nonce: <long>

microPaymentRequestDTO

update()

/payment/payment

MicroPaymentResponseDTObalanceReceiver: <long>timeOfExecution: <long>

microPaymentResponseDTO

Figure 4.3: Offline payment with the /payment endpoint

Page 44: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

34 CHAPTER 4. IMPLEMENTATION

mine blocks when needed. As this test requires a local Bitcoin Core node to be run-ning, it can not be executed as part of the continuous integration pipeline. It should bemanually executed by the developer before each deployment.

4.5.2 Load Test

To test the throughput and isolation level of the underlying database, a load test wasadded. This test spawns three threads, each representing a user. Each thread thenrepeatedly sends coins to the next user, creating a closed circle of payments. The testruns for ten seconds while a fourth thread checks that the total sum of balances neverchanges to an inconsistent state and no deadlocking occurs.

Page 45: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 5

Evaluation

This chapter evaluates Coinblesk 4.0 against the previous implementation. The mainfocus lies on the reduction of transaction fees. Other aspects such as security and gen-eral features are also compared and limitations highlighted.

5.1 Transaction Fees

To evaluate the impact of the new payment system on the total of transaction fees,a simulation was run with four distinct user profiles. Each profile spends the sameUSD 310 over the course of a month but uses a different mix of small, medium andlarge sized payments. The specific profiles are shown in Table 5.1. Each profile alsosends some payments to external addresses outside of Coinblesk. The external profileexclusively uses external payments.

Assuming an exchange rate of 1800 USD/BTC 1, the transaction fees are calculatedfor all profiles using Coinblesk 3.0, Coinblesk 4.0 and plain pay-to-public-key-hash(P2PKH) bitcoin transactions. Each transaction is assumed to have a single input andtwo outputs. The difference in signature length between plain P2PKH transactionsand Coinblesk transaction is accounted for. For Coinblesk 4.0, the payment order isrelevant and the resulting fees were averaged over 1000 simulation runs. The resultsof the simulation are shown in Figure 5.1 and Table 5.1.

It can be clearly seen that the transaction fees for P2PKH payments and Coinblesk3.0 directly correlate with the number of payments made, as each payment triggersa transaction to the network. The higher fee in Coinblesk 3.0 in comparison to directP2PKH transactions is the result of larger transaction sizes due to the longer signaturesfrom timelocked MultiSig addresses.

For a large amount of small payments, Coinblesk 4.0 outperforms direct P2PKH pay-ments and Coinblesk 3.0 by 95% and 96% respectively. As transactions are only broad-cast for each external payment and after the channel amount of USD 100 is reached,

1Source: bitstamp.net as of May 14th 2017

35

Page 46: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

36 CHAPTER 5. EVALUATION

small medium large external0

50

100

150

200

250

300

Sum

oftr

ansa

ctio

nfe

esU

SD

Direct P2PKHCoinblesk 3.0Coinblesk 4.0

Figure 5.1: Transaction fee for different payment profiles.

Profile

per month small medium large external

Number of payments to Coinblesk user

small (USD 1) 200 5 0 0

medium (USD 10) 6 23 1 0

large (USD 25) 0 1 10 0

Number of external payments (USD 10) 5 5 5 31

Total number of payments 211 34 16 31

Total sum of payments 310 310 310 310

Direct P2PKH paymentsa

Number of broadcasted transactions 211 34 16 31

Total fees in USD 188.84 30.43 14.32 27.74

Coinblesk 3.0b

Number of broadcasted transactions 211 34 16 31

Total fees in USD 285.76 46.05 21.67 41.98

Coinblesk 4.0bc

Number of broadcasted transactions 7.51 7.38 7.07 31

Total fees in USD 10.17 10.00 9.57 41.98a Assuming transaction size of 226 bytes.b Assuming transaction size of 342 bytes.c Maximum channel size USD 100. Average taken from a sample of 1000 random payment orderings.

Table 5.1: Evaluation profiles for transaction fees

Page 47: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

5.2. FEATURES 37

Direct Transactions Coinblesk 3.0 Coinblesk 4.0

Transaction fees high high low

Central system no yes yes

Trust no no limited

Instant payments no yes yes

Secure against malleability yes no yes

Payment speed ~10 min <1 sec <100ms

Offline transactions no yes yes

Table 5.2: Comparison matrix between Coinblesk 3.0 and Coinblesk 4.0

the required fee is decreased drastically. If a user only sends payments to externalnon-Coinblesk users, this advantage disappears and both Coinblesk versions have thesame performance.

Sending more payments to other Coinblesk users in Coinblesk 4.0 has almost no effecton transaction fees. The difference between sending 16 large payments or 211 smallerpayments is 60 cents, or 6%. External payments, however, correlate directly with thenumber of payments made.

5.2 Features

Besides the discussed transaction fees, Coinblesk 3.0 and Coinblesk 4.0 differ in otheraspects. This section describes those differences. The findings are summarized in Table5.2.

Trust Coinblesk 4.0 adds some required trust back to the system. When a user sendssome funds over a micropayment channel, he trusts the server to forward thatmoney to the receiver at some point in the future. Likewise, the receiver truststhe server to receive a payout of his virtual balance from the server. Trust betweenCoinblesk users is not required.

Trust is a clear disadvantage in a payment system. However in Coinblesk 4.0,this trust is very limited. For one it is completely voluntary: the sender can choseto use an external payment instead of the micropayment channel. He will losethe advantage of lower fees but he no longer has to trust the server. Likewise, thereceiver can remove trust in the server by requesting to be paid by an externalpayment. Another method for the receiver is to pay out often. This allows for a avery flexible way of balancing costs and trust. The server also limits the amountin a payment channel to a configurable amount.

Instant Payments Coinblesk 3.0 transactions between users are confirmed instantly.In Coinblesk 4.0 this is equally the case, however with one minor difference:

Page 48: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

38 CHAPTER 5. EVALUATION

when a payment channel is closed, the account is locked until the channel trans-action is mined in a block. This means that no micropayment or external paymentcan be made in that time, which could – assuming a correctly calculated trans-action fee – take up to approximately ten minutes. Even though account lockinghappens irregularly, the client can avoid this limitation in various ways: virtualpayments can still be used when an account is locked. It can be useful to havea positive virtual balance for that case. Additionally the client can pro-activelyclose his channel. Having no open channel guarantees the next payment to beinstant.

Security Transactions in Coinblesk 3.0 were prone to malleability attacks. In Coinblesk4.0 such an attack has no impact, as no transaction input is linked to an unminedtransaction.

Payment Speed Micropayment transactions in Coinblesk 3.0 are confirmed after asuccessful broadcast. A broadcast waits for acknowledgements from all con-nected nodes. A micropayment in Coinblesk 4.0 does not need to interact withthe network and only triggers a database update. This lowers the speed of trans-actions significantly, as no costly network activity is required.

Page 49: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Chapter 6

Summary and Conclusions

The overriding purpose of this thesis was to reduce transaction fees in Coinblesk, a mo-bile payment solution developed by the University of Zurich. An analysis has shownthat transaction fees have been rising significantly over the last few months, as the bit-coin network is closing in on its capacity limit. This trend is likely to continue withbitcoin’s rising popularity and no imminent protocol-based solution in sight. Mean-while Coinblesk with its focus on smaller point-of-sale payments suffers heavily fromthe rising transaction costs.

In order to solve the problem, off-chain payment solutions for bitcoin were examined.Based on the findings, a new payment model for Coinblesk was developed and imple-mented. The new system uses micropayment channels in a spoke-and-hub arrange-ment, which allows most payments to execute off-chain. The new system brings sev-eral advantages. Most notably, a simulation revealed, that transaction fees are low-ered by up to 96% and an increasing number of payments showed no significant im-pact on paid transaction fees. The refactoring of Coinblesk additionally simplified thesetup and maintainability of the system and removed a previous vulnerability basedon transaction malleability.

A downside to the new system is the required trust in the server. This trust, however,was shown to be very limited and can be optionally avoided by the user if desired.The vastly lower costs and other benefits of the new system by far outweigh the risk ofintroduced trust.

As bitcoin is still evolving, the current system should be constantly reevaluated. Futurework might leverage upcoming protocol changes in bitcoin to further improve uponthe payment model and Coinblesk could be extended, to add support for the newupcoming alternative cryptocurrencies.

39

Page 50: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 51: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Bibliography

[1] Marcin Andrychowicz et al. “On the malleability of bitcoin transactions”. In: In-ternational Conference on Financial Cryptography and Data Security. Springer. 2015,pp. 1–18.

[2] Mehmet Ali Bekooglu. “Mobile Bitcoin Payment System (MBPS) Federation”.MA thesis. University of Zurich, 2014.

[3] BitClub Attacks the Bitcoin Network with Transaction Malleability. Mar. 10, 2017. URL:https://www.cryptocoinsnews.com/bitclub- attacks- the- bitcoin-network-with-transaction-malleability/ (visited on 04/28/2017).

[4] Bitcoin Classic. URL: bitcoinclassic.com (visited on 04/24/2017).[5] Bitcoin Core. URL: bitcoincore.org (visited on 04/24/2017).[6] Bitcoin Core v0.10.3 Release Notes. Oct. 14, 2015. URL: https://github.com/

bitcoin/bitcoin/blob/master/doc/release- notes/release- notes-0.10.3.md (visited on 04/28/2017).

[7] Bitcoin Unlimited. URL: bitcoinunlimited.info (visited on 04/24/2017).[8] Bitcoin XT. URL: bitcoinxt.software (visited on 04/24/2017).[9] Luke Dashjr. BIP process, revised. Feb. 3, 2016. URL: https : / / github . com /

bitcoin/bips/blob/master/bip-0002.mediawiki (visited on 04/24/2017).[10] Alessandro De Carli. “Protocol Improvements in Coinblesk - A Mobile Bitcoin

Instant Payment Solution”. MA thesis. University of Zurich, 2016.[11] Christian Decker and Roger Wattenhofer. “Bitcoin transaction malleability and

MtGox”. In: European Symposium on Research in Computer Security. Springer. 2014,pp. 313–326.

[12] Kevin Helms. Lightning Network Used to Sell Beer at Room77. Apr. 3, 2017. URL:https://news.bitcoin.com/lightning-network-beer-room77/ (visited on05/08/2017).

[13] Alyssa Hertig. Litecoin Successfully Activates SegWit. May 10, 2016. URL: http://www.coindesk.com/litecoin-successfully-activates-long-debated-segwit-upgrade/ (visited on 05/16/2017).

[14] Don Johnson, Alfred Menezes, and Scott Vanstone. “The elliptic curve digitalsignature algorithm (ECDSA)”. In: International journal of information security 1.1(2001), pp. 36–63.

[15] Michael Jones, John Bradley, and Nat Sakimura. JSON Web Token (JWT). RFC7519. RFC Editor, May 2015. URL: http://www.rfc-editor.org/rfc/rfc7519.txt.

[16] Simon Josefsson. The base16, base32, and base64 data encodings. RFC 3548. RFC Ed-itor, July 2003. URL: http://www.rfc-editor.org/rfc/rfc3548.txt.

41

Page 52: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

42 BIBLIOGRAPHY

[17] Eric Lombrozo, Johnson Lau, and Pieter Wuille. Segregated Witness (Consensuslayer). Dec. 21, 2015. URL: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki (visited on 05/02/2017).

[18] Jeton Memeti et al. “Bitcoin in Practice”. In: Master Project at University of Zurich(2014).

[19] Satoshi Nakamoto. Bitcoin: A peer-to-peer electronic cash system. 2009.[20] nLockTime. URL: https://en.bitcoin.it/wiki/NLockTime (visited on 05/02/2017).[21] Justin OConnell. Without Segwit There is No Lightning Network. Dec. 24, 2016.

URL: https://www.cryptocoinsnews.com/segwit-lightning/ (visited on05/07/2017).

[22] Giuseppe Pappalardo et al. “Blockchain Inefficiency in the Bitcoin Peers Net-work”. In: arXiv preprint arXiv:1704.01414 (2017).

[23] Joseph Poon and Thaddeus Dryja. The bitcoin lightning network: Scalable off-chaininstant payments. 2015. URL: https://lightning.network/lightning-network-paper.pdf (visited on 05/04/2017).

[24] Leonard Richardson and Sam Ruby. RESTful web services. " O’Reilly Media, Inc.",2008.

[25] Peter R Rizun. A Transaction Fee Market Exists Without a Block Size Limit. 2015.URL: https://www.bitcoinunlimited.info/resources/feemarket.pdf.

[26] Segregated Witness Benefits. Jan. 26, 2016. URL: https://bitcoincore.org/en/2016/01/26/segwit-benefits/ (visited on 05/02/2017).

[27] Segregated witness: the next steps. URL: https://bitcoincore.org/en/2016/06/24/segwit-next-steps/ (visited on 05/08/2017).

[28] Spring Boot. URL: https://projects.spring.io/spring-boot/.[29] Spring Framework. URL: https://projects.spring.io/spring-framework/.[30] Peter Todd. OP_CHECKLOCKTIMEVERIFY. Oct. 1, 2014. URL: https://github.

com/bitcoin/bips/blob/master/bip-0065.mediawiki (visited on 05/02/2017).[31] Raphael Voellmy. CoinBlesk, a Mobile NFC Bitcoin Payment System. 2015.[32] Pieter Wuille et al. Version bits with timeout and delay. Oct. 4, 2015. URL: https:

//github.com/bitcoin/bips/blob/master/bip-0009.mediawiki (visited on04/26/2017).

Page 53: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Abbreviations

API Application Programming InterfaceBIP Bitcoin Improvement ProposalBTC BitcoinDTO Data Transfer ObjectECDSA Elliptic Curve Digital Signature AlgorithmHTLC Hashed Timelock ContractJAR Java ArchiveJSON JavaScript Object NotationMB MegabyteNFC Near Field CommunicationP2PKH Pay to Public Key HashREST Representational State TransferRPC Remote Procedure CallSegWit Segregated WitnessUTXO Unspent Transaction Output

43

Page 54: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 55: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

List of Figures

2.1 Transaction fees and full blocks over time . . . . . . . . . . . . . . . . . . 4

2.2 Miner support for SegWit and Bitcoin Unlimited . . . . . . . . . . . . . . 6

2.3 Comparison of a standard transaction and a SegWit transaction . . . . . 8

2.4 Micropayment channel setup using refund transaction . . . . . . . . . . 9

2.5 Updates to an open micropayment channel . . . . . . . . . . . . . . . . . 10

2.6 Routing payments with HTLC contracts . . . . . . . . . . . . . . . . . . . 12

3.1 Architecture Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.1 A simple token based authentication model . . . . . . . . . . . . . . . . . 27

4.2 Server verification process for the /payment endpoint . . . . . . . . . . . 31

4.3 Offline payment with the /payment endpoint . . . . . . . . . . . . . . . 33

5.1 Transaction fee for different payment profiles. . . . . . . . . . . . . . . . 36

45

Page 56: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 57: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

List of Tables

5.1 Evaluation profiles for transaction fees . . . . . . . . . . . . . . . . . . . . 36

5.2 Comparison matrix between Coinblesk 3.0 and Coinblesk 4.0 . . . . . . . 37

47

Page 58: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere
Page 59: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Appendix A

Installation Guidelines

Installing Dependencies

Java 8 SDK

# *NIXsudo apt-get install openjdk-8-jdk

# OS X and Windows:# http://www.oracle.com/technetwork/java/javase/downloads/index.html

Coinblesk Shared Resources

git checkout [email protected]:coinblesk/coinblesk-shared-resources.gitcd coinblesk-shared-resources./gradlew install

Local Development

./gradlew run

The service is available at http://localhost:8080. The database is inspectable dur-ing development at http://localhost:8080/h2-console (make sure to use the fol-lowing database connection settings: jdbc:h2:mem:testdb

49

Page 60: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

50 APPENDIX A. INSTALLATION GUIDELINES

Building

./gradlew assemble

Ready-to-run jar file is at build/libs/coinblesk-server-2.1.SNAPSHOT.jar

Deployment

Run directly (jar is executable)

./coinblesk-server-2.1.SNAPSHOT.jar

or as jar with java

java -jar coinblesk-server-2.1.SNAPSHOT.jar

In production use the according profile and set some additional sensitive configurationvia environment variables:

SPRING_PROFILES_ACTIVE=prod \BITCOIN_POTPRIVKEY=9732406335342145465465465{...}BITCOIN_MICROPAYMENTPOTPRIVKEY=75570397743156077{...} \SECURITY_JWT_SECRET=supersecret \EMAIL_PASSWORD=hunter2 \SPRING_DATASOURCE_URL=jdbc:postgresql://localhost/db?user=cb&password=pwjava -jar coinblesk-server-2.1.SNAPSHOT.jar

Configuration

The following settings can be configured with environment variables or by changingapplication.properties:

server.port Port on which applicationshould run

8888

spring.datasource.url Database JDBC path. Forin memory database use"jdbc:h2:mem:testdb". h2 andpostgres drivers are on theclasspath.

jdbc:h2:mem:testdb

logging.level.root Sets the root logging level(WARN, ERROR, DEBUG,OFF...)

INFO

coinblesk.url The endpoint at which coin-blesk api is available

https://coinblesk.ch/

Page 61: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

51

coinblesk.config.dir The folder at which to storeSPV chain and wallet files

/var/coinblesk

coinblesk.defaultapiversion The default API version to as-sume should the client notspecify the version in theheader.

/var/coinblesk

coinblesk.minimumlocktimeseconds Minimum lock time in secondsfor newly created addressees

coinblesk.maximumlocktimedays Maximum lock time in days fornewly created addresses

coinblesk.maximumchannelamountusd Maximum amount in USD in achannel

security.jwt.secret The secret to use to sign JWTs.Should be long and compli-cated and always set via envi-ronment variable

kI34jxqkrPxv8qYxaQpx98...

security.jwt.validityinseconds Validity of JWT in seconds un-til expiration

604800

security.jwt.adminvalidityinseconds ... same for admin users 3600bitcoin.net Which bitcoinnet to use:

"mainnet", "testnet", "unittest"testnet

bitcoin.firstseednode Which server to try to connectfirst. In testnet mode: This isthe only server we connect to.

bitcoin4-fullnode.csg.uzh.ch

bitcoin.minconf Number blocks for confirma-tions needed for a transaction

1

bitcoin.potprivkey Privatekey in number formatfor the pot of the server. Keepthis secret and only set by envi-ronment variable. A new onecan be generated with ‘newECKey().getPrivKey()‘

97324063353421115803931...

bitcoin.micropaymentpotprivkey Privatekey in number formatfor the micro payment pot ofthe server. Keep this secret andonly set by environment vari-able.

19283019283019238012983...

bitcoin.potcreationtime Creation time of the wallet potin epoch seconds. Used forcheckpointing optimization atinitial chain download.

1486638252

email.enabled True / False. If the servershould send out email.

True

email.host ‘mail.smtp.host‘ SMTP host[see JavaMail API]

mail.office365.com

email.protocol ‘mail.transport.protocol‘ [seeJavaMail API]

smtp

email.port ‘mail.smtp.port‘ [see JavaMailAPI]

587

email.auth ‘mail.smtp.auth‘ Username/-Password needed. [seeJavaMail API]

true

email.starttls ‘mail.smtp.starttls.enable‘ UseSTARTTLS [see JavaMail API]

true

Page 62: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

52 APPENDIX A. INSTALLATION GUIDELINES

email.debug ‘mail.debug‘ More email de-bug output. [see JavaMail API]

false

email.trust ‘mail.smtp.ssl.trust‘ Trustself signed mail servers.‘mail.smtp.ssl.trust‘ [see Java-Mail API]

false

email.username Username for smtp server ifauth enabled

bob

email.password Password for smtp server ifauth enabled

supersecurepassword!

email.admin Admin email address forwarning related emails

[email protected]

email.sendfrom Sender email for outgoingemails (account activation,password reset)

[email protected]

Page 63: Transaction Fee Reduction in Coinblesk - UZH · 2017-05-16 · liche Bitcoin Transaktion mittlerweile über 1 US Dollar. Dies macht Bitcoin zur einer ungeeigneten Währung, insbesondere

Appendix B

Contents of the CD

• The LATEX source of this thesis

• Source code of the block chain parser to collect transaction fee data

• Script to crawl exchange rates from public API

• Script used for the evaluation simulation

• CSV data files for the plots

• Source code of the Coinblesk server application

• Source code of the Coinblesk android client

53