• Non ci sono risultati.

Design and implementation of a Decentralized Ticketing Application based on Smart Contracts enabled Blockchain

N/A
N/A
Protected

Academic year: 2021

Condividi "Design and implementation of a Decentralized Ticketing Application based on Smart Contracts enabled Blockchain"

Copied!
61
0
0

Testo completo

(1)

Design and implementation of a

decentralized Ticketing Application based

on Smart Contracts enabled Blockchain

Author:

Giulia Di Bella

Supervisors: Prof. Gianluca Dini Prof. Mario G.C.A. Cimino Ing. Stefano di Sandro

A thesis submitted in fulfillment of the requirements for the degree of MSc in Computer Engineering

(2)

ii

“The technical revolution reshaping our society is based not in hierarchy but in decentraliza-tion, not in rigidity, but in fluidity.”

(3)

Università di Pisa

Abstract

Scuola di Ingegneria

Dipartimento di Ingegneria dell’Informazione

MSc in Computer Engineering

Design and implementation of a decentralized Ticketing Application based on Smart Contracts enabled Blockchain

by Giulia Di Bella

This thesis is the result of the work conducted during a six months internship at A-tono Technologies srl. This study has two major purposes: (1) to investigate the science behind blockchain, the technology and its main applications from Bitcoin and cryptocurrency to Ethereum and Smart Contracts, exploring the current state of the art, (2) to develop a Proof Of Concept of a decentralized Ticketing Application running smart contracts on the Ethereum blockchain. Blockchain technology has been introduced in order to guarantee integrity and to prevent touting and fraud in the ticket market, giving transparency to the whole process without needing Third Trusted Parties or any user personal information disclosure. Finally on the basis of the results of this research, an empirical evaluation of the decentralized application developed and of the Ethereum platform was provided.

(4)
(5)

anche l’ingegner Stefano di Sandro, che mi ha supportato ed ascoltato pazientemente durante lo svolgimento di questo progetto.

Un ringraziamento di cuore va a tutti gli amici di A-tono: Marinella, Enzo, An-tonio, Tommaso, Alessandro, Francesco, Mirko, Daniele ed Emanuele, che in questi sei mesi mi hanno fatto sentire a casa e hanno reso piacevole ogni singolo giorno di tirocinio.

Grazie ad Erica, per tutte le volte che mi ha dato asilo, per le ansie condivise, per tutte le strane coincidenze che ci accomunano, ma soprattutto perchè mi ha in-segnato che un ingegnere non "funziona" solamente, ma deve possedere anche del senso estetico.

Grazie a Peter e ad Erica per la più grande soddisfazione universataria data da progetti finiti all’alba ma con "notevole tigna".

Grazie a Maria Grazia per il supporto a distanza in ogni occasione e perchè, se non fosse stato per lei, starei ancora cercando di capire come si scrivono e-mail de-centi.

Un grazie a Micol che è una delle poche certezze della mia vita, e perchè penso di non avere ricordi, da ventun’anni a questa parte, che non siano stati condivisi con lei.

Un rigraziamento ai compagni di Computer Engineering, perchè senza i vari "o’ ripassone" non sarei mai andata da nessuna parte.

Grazie a mia cugina Alessia, perchè c’è ed è sempre pronta a venire in soccorso durante momenti di crisi.

Grazie ad Elena perchè se sono riuscita ad arrivare in fondo, anche quando cre-devo di non farcela, è anche un po’ merito suo.

Grazie anche a tutti gli amici e le amiche che non ho citato personalmente, ma che standomi vicino e dedicandomi il loro tempo, sono stati preziosi per affrontare questi anni.

Infine ringrazio tutta la mia famiglia che mi ha sempre sostenuto sotto ogni punto di vista, e soprattutto grazie a mia mamma che è riuscita a sopportarmi anche quando vagavo per casa in preda ai momenti isterici e disperati, e a mio papà per essere comunque sempre, a volte fin troppo, fiero di me.

(6)
(7)

Abstract iii

1 Introduction 1

1.1 Why Blockchain? . . . 1

1.2 Report Organization . . . 2

2 Bitcoin and Cryptocurrency 3 2.1 Introduction to Bitcoin . . . 3

2.1.1 Cryptographic Fundamentals . . . 3

2.2 Bitcoin decentralization . . . 5

2.2.1 Distributed emergent consensus . . . 5

2.2.2 Distributed Consensus with Blockchain . . . 6

2.2.3 Incentives for Miners . . . 8

2.2.4 Proof-Of-Work . . . 8 2.3 Mechanics of Bitcoins . . . 9 2.3.1 Transactions . . . 9 2.3.2 Scripts . . . 11 2.3.3 Blocks . . . 11 2.3.4 Network . . . 12

2.4 Limitations and improvements . . . 13

3 The Ethereum Platform 15 3.1 Introduction to Ethereum . . . 15 3.1.1 Ethereum History. . . 15 3.2 Implementations . . . 16 3.3 Mechanics of Ethereum. . . 16 3.3.1 Accounts . . . 16 3.3.2 Ether . . . 17 3.3.3 Gas . . . 17 3.3.4 Smart Contract . . . 18

3.3.5 Transactions and Messages . . . 18

3.3.6 Mining . . . 18

3.4 Solidity Language . . . 19

3.5 Security and Controversies . . . 21

3.6 Decentralized Applications . . . 21

3.7 External projects linked to Ethereum . . . 22

4 Decentralized Ticketing Application 23 4.1 Initial Description . . . 23

4.2 Requirements . . . 23

4.2.1 Functional Requirements . . . 23

4.2.2 Non Functional Requirements . . . 24

(8)

viii

4.4 Design Phase. . . 26

4.4.1 Use Case Diagram . . . 26

4.4.2 Sequence Diagrams. . . 26

4.5 Development Phase. . . 28

4.5.1 Smart Contracts . . . 28

4.5.2 Web Application GUI . . . 33

4.6 Testing Phase . . . 33 4.6.1 Environment Settings . . . 34 4.6.2 Testing stages . . . 34 4.7 Evaluation Phase . . . 36 4.7.1 Efficiency . . . 36 4.7.2 Security . . . 37 4.7.3 Privacy . . . 37 4.7.4 Costs . . . 37 5 Conclusions 39 5.1 Problems Encountered and possible solutions. . . 39

5.2 Final considerations and future Works . . . 40

(9)

2.1 Blockchain Data Structure . . . 4

2.2 Merkle Tree Data Structure. . . 4

2.3 Double Spending Attack . . . 7

2.4 Bitcoin Difficulty chart . . . 9

3.1 Ethereum Difficulty Chart . . . 20

4.1 Use Case Diagram. . . 27

4.2 Sequence Diagram Buy Ticket Event . . . 28

4.3 Sequence Diagram Buy Train Event. . . 29

4.4 Web Application Event Example . . . 34

4.5 Web Application Train Example. . . 35

4.6 Example of contract creation with Solidity IDE and Metamask on Rop-sten . . . 36

(10)
(11)

2.1 The structure of a transaction . . . 10

2.2 The structure of a transaction output . . . 10

2.3 The structure of a transaction input . . . 10

2.4 The structure of a block. . . 12

2.5 The structure of the block header . . . 12

3.1 Ethereum Clients . . . 16

3.2 Ethers denominations . . . 17

3.3 Ethereum Transaction Fields . . . 18

4.1 Event Contract costs . . . 37

(12)
(13)

DAG Direct Acyclic Graph

DAO Decentralized Autonomous Organization

EVM Ethereum Virtual Machine

EOA External Owned Account

IPFS InterPlanetary File System

KYC Know Your Costumer

NIST National Institute of Standards and Technology

OOG Out Of Gas

POS Proof Of Stake

POW Proof Of Work

(14)
(15)
(16)
(17)

Introduction

1.1

Why Blockchain?

Blockchain can be defined as a distributed database model used to validate financial transactions and comparable to a tamper evident decentralized ledger.

Blockchain has affirmed for the first time as technological base underlying Bit-coin, the virtual cryptocurrency born in 2008. Since that Blockchain has evolved in several ways, and in 2013 the Ethereum project was defined for the first time. Ethereum is basically a platform designed to run smart contracts deployed on a blockchain over a decentralized network of peers. A smart contract is nothing else than an application that runs exactly as programmed without downtimes, censor-ship, fraud or third party interference, executed by every node in the network. Ethereum is also an open source project with a strong community behind it, that offers a good support for smart contracts via Solidity, the de facto standard lan-guage for programming smart contracts. Currently it represents the state of the art of smart contract platform as well as the most advanced blockchain technology, that allow devoloping working decentralized applications.

But which benefits blockchain can be add to ticketing applications? This is the goal of the internship experience inside A-tono technology srl[1] and the question to which this thesis aspires to give an answer. First of all it’s important to consider that one of the major problems in ticketing applications is ticket forgery and fraud, so the aim of this project is to understand if it’s possible adopting blockchain technology to afford this issues. But before even starting to think of using blockchain as backbone of an application, there must be the awareness that blockchain is really a feasible and the better solution for the objective target. In fact compared with distributed databases, only in certain situations blockchain represents the better solution. In particular it is when there is trustiness and robustness issues, since in terms of per-formance and confidentiality distributed databases behave better, because of the na-ture itself of blockchain. As already underlined ticketing market is a lack of trust scenario and for this reason suitable for blockchain, even if there are several limita-tions in transaclimita-tions performance, as shown later in this paper. Among all possible scenario tickets for events represent the best one applying blockchain technology to, because it has no such hard real-time constraints, like transport or parking tickets. However this project affords two cases, managed by two different kinds of smart contracts: one for event tickets and one for train tickets.

For the reasons expressed above and after analyzing deeply the wide field of blockchain technologies the choice on which platform to adopt for this application development easily fell on the Ethereum platform.

In parallel with project implementation a research has been done also in order to figure out the state of the art of the blockchain utilization in ticketing applications: several projects was born and have been well-documented during these months,

(18)

2 Chapter 1. Introduction proving this is a current hot topic. The most interesting among these projects are the LAVA project [23], Blocktrick [19] and the Aventus protocol [2]. All of them, al-though they are in an embryonic phase yet, try to prevent ticket fraud during events organization.

1.2

Report Organization

This report is organized in the following way: the first two chapters, after introduc-tion, provides a general overview of the background concepts regarding blockchain and decentralized applications, respectively starting with Bitcoin mechanism in the second chapter, and then with The Ethereum platform in the third one. The fourth chapter describes the application developed for this project, while the last one presents final consideration and evaluation of this work, trying also to give some hints for fu-ture works.

(19)

Bitcoin and Cryptocurrency

2.1

Introduction to Bitcoin

Bitcoin is a decentralized digital currency, invented in 2008 with the publication of a paper titled Bitcoin: a Peer-to-Peer Electronic Cash System, written under the alias of Sathoshi Nakamoto [28] and deployed on January 3, 2009. Units of currency called bitcoins are used to perform transactions from one owner to the next, where owners are identified by a public key, from which is derived an address, not inherently tied to their real-world identity. Users own the correspondent private key that allow them to prove ownership of transactions in bitcoin network, unlocking coins in order to spend them and to transfer them to a new recipient. It’s necessary for each user to be aware and to check the validity of all these transactions, in order to solve the issue of double spend, when an user attempts to transfer the same coins more than once. To do so transactions are broadcast into the network and to determine which one of them came first, they are grouped into blocks, which serve to timestamp the transactions they contain and attest their validity. Blocks are themselves formed into a chain, which each block referencing the previous one. This process produces a blockchain, which is publicly available to every user in the system. Since Bitcoin is a distributed, P2P system and as such there is no central server or point of control, Bitcoins are created through a process called mining, which involved competing to find a solution, called Proof-Of-Work, to a mathematical problem while processing bitcoin transactions and forming blocks. Any bitcoin node may work as a miner, us-ing his computer’s process power to verify and record transactions, even if winnus-ing the round requires actually an high computational cost, unaffordable by most nodes. However every 10 minutes on average someone is able to find a new accepted block, i.e. a block that extends the blockchain and to broadcast it as the same P2P man-ner as transactions. Furthermore the winning node is rewarded with new bitcoins created from scratch.

In this chapter the toughest concepts will be explained more in detail and also other aspects, the most meaningful for the thesis purposes, will be analyzed, but for a comprehensive overview please see bibliography [3].

2.1.1 Cryptographic Fundamentals

This paragraph is a brief introduction to the cryptographic fundamentals used in Bitcoin, in order to provide the basics before going into detail of its architecture:

1. Cryptographic Hash functions: Hash functions are plenty used in Bitcoin. Ba-sically an Hash function takes an input of any length and generates a fixed-size output. This output in Bitcoin has length of 256 bit, as specified by the algo-rithm used: Secure Hash Algoalgo-rithm with digest of 256 bits called SHA-256.[36]

(20)

4 Chapter 2. Bitcoin and Cryptocurrency 2. Hash Pointers and Data Structure: an Hash pointer is basically a pointer to retrieve data stored and to verify that those data haven’t been changed. In particular there are two important hash pointers-based data structure used in Bitcoin. The first is obviously the Blockchain: this data structure, showed in figure 2.1, is simply a sequence of data blocks, in which each block contains the hash pointer of the previous block, until the first block, called Genesis Block. This data structure is useful to build a Tamper evident log: it’s possible in fact to add new block at the end, but it’s impossible to change data within the blockchain without detecting it, because if an adversary had changed some data inside a block, even if the head of chain is the only thing stored, the tam-per tam-performed would be propagated along the entire chain until the head hash, that can’t be modified. The second is Merkle Tree: as shown in figure 2.2it’s a

FIGURE2.1: Blockchain data structure

binary balanced tree of hash pointers. This data structure has several advan-tages: it’s possible proving membership of a data in a merkle tree with loga-rithmic complexity and storing only the root, i.e. 256 bits.

FIGURE2.2: Merkle Tree data structure

3. Digital Signatures: the algorithm for Digital Signatures allowed by Bitcoin is Elliptic Curve Digital Signature Algorithm(ECDSA). [7] In particular Bit-coin uses a specific elliptic curve and set of mathematical constants, defined in

(21)

key pair. Therefore a single person or a company or any external agents de-fined as the owner of a private/public key pair, is identified by his Bitcoin address, computed through hashing the public key, with the use of two hash algorithms: Secure Hash Algorithm and RACE Integrity Primitives Evalua-tion Message Digest(RIPEMD), producing a 160-bit number as shown in the following formula: Address = RIP EM P D160(SHA256(Pk)).

2.2

Bitcoin decentralization

The most relevant aspect of Bitcoin technology is definitely how decentralization is achieved. This paragraph explores just this concept, focusing on the consensus reaching methodologies.

2.2.1 Distributed emergent consensus

Distributed consensus is a key challenge in Bitcoin. This concept concerns a series of protocols studied in order to achieve reliability in distributed systems.

Definition 2.2.1. Distributed consensus: given n nodes, each of them has an input value, the protocol ends in finite time when all the correct nodes, no faulty or ma-licious, decide for the same value and this value must be proposed by at least one correct node.

In order to better understand how this practically works in Bitcoin, assuming that for example Alice wants to pay Bob a certain amount of Bitcoin in order to re-ceive some sort of good. In a simplified model what Alice must do is to build a trans-action, which includes Bob’s address, an hash pointer to a previous transtrans-action, from which Alice had received the coins she want spend, and her digital signature on it, to prove she’s actually the sender of that transaction. Then Alice broadcasts this trans-action to all nodes of the network. The main task of the nodes is therefore to reach consensus on which transactions were broadcast within the network and in which order they happened. So at any given time all nodes store a sequence of blocks of transactions on which they’ve reach consensus, basically the shared blockchain and in addition to it also a set of outstanding transactions, means verified transactions but not yet present in blockchain. This set is slightly different for each node, but this is fine since it includes only transactions, on which consensus in not reached yet. The mechanism to achieve this in Bitcoin is called emergent consensus because it’s not achieved explicitly - there is no election of fixed moment when it occurs - but it’s a consequence of the asynchronous interaction of thousands of independent nodes, by following some rules as explained in the further subsections.

Why is consensus so difficult to achieve in Bitcoin context? Since, as repeatedly stressed, Bitcoin is a P2P system, with no central authority or point of control, not all nodes may be connected or act honestly, rather they may be faulty or even ma-licious, there’s also a certain latency within the network, with no notion of global time and this is an issue especially to order events. In fact there is a lot of literature

(22)

6 Chapter 2. Bitcoin and Cryptocurrency concerns consensus in fault-tolerant distributed systems. Despite many impossibil-ity results have been proved, just think to the Byzantine generals problem or the Fischer-Lynch-Paterson impossibility result, for which under some conditions, what they proved is that consensus is impossible, even with a single faulty process, there are a few well-known protocols, when Paxos is probably one of the most famous, notwithstanding the fact that it has several limitations. For further information on the basic techniques behind these scientific aspects behind blockchain technology, see bibliography [39].

2.2.2 Distributed Consensus with Blockchain

Blockchain is, as said before, a public append-only ledger and nodes have to achieve consensus on the next block that extends the chain and on the order of the transac-tions to insert in that block. There’s also another constraint to take in account: users have no identity, mainly for two reasons, because of the lack of a central authority that distributes IDs and to guarantee a sort of pseudo-anonymity.

Bitcoin consensus algorithm is composed by four independent processes, repre-senting by the following simple rules, on which nodes of the network are agree:

1. Each node verifies that the received transactions are unspent and with a valid signature, storing then only the ones who passed the validation test in a mem-ory pool, i.e. the set of the valid, but unconfirmed transactions.

2. Some nodes, called miners, aggregate transactions into a block, the candidate block to extend the blockchain, and compete between each others to win the round, solving an hard computational hash puzzle and find a solution, called Proof-Of-Work. The winner node broadcasts the block as the same way of trans-actions, while the others miners, as soon as they received the new block, stop the current computation and start mining a new block.

3. Each node verifies the new block and accepts it if it’s correct, i.e. it respects bitcoin standards and all the transactions in it are valid, otherwise they reject it. Accepting a block simply means to insert an hash pointer to that block in the next candidate block.

4. Miners choose to extend the longest correct blockchain, by inserting the hash pointer to the last block found in the next.

On the light of this information it’s possible to achieve what an attacker may or may not do. First of all he can’t steal another user’s coin, if we assume that the algorithm of digital signature is enough robust to not be forced. On the contrary an issue, that is worth to deepen, is the double spending attack. For a better under-standing what this kind of attack consists of, it’s necessary to see first what happens when two miners create a block almost at the same time. Basically the two miners send two different blocks into the network, and due to the latency of the network itself and to the different geographical positions of nodes it may happen that some nodes receive one of the two blocks first, while other nodes receive first the other block: this situation represent a temporary fork of the blockchain, i.e. when miners are working on different branches. One of the two branches will eventually become longer than the other and to resolve the fork miners will mine on the longest chain. The consequence is that the shorter branch will be discarded, the work spent to mine its blocks wasted and the rewards not collected. Although a temporary fork will be always resolved, a malicious node could take advantage of an event like this for

(23)

transaction appears into the blockchain. Bob as soon as he sees Alice’s transaction published inside a block in the blockchain, he thinks Alice pays him for the asset and he delivers it to Alice. But since Alice may not to be an honest node, she may try to cheat Bob, building at the same time a second transaction in which she transfers the same coins, that should be intended to Bob, to another address A’, likely linked to her. If Alice has also enough computational power, she is able to fork the blockchain, finding blocks that extend it starting from a block antecedent of the one, that con-tain her transaction to Bob. Since the rule for miners is to extend the longest branch by default, more computational power Alice has and more blocks she’s able to find, more it’s likely that the valid accepted branch will be the one in which is present the second transaction, in such a way that the first branch will be ignored, even so the block, that become an orphan block, containing the transactions to Bob, who loses coins, that he should has received for the asset already delivered, since the double spending attack has been successful. Luckily there’s a strategy to protect against this kind of attack and it consists of waiting for a certain number of confirmations before consider globally accepted a transaction. This means that once a transaction is included in a block it has one confirmation, as soon as another block is mined on the same blockchain the same transaction has two confirmations, and so on. More confirmations a transaction has, more likely it has to be in the longest valid chain. Since mining a block requires a big computational effort it’s pretty unlikely forking the blockchain too far behind, because this would involve to find so many block in a very short time, in order to create an alternative valid longest branch. In particular the guarantee against the double spending attack is expressed in probabilistic terms, since the probability of this attacks may happen decreases exponentially with the number of confirmations. Heuristically a number of six confirmations, more or less correspondent to one hour, is generally believed a valid trade-off between security and waiting time for considered a transaction globally accepted.

FIGURE2.3: Double Spending Attack

So Bitcoin uses the mechanism of the digital signatures and of the emergent con-sensus to protect against invalid transactions and against coins stealing. The security

(24)

8 Chapter 2. Bitcoin and Cryptocurrency against the double spending attack is always base on the emergent consensus mech-anism, but it’s only a probabilistic guarantee.

2.2.3 Incentives for Miners

All the previous considerations apply only if the majority of the nodes in the network act honestly. In order to make this happens Bitcoin provides two kind of incentives to reward miners for their computational work:

1. Block Reward: each block contains a special transaction called coinbase transac-tion, that represents a reward for the miner. When Bitcoin was born in 2009 this reward was 50BTC, but it halved twice already, once in 2012 and once in 2016, so currently in 2017 it is equal to 12.5 BTC, but it’s designed to halve again every four years until 2140, when all of 21 millions coins, as limited by the protocol, will be emitted. After that block reward will be null.

2. Transactions Fees: the difference between the sum of the inputs and the sum of the outputs for each transaction goes to the miner as reward. It’s straightfor-ward that transactions with highest fees are more probably chosen by miners and so more quickly included in a block. Transaction fees can be considered as a disincentive for spamming. They are collected by miners in the coinbase transaction and their value depends of transaction size.

2.2.4 Proof-Of-Work

The mechanism to choose at every round which is the winning miner and conse-quently the next block in the chain is so far to be a trivial problem. First of all this must be done on the base of a resource that can’t be easily monopolized in order to avoid the so called Sybil attack[13], i.e. when an adversary is able to multiply his power inside the network, and therefore his chances to be the winning miner, by the creation of nodes or copy of nodes that act like real distinct participants. The force of Bitcoin’s POW to find a solution to this kind of attack in a P2P network is based on using node’s computational power as resource. In fact inside the network miners compete between other miners in order to find a solution to an heavy com-putationally hard hash puzzle. It consists on finding a random number, a 32 bit nonce, such that the SHA256 hash algorithm applied twice to the concatenation of the block header and the nonce gives as output a value lower than a specific out-put target. Block structure will be explained later in details, for now it’s sufficient to know that block’s header contains the following information: hash of the previous block and a field from which it’s possible to retrieve all the transactions inside of it. Therefore each miner has to compute this hash multiple times, with different nonce, until he finds a 256 bit output that satisfy the target. If the hash function is secure this task requires a certain number of steps depends on the target difficulty.

In particular a POW solution has three important properties:

1. It’s difficult to compute: at Jan 2017 at least the first 68 bits of the output must be zero and the difficulty implies approximately 2070.5steps to find a block. 2. It has an adaptive difficulty: every 2016 blocks, i.e. almost every two weeks,

each nodes recomputes independently blocks difficulty in order that interval time between two consequent blocks discovered remains almost the same, i.e. 10 minutes on average, with the following formula:

(25)

FIGURE2.4: Bitcoin Difficulty chart

2.3

Mechanics of Bitcoins

In order to complete Bitcoin overview it worth to explore how the protocol works in practice and what are its main components. This paragraph addresses Bitcoin transactions, scripts, blocks and network architecture.

2.3.1 Transactions

Bitcoin’s blockchain is a transaction-based append-only ledger. A transaction is a data structure that encodes a transfer value from a source of funds, called input to a destination, called output. The lifecycle of a transactions is composed by five phase:

1. Transaction creation.

2. Transaction signature by involved parties. 3. Flooding phase into the blockchain network.

4. Transaction verification by every node that receives it and that rebroadcast it if it’s correct.

5. A Miner node inserts it into a block recorded into the blockchain.

In table 2.1 Bitcoin transactions fields are shown. The most important fields are transaction output, that represents the amount of bitcoins locked by the owner and that creates an UTXO (Unspent Transaction Output), contained by miners in the UTXO set, and transaction input. Their respective structure are shown in tables2.2

(26)

10 Chapter 2. Bitcoin and Cryptocurrency

TABLE2.1: The structure of a transaction

Size Field Description

4 bytes Version Specifies which rules this transaction follows 1-9 bytes Input Counter Number of input included

Variable Inputs One or more transactions inputs 1-9 bytes Output Counter Number of output included Variable Outputs One or more transaction outputs 4 bytes Locktime Unix timestamp or block number

TABLE2.2: The structure of a transaction output Size Field Description

8 bytes Amount Bitcoin value in satoshis (10−8bitcoin) 1-9 bytes Locking-script Size Locking-script length in bytes

Variable Locking-script Script defining the conditions to spend the output

TABLE2.3: The structure of a transaction input

Size Field Description

32 bytes Transaction Hash Pointer to the transaction containing the UTXO 4 bytes Output Index Index of the UXTO inside transaction

1-9 bytes Unlocking-script Size Unlocking-script length in bytes

(27)

1. Locking Script or scriptPubKey: it specifies the conditions to spend the output. 2. Unlocking Script or scriptSig : it solves the condition specified by the Locking

Script.

If the concatenated execution of the Unlocking Script and the Locking Script, returns True, and nothing else, in the stack then the owner can claim and spend the output. Currently only five types of scripts are accepted by Bitcoin nodes:

1. Pay to Public Key Hash(P2PKH): This is straightforward the most common and used script.

2. Pay to Public Key: It was replaced by the previous script in order to make Bit-coin addresses shorter, but it is still used by some old miner node in the Bit- coin-base transaction.

3. Multisignature or M-out-N Scheme: M of a list of N possible signatures are re-quired in order to unlock the output.

4. OPRETURN opcode: In the locking script this code represent a so-called Proof-Of-Burn, i.e. a script that can’t be redeemed, destroying de facto that coins. This script has two main uses, the first is writing arbitrary data into the blockchain and the second is forcing user to destroy coins in order to use blockchain for other purposes than cryptocurrency, without bloating UXTO dataset how it happens if someone sends coins to an existent Bitcoin address.

5. Pay to Script Hash(P2SH): This script was introduced later in the list of the stan-dard accepted scripts, by a soft fork, for efficiency reasons. Firstly to move the complexity from the sender’s side to the recipient’s side, since the transactions fees depend on transaction size, so in this way a complex script is recipient’s burden. Secondly the Locking script occupies memory in the UTXO pools for miners and in this way the output scripts are shorter.

2.3.3 Blocks

A bitcoin block contains more transactions for two main reasons: firstly for efficiency reason to reduce the overhead for mining using it for more transactions and secondly to make blockchain verification faster. In table2.4it’s shown Bitcoin block architec-ture and in table2.5the detailed structure of the block header. In essence each block contains the hash of the header of its parent block and the hash pointer of the root of the merkle tree computed on the base on the transactions contained in the block itself. This structure allows proving that a transaction is present in a block with a complexity O(logn), that is useful especially for SPV nodes that don’t download the entire blockchain but only block headers.

(28)

12 Chapter 2. Bitcoin and Cryptocurrency

TABLE2.4: The structure of a block

Size Field Description

4 bytes Block size Size of the block in bytes 80 bytes Block Header Several fields

1-9 bytes Transaction counter Number of transactions

Variable Transactions Transactions recorded in the block

TABLE2.5: The structure of the block header

Size Field Description

4 bytes Version Version number to track protocol upgrades 32 bytes Previous Block Hash Reference to the hash of the previous block 32 bytes Merkle Root Hash of the root of the merkle tree of transactions 4 bytes Timestamp Block creation time

4 bytes Difficulty PoW algorithm difficulty target for this block 4 bytes Nonce Counter for PoW algorithm

2.3.4 Network

Bitcoin works on a P2P network using an ad hoc protocol over TCP on 8333 port, in which all nodes are equal and called peers. A new node can join and leave the net-work anytime. Bitcoin peers forget no-responding nodes after a period of inactivity. For joining the network a new node can contact a Bitcoin node, finding him through one of the five DNS seed contained in the Bitcoin client core or by its IP address if known, after that it sends a special message called getaddress to receive from the bit-coin peer a list of bitbit-coin nodes. This process is repeated until the new node reaches a certain number of P2P connections.

Transactions propagation within the network happens by a flooding phase: each time a node receives a new transaction he decides to rebroadcast it if its script exe-cution returns true, if its script is standard (White List),if it was no heard before by check if its hash is already present in the node’s memory pool and if it doesn’t seem a double spend. Valid transactions are inserted in the memory pool and rebroad-cast. Pay attention that two nodes can have different memory pools, but that’s fine because at that stage they haven’t reached consensus yet. Race conditions can be happened, but they will be solved by miners building the next block of the chain.

For blocks propagation the process is the same of transactions: a node relays a block if it meets the target, if it contains only valid transactions, verifying by script execution, and if it extends the longest correct chain.

Since Bitcoin protocol has been designed with the main aim to be simple and suitable for a decentralized architecture it has not been optimized for improving network performance, whose latency can be also of 30/40 seconds for big blocks.

Despite of the fact all nodes in Bitcoins are equal as peers, actually they can per-form different functions. In particular it’s pretty much important to make a dis-tinction between Full Nodes and Simple Payment Verification Nodes: the formers are always connected, they handle the storage of the entire blockchain (that amounts at 100GB in Jan 2017), the storage in the RAM of whole UTXO set in order to quickly detect double spend (1.6GB at January 2017) and for starting are necessary several

(29)

2.4

Limitations and improvements

Finally after this in-depth view of the architecture of Bitcoin, it’s possible to identify five main limitations:

1. Throughput limitations: considered that average block size is about 1MB and av-erage the transaction size is about 250 byte, a block can contain approximately 4000 transactions. In this case the limit is represented by the 10 minutes of interval time on average between consecutive blocks, because this implies a throughput of only 7 transactions per second. Compared with the 2000 trans-actions per seconds on average and peaks of 56,000 transtrans-actions per second handled by Visa [20] and the 193 transactions per second of Paypal [30], it’s straightforward that scalability is an open problem for Bitcoin currently. 2. Cryptographic limitations: another significant problem is represented by the fact

that cryptographic algorithms are fixed by standards. In particular only a cou-ple of hash algorithms and one algorithm for digital signatures, ECDSA Sec P256, are allowed. Therefore someone might reasonably think that at a cer-tain point in the Bitcoin lifetime these algorithms might be broken and that the Bitcoin scripting language should be extended in order to support new crypto-graphic algorithms to remain secure, except that changes in standards are very difficult to apply, as explained in the following point.

3. Change implementation difficulties: in Bitcoin there are two main ways to imple-ment changes in the protocol. The first is to realized an Hard-Fork: if a new version of Bitcoin client is released, it will cause several problems, because it will impossible to determine if all nodes have downloaded the new version.In fact if eventually old nodes do not accept blocks containing transactions with the new features, such as a new digital signature scheme, it will cause an in-evitably split of the blockchain, unacceptable for most of the users for obvi-ous reasons. The other way is represent by a Soft-fork in order to avoid an Hard-fork, allowing only new features that restrict the number of valid blocks and/or transactions; in this case the risk is only that an old miner might cre-ate a block that will be rejected by the network, giving nodes an incentive for updating software in order to not waste any further money and time. The in-troduction of the P2SH script is an example of a successful soft-fork. Other changes in depth require an Hard-fork, such as solving bugs, new operations, change mining rate and block or transaction size. In all of these case is better to start from scratch with an altcoin, rather that perform an hard-fork.

4. Blockchain’s size effort: Bitcoin blockchain size reaches 100,000 MB in Jan 2017 and this not only represents an important issue for scalability, but also a dis-couraging factor for running a full node.

5. Anonymity and Privacy: in Computer Science it’s common to distinguish be-tween pseudoanonymity, referred to a system in which users don’t use their

(30)

14 Chapter 2. Bitcoin and Cryptocurrency real identity, and anonymity, that is achieved only if with the first condition is guaranteed also the unlinkability, i.e. the impossibility to link different ac-tions of the same user inside the system. Since blockchain is completely public Bitcoin achieves only pseudoanonymity, and this is not enough to guarantee privacy, as demonstrated by several studies like transaction graph analysis, through which is likely possible by observing transactions flow linking bitcoin public keys to real people [18]. Although some attempts of de-anonymization are already done, like [6] and [35], this is a still open issue since too much anonymity could be encourage laundering and other illegal actions.

(31)

The Ethereum Platform

3.1

Introduction to Ethereum

Ethereum is a blockchain-based computing platform, that allows to develop Smart Contracts, expressed in a complete-Turing script language, executed by a decentral-ized virtual machine, called Ethereum Virtual Machine. Ethereum can be described through its four major interdependent components:

1. Cryptographic tokens: it has its own internal cryptocurrency, called Ether, ex-changeable cryptocurrency that allows nodes to share computing resources for the execution of programmable smart contracts on the blockchain.

2. P2P network: like Bitcoin also Ethereum is a P2P network and individual users connect their computers together forming a network without a central server or point of control.

3. Turing-complete Virtual machine: a virtual machine is a computer that exists as software. It can be run independently of the underlying hardware. Turing complete means that in principle a contract could be programmed to solve any computation problem.

4. Consensus formation algorithm: Ethereum consensus algorithm allows users of the blockchain to reach consensus about the current state (all of the data) of the blockchain every 12 seconds.

In the following sections a complete overview of the Ethereum blockchain is given and this is particularly relevant since the project of this thesis is largely fo-cused on exploiting this platform.

3.1.1 Ethereum History

Ethereum was initially described in a white paper by Vitalik Buterin, in 2013 [9] with the goal of building decentralized applications, but it was formally defined later in Gavin Wood’s Yellow Paper [41]. The first version of Ethereum, called the Frontier release and launched on 30th July 2015, was essentially a beta release that allowed developers to learn building Ethereum decentralized applications. On March 14th 2016, was released Homestead, the second version of the Ethereum platform and the first production release of Ethereum. This section will refer to that second version, by following the official Homestead documentation [11]. Furthermore since it was born, Ethereum network has accomplished other two hard-forks: the DAO-Fork, in June 2016 and the Spurious Dragon hard fork towards the end of November 2016. The former represents the first time a blockchain was forked to reverse a transaction

(32)

16 Chapter 3. The Ethereum Platform

TABLE3.1: Ethereum Clients

Client Description

Ethereum Go Go, most used for Web Dapp.

Parity Rust, fastest and lightest Ethereum client cpp-ethereum C++

pyethapp Python, used mostly for educational purposes ethereumjs-lib Javascript

Ethereum(J) Java ruby-ethereum Ruby

ethereumH Haskell, no Homestead release yet

in order to make reparations to investors in a failed enterprise because of an hack-ing attack, but this will be explain better further in the dedicated section, the latter instead was an hard fork response to the DoS attacks on the Ethereum network in September and October 2016 [22].

3.2

Implementations

Ethereum has been multiple client implementations across a range of different op-erating systems. Table 3.1 gives a complete overview of all the actual available Ethereum clients. At time of writing the leading implementations are go-ethereum, commonly referred to as geth implemented in Go, and Parity, written in Rust lan-guage and integrated directly into a Web browser. [11]. Currently no Ethereum light client was officially released to bring Blockchain to mobile devices, even if a devel-opment phase has already begun, as shown by Status project [38].

3.3

Mechanics of Ethereum

This section resumes the most important technical aspects of the Ethereum platform. 3.3.1 Accounts

An account is represented by a pair of public and private keys and its address is derived from the public key by taking the last 20 bytes. In Ethereum we have two kinds of accounts:

1. Externally Owned Accounts: identities accounts controlled by a private key. They can send transactions to another account for transferring ethers or for triggering contract code. They use public key cryptography to sign transac-tion so that the EVM can securely validate the identity of a transactransac-tion sender. 2. Contract Accounts: basically program code to insert programmable logic into the blockchain. From a practical point of view a contract are very close to a programming class.

These entities are also called state objects because they have a state: EOAs have bal-ance and contracts have both balbal-ance and contract storage. The state of all accounts is the state of the Ethereum network which is updated with every new block.

(33)

Gwei (shannon 10 Microether (szabo) 1012 Milliether (finney) 1015

Ether 1018

3.3.2 Ether

Ether is the cryptocurrency created to serve as "fuel" on the Ethereum network. It’s used for paying nodes for their computational work to maintain the security within the blockchain and to execute contracts when required within the EVM. It’s possible to get Ethers or by mining, obtaining 5 ETH for each new block discovered, or by buying them from third parties.

Ethereum has a metric system of denominations for units of ether. The smallest denomination is called Wei, which is the one used for contracts and accounts bal-ance. In table3.2there’s a list of the named denominations and their value in Wei. Actually it’s not easy to say what is the real value of one ether in fiat currency due to the instability and fluctuation of ether’s markets. When this project started in fact, on March 2017, one Ether was worth almoste30, but now at time of writing, on July 2017, it is worth approximatelye230 [16], and this value it is intended to fluctuate wildly in the next months.

3.3.3 Gas

Ethereum implements an execution environment on the blockchain called Ethereum Virtual Machine (EVM). Every node participating in the network runs the EVM as part of the block verification protocol. They go through the transactions listed in the block they are verifying and run the code as triggered by the transaction within the EVM. When a contract is executed as a result of being triggered by a message or transaction, every instruction is executed on every node of the network. Each computational activity has a cost expressed in amount of Gas units. For this reason each transaction must specify two extra parameters:

1. Gas Price: the price in Ether that the sender is willing to pay for one unit of gas. It counts also as an incentive for miners.

2. Gas Limit: the maximum amount of gas the sender is willing to expend in this transaction. It’s obviously a predicted upper limit and it protects nodes from the halt problem caused by infinite loop.

Therefore before sending a transaction, the sender must be sure to have enough Ethers, in particular he must have an amount of Ether equal to T otalCost = GasLimit∗ GasP rice. If the total gas exceeds the gas limit, then all changes are reverted, except that the transaction is still valid and the fee can still be collected by the miner. All excess gas not used by the transaction execution is refund to the sender as Ether.

(34)

18 Chapter 3. The Ethereum Platform

TABLE3.3: Ethereum Transaction Fields

Field Description

Recipient address Recipient of the message Digital signature Signature of the sender

VALUE Amount of wei to transfer from the sender to the recipient (optional) STARTGAS Maximum number of computational steps allowed

GASPRICE Fee the sender is willing to pay for gas

The concept of Gas limit is applied also to Blocks, as the maximum amount of Gas that can be used per block, considered as the sum of the gas limit of all the transactions it contains. Blocks can’t be too big for the impact they might have within the network.

3.3.4 Smart Contract

A contract is a collection of code (series of functions) and data (the state), that resides at a specific address on the Ethereum blockchain. In other words it’s an instance of a computer program that runs on the blockchain, executed by all the consensus nodes. Create a contract is equal to posting a transaction and its code is executed by the network of miners who reach consensus on the result and update the blockchain accordingly. A contract can read or modify its internal state, consume and receive messages or trigger another contract’s execution by sending a message. A smart contract can be written using different programming languages:

1. Solidity: Javascript-like 2. Serpent: Phyton-like

3. LLL: LISP-like, but closer to assembly.

4. Mutan: statically typed, C-like language, deprecated.

Nevertheless Solidity seems become the de-facto programming language for smart contract, especially for DApp and it will be analyzed more in detail further in this chapter.

3.3.5 Transactions and Messages

Transactions refer to the signed data package that stores a message to be sent from an externally owned account to another account on the blockchain. Transactions are action triggers, since Ethereum environment is inert by nature. User can send a transaction to another External Account in order to transfer Ethers or to a Contract in order to perform code execution. A complete view of Ethereum transaction field is shown in table3.3

Essentially, a message can be conceived of as function calls, and it’s very close to a transaction, except it is produced by a contract and not by an EOA.

3.3.6 Mining

In Ethereum 1.1, with the Serenity release, the mining process is likely to be replaced by a Proof-Of-Stake model, but for now it’s still based on a Proof-Of-Work algorithm

(35)

takes a long time to generate. However the DAG only depends on block height, so it can be generated in advance. Of course the PoW verification can be performed also with both low CPU and small memory, since the DAG does not need to be generated for that.

Block reward for mining is equal to a static block reward of 5 ETH plus the trans-action fees payed for the gas spent by the miner. The peculiarity of Ethereum is that the block reward is valid also for Uncle Blocks. An Uncle block is an ancestor of the current block, but it’s not part of the longest chain and it’s up to 6 blocks back from the current block. The reward for an uncle block it’s 78 of the static block reward; only two uncles for blocks are allowed.

Both CPU and GPU mining are allowed, even if CPU mining is not profitable anymore at the current difficulty, but suitable only for a testnet. GPU miners are almost two orders of magnitude more efficient and it’s more likely they may find a new block than a CPU miner. Furthermore since Ethash algorithm is memory hard in order to fit the DAG into memory, it needs 1-2GB of RAM on each GPU. At time of writing difficulty is 182, 195T H, this means that by using Hardware with an hash rate of 25M H/S it will take an average of 84.62 days to find one block, under the assumption that difficulty remains constant during that period. In figure 3.1

it’s possible to see a chart of the Ethereum Block Difficulty Growth from Ethereum launch in 2015 until March, 2017.

3.4

Solidity Language

Solidity is the main programming language for smart contracts in Ethereum. It’s a high level language, Object Oriented and Javascript-like, which when compiled gets converted to EVM byte code.

Just for having some idea of what a Solidity smart contract is, the following code, provided by Official Solidity documentation [37], shows a very simple smart con-tract, that basically has a state, consisting in a variable called storedData, and two functions that allow anyone to store and read a single number, accessible by anyone. pragma solidity ^0.4.0; contract SimpleStorage { uint storedData; function set(uint x) { storedData = x; }

function get() constant returns (uint) { return storedData;

} }

(36)

20 Chapter 3. The Ethereum Platform

FIGURE3.1: Ethereum Difficulty chart

Actually writing a safe smart contract is not so simple and to fall in some pitfalls may be not be so difficult, since programming in Solidity requires to have multidis-ciplinary skills, like cryptography, programming languages, game theory, but also adversarial thinking abilities of cybersecurity, in order to anticipate strategic actions of malicious users. However there’s some guidelines to follow in order to avoid dangerous situations:

1. No Private Information: since blockchain is public everything in a smart contract is publicly visible, even local variables and state variables marked as private. 2. Hard to achieve randomness: using random numbers in smart contracts is quite

tricky because miners are able to cheat if pseudo-randomness depends on block header values, malleable by miners.

3. Avoiding Re-Entrancy: re-entrancy may happen when there’s an interaction from one contract with another contract and any transfer of Ether hands over control to that latter contract. This makes it possible for the second contract to call back into the first before this interaction is completed and if the recipient is a contract that calls back into withdraw, it get multiple refunds and basically retrieve all the Ether in the contract. To avoid re-entrancy, it’s fundamental to use Checks-Effects-Interactions pattern: if functions have to perform some checks, they must be done first; if all checks passed, effects to the state variables of the current contract should be made and interaction with other contracts should be the very last step in any function.

4. Sending and Receiving Ethers: sending back the money by simply using a send function is a security risk because it can be prevented by the caller by raising

(37)

3.5

Security and Controversies

One of the most critical aspect of the security model adopted in Ethereum is cer-tainly that DApps running over Ethereum are subject to the attacks described in [24]. These attacks exploit the fact that Ethereum miners are subjected to the so-called verifier’s dilemma, according to which they are not able to determine whether to verify transactions or not. In both cases honest miners are vulnerable of an attack. In fact if a miner behaves honestly, validating all transactions, then an adversary can flood nodes with resource-intensive transactions. Since honest nodes will spend a significant amount of time to verify them, the adversary obtains an advantage in the race for mining the next block and gaining the associated fee. Otherwise, if miners choose to skip verification of resource-intensive transactions, then an adversary can claim the reward of a contract by broadcasting a transaction with a meaningless re-sult. Since this transaction will not be verified, the adversary obtains the reward. Another controversy about Ethereum and its community concerns the DAO Attack and its resolution. DAO means Decentralized Autonomous Organization and it’s an Organization for capital fundings. In June, 2016 almost 50 million $ was stolen by some attackers, that were able to perform a re-entrancy attack, exploiting a weakness inside the DAO contract, and withdraw all the funds inside it. After a debate lasted some weeks Ethereum community reaches the agreement to perform an Hard Fork of the Ethereum blockchain in order to completely reverse the attack and save the funds. The controversy here is that from June 2016 exist two parallel chain Ethereum Classic and the DAO fork.

3.6

Decentralized Applications

Ethereum is suited to serve as the shared back end to a decentralized Internet, called Web 3.0. A classical web-app has a client-server architecture, working at a very high level, hosted on a hosting provider. All the clients interact with this one cen-tral application and when a client makes a request to the server, the server queries the database and/or cache, reads, writes and updates the database and serves the client. Decentralized applications [31] looks very different at a high level. Every client (browser) communicates with it’s own instance of the application. There is no central server to which all clients connect to. This means, every user who wants to interact with a DApp will need a full copy of the blockchain running on their com-puter. That means, before someone can use an application, he has to download the entire blockchain and then start using the application. This has the advantage of not relying on a single central server. Actually there’s no need to afford the burden of downloading the entire blockchain, since there are a few optimizations to inter-act anyway with it, like Metamask Chrome plugin, as shown later in this paper. In conclusions blockchain in DApps has a dual function:

(38)

22 Chapter 3. The Ethereum Platform 1. Database: the linked series of blocks holds all the transaction data happened inside the network. All the nodes in this network have same copy of the data, that can’t be modified or deleted once written into the blockchain.

2. Code: the database aspect of blockchain just stores the data. The application code is the contract written in the Solidity language. Then the solidity compiler compile the contract to Ethereum Byte Code and then it has to be deployed to the blockchain. So basically, the blockchain stores data, the code and also runs the code in the EVM. To build web based dapps, Ethereum comes with a Javascript library called web3.js [40] which connects to the blockchain node.

3.7

External projects linked to Ethereum

In addition to the Ethereum platform and Solidity language, this research investi-gates also some of the several projects already developed around smart contracts, in order to understand if they should be useful for thesis purposes. Here below there is an overview of the most relevant of them:

1. Truffle: Truffle [12] is a development environment, testing framework and asset pipeline for Ethereum, that allows among other things to compile smart con-tracts, to generate JavaScript bindings and to include easily web3.js library, that facilitates the communication between the web app and the Ethereum client. 2. Metamask: Metamask [26] is a Chrome plugin, that allows having blockchain

accounts inside browsers, without running a full Ethereum node and no in-stalling an Ethereum client. Currently it’s just a developer preview, and has not been released officially, hence it’s non recommend putting serious funds in it, but instead encourage to use it to help prepare DApps for Ethereum browsers. Metamask is a hyper-light client that doesn’t replicate the entire blockchain locally, but it does let users manage their own accounts, so they can casually benefit from the security of private key management, while placing trust for block validation on Metamask’s configured RPC provider.

3. Oracles: an Oracle in the Ethereum world is nothing but a third party to contact for having a connection to a data-source outside of the blockchain. In practice an Oracle watches blockchain events and responds them by publishing results of a query back to the contract, calling a specific function. Currently this is the only way a contract has to interact with the off-chain world. That straightfor-wardly introduces some trust issues because a decentralized contract requires trusting on a single outside data source. A possible solution lies in using mul-tiple independent oracles respond to the same queries to form a consensus. The most famous example of oracle actually is represented by Oraclize [29], a FinTech company providing a reliable connection between Web APIs and Decentralized applications.

(39)

Decentralized Ticketing

Application

4.1

Initial Description

The second part of the work of this thesis was conducted during the internship in-side A-tono technology srl [1] and it concerned in the development of a Proof of Concept Application, that exploits blockchain technology in the context of decen-tralized ticketing distribution and payment methods. This wide-ranging project fits company’s research and innovation goals in new technologies. In particular the goal of this project is realizing a decentralized version of their mobile ticketing applica-tion, called DropTicket [14]. In this chapter are exploring all the several steps of project implementation from requirements definition to development and evalua-tion phases.

4.2

Requirements

The first step is requirements definition. In order to do so it was very useful an-alyzing DropTicket application, understanding issues and characteristics of digital tickets and extracting requirements that can be suitable for smart contracts and de-centralized applications. Below are listed both functional and non functional re-quirements of the application:

4.2.1 Functional Requirements

Basically the application has some mandatory functionalities:

1. Ticket Reseller can create a new contract, becoming the owner of that contract, to sell tickets for a specific event or transport service.

2. Each Ticket must have some information such price, validity time and brief description.

3. Customer can buy a ticket directly from the contract (no intermediary) in a P2P network context, performing transaction in Ethers to become the owner of a ticket.

4. Customer can’t resell the ticket to anyone, can’t copy it and can’t modify it. Eventually if the contract allows it, user can be refunded.

5. Customer can use a ticket to attend an event or to use a service: multiple times (if ticket allows it) or within the validity period.

(40)

24 Chapter 4. Decentralized Ticketing Application 6. Ticket Validation: If the customer wants to check-in, he creates a check-in trans-action on the blockchain. This can be done manually by the application GUI. 7. Know Your Costumer: in addiction to ticket validation it’s necessary to find a

way for identify ticket owner. The protocol studied to match this goal, includes inserting inside ticket information further the owner address also the hash of an user information, like the hash of user Facebook id, that can be retrieved in order to verify identity.

8. Inspection of ticket validity and of customer identity can be done by simply querying the blockchain.

9. Since right now Blockchain and Ethers are concepts hard to understand for most of people, especially users may not to know how to retrieve Ethereum internal cryptocurrency, the application implements also an Euro/Ethers Ex-change service, through which a customer can buy Ethers sending a request to Ticket Provider, using more classical payment methods such Credit cards. 4.2.2 Non Functional Requirements

The application is evaluated also in base on the following parameters:

1. Efficiency: in terms of Networks latency and throughput (transactions/s), re-served storage size (in bytes) and byte-code size (also measurable in bytes). 2. Security: in terms of avoiding dangerous programming patterns, in order to

make smart contracts secure.

3. Privacy: as already said blockchain environment does not guarantee complete anonymity, but only pseudo-anonymity. In addiction to that it will be neces-sary have also a Know Your Customer technique to have some possibility to identify a ticket user, without compromise personal information of the user himself.

4. Cost: each transaction, from contract deployment to a function call that mod-ifies in a certain way the state of the contract, has a cost in terms of gas, and so, on the base of the gas price in Ethers. In evaluating phase it’s present the study conducted in order to compute the cost of the deployment and of the utilization for the whole application.

Mostly of this parameters depend on the Ethereum technology itself so during the evaluating phase both DApp performance and Ethereum behavior are considered.

4.3

Analysis Phase

Before describing the design phase and the whole structure of the application it worth showing some considerations first, that in this phase of analysis, allowed to define the line guides of the project. As already said the goal was the design and the development of a decentralized application that can be suitable for ticketing, so the main problem was basically understanding how translating all business logic, usually responsible of a central server, into a smart contract executed by several de-centralized nodes. Of course the role of a central server still remains, although not within the logic application, but as far as it is concerned smart contracts addresses storage and users management.

(41)

that provided this information identity verification can be easily done. Another im-portant question is should the contract include also the Service Provider? A positive answer should allow Service Provider to have an active role in event or service and ticket configuration inside the contract itself and also should allow to define func-tions to spread incomes between Service Provide and Ticket Reseller automatically, given more transparency and safeguards for all involved. However this last solu-tion is impracticable for business reasons, since Ethereum is a public blockchain and it does not guaranteed the confidentiality that this private business negotiation re-quired. For this reason the developed contracts included only costumers and ticket reseller, i.e. contract owner, as actors.

As matter of facts tickets are configured inside of the smart contract, whose Ethereum address is sent from the central server to the ticket application. Accord-ing to this viewpoint tickets are nothAccord-ing else than blockchain-based tokens, afford-able by interacting with the smart contract. As in off-chain world each ticket must have its own parameters and an its own lifecycle, that goes from its emission to its expiration time, passed through different phases like purchasing and validation. In order to completely exploit the possibilities of smart contracts and of Solidity programming language, all these stages are included in such a way that a ticket is represented inside the contract as a complex structure, who need extra transac-tion to update ticket state in order to be validated. This structure, representing a ticket, must contain some mandatory information like description, price and expi-ration date. About this an important decision regards how this information must be stored inside the contract: the simplest solution to make contract aware of ticket price and consequently knowing if an user transaction contains enough money to buy the ticket, consists to initialize a local variable with an unitary price value, and then, through an appropriate function, computing the total price on the base of other user input (number of tickets, type of tickets, etc.). This solution is particularly suit-able for tickets of events, when all of this information are known a priori. However how showing later this is not always feasible, especially when a ticket service plat-form is pretty complex and big and it’s impossible to transfer all the logic inside of a contract, that it is not able in this case to know ticket price in advance. In fact as al-ready said deploying complex contracts has a not negligible cost and more complex the contract is and more expensive it is, in terms of gas consumed and ethers spent, to deploy it into the network. The alternative in this second case is to establish an escrow protocol between the customer and the owner to configure and buy ticket inside the contract in such a way that safeguards both, as shown later in the contract for train tickets. Another information that is mandatory for ticket is its expiration date: in a decentralized network without a single unit of control there’s no synchro-nization and any idea of global time for nodes. The only possibility to determine expiration time is using block timestamps. However block timestamp dependence is a security issue: miners set the timestamp for the block, normally as the current time of their local system, but it may be malleable by them: it can be varied by roughly 900 seconds, while still having other miners accept the block. Alternatively

(42)

26 Chapter 4. Decentralized Ticketing Application can be used block numbers and assuming to measure time in number of block cre-ated instead of timestamp. In this project block timestamp are used to determine purchase and expiration time, assuming that 900 seconds is a tolerant confidence interval.

Another important issue regarding blockchain technology is represented by the latency of the network and by the number of block confirmations to wait in order to consider a payment confirmed. Ticket reseller can keep trace of its customers and bear the burden of latency times, considering a ticket valid as soon as a transaction is sent, without waiting for confirmations, but double spend should be a security risk in this case. It should be always appropriate waiting a certain number of blocks, in Ethereum a new block is added every 12 seconds on average, before consider a transaction done. This of course represents a throughput and scalability limitation, but this is the only way to avoid double spend attack, as blockchain technology is currently implemented.

Finally the last, but not least aspect to deal with is the payment method: since Ethereum supports its own cryptocurrency, used also for paying miners computa-tion, i.e. Ether, it can be used also as payment currency: actually blockchain tech-nology is not mature enough to have already created a sort of confidence for users to pay tickets in Ethers. But from the moment that to interact with the Ethereum blockchain there’s no alternative than adopt ethers, it is assumes that users can buy ethers from application exchange currency service.

4.4

Design Phase

This paragraph refers to a more formal description of the whole application, ex-pressed through UML diagrams.

4.4.1 Use Case Diagram

In figure4.1it’s shown the behavior on an high level of the whole application through use cases, highlighting the roles of the actors that interact with the system and the functionalities provided by the system itself. The first module is the login package: the user, in order to be able to use the service, must be connected to an Ethereum local node, have an unlocked Ethereum account and be logged to his Facebook ac-count, as required by system KYC policy. Eventually if the user needs some Ethers, he can buy them directly inside the app sending euro to the Owner, i.e. the ticket reseller, that will perform a transaction to transfer Ethers from his account to user’s account. User can interact with the Web App looking for Events or Train Tickets, performing transaction in blockchain through his Ethereum Local node, in order to buy or consume a ticket. Contract owner can withdraw ticket sells revenues directly from the contract.

4.4.2 Sequence Diagrams

Going deep into the application behavior let’s consider the flow of events inside of the more interesting use cases. The first is the Buy Ticket Event use case, whose sequence diagram is shown in figure4.2. This is the use case that describes the inter-action between the user and the smart contract of a particular event in order to buy a ticket: an user chooses an event from the catalog in the server database, in which is specified also the correspondent smart contract address; then the user picks a spe-cific type of ticket, selects the quantity and finally clicks on the Buy button. This

(43)

FIGURE4.1: Use Case Diagram

latter action makes interact the user with the Ethereum blockchain: the user per-forms a transaction, that calls a function of the deployed contract, if he has sufficient amount of ethers in his account balance to pay tickets and miners for the comput-ing work the transaction will be accepted by nodes in the P2P network, otherwise it will be rejected. Once the transaction is confirmed the user is the owner of a token suitable for accessing to that event.

Figure4.3 represents instead the sequence diagram of The Buy Train Ticket use case. The flows starts when user wants to buy a right-to-travel ticket, accessing to the Transport section of the app and inserting research parameters (origin and destination stations, train type, date, service level, ...) and he sends the request to the server, that in turn makes a REST call to an external Train Server Platform and return a list of all possible solutions with correspondent prices. Since in this case not all the business logic has been translated inside the smart contract an escrow protocol is needed. When the user makes his choice, starting the interaction with

Riferimenti

Documenti correlati

In particular, discrete binary phase masks (0 or π) with finite phase-jump positions, known as Toraldo Pupils, have the advantage of being easy to fabricate but offer relatively

Results: The acute BCCAO/R procedure is followed by increased brain tissue levels of the eCBs 2-arachidonoylglycerol and anandamide, palmitoylethanolamide, an avid ligand of

The resulting model, with the 68.4% envelope is overlaid in the lower-right panel of Fig. The above temperature and den- sity functions contain many more free parameters than Eq.

Over the duration of our campaign, the transient showed a degree of linear polarization and position angle fully consis- tent with that shown by stars in the field, whose

In the European lifelong guidance strategy, Career Management Skills (CMS) is the term used to describe the skills, attributes, attitudes and knowledge that individuals

Affettiva Dopo la prima raccolta concezioni, a distanza di qualche giorno ne verrà svolta una seconda. Lo scopo di questa discussione è quello di far emergere il problema di

L’intervallo di variazione della velocità e del momento torcente imposto viene deciso in base alle tempistiche, alle condizioni del sistema e alla sensibilità del banco di

Gli impianti A-CAES (Adiabatic Compressed Air Energy Storage) sono impianti basati su un ciclo termodinamico Brayton, consistono in sistemi con lo stesso principio