100% found this document useful (1 vote)
129 views

A Distributed Library Management System Based On Blockchain

This document is Antonio La Barba's master's thesis from 2018-2019 at the University of Palermo on developing a distributed library management system using blockchain technology. It aims to study applying blockchain to allow direct book exchanges between users without a central authority. The document reviews relevant literature, the state of blockchain technology, and explores using Hyperledger Fabric to build a prototype library management system with a user-centric design approach. Development of the smart contracts and client application is ongoing, with the goal of demonstrating how blockchain can effectively support decentralized solutions.

Uploaded by

Antonio La Barba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
129 views

A Distributed Library Management System Based On Blockchain

This document is Antonio La Barba's master's thesis from 2018-2019 at the University of Palermo on developing a distributed library management system using blockchain technology. It aims to study applying blockchain to allow direct book exchanges between users without a central authority. The document reviews relevant literature, the state of blockchain technology, and explores using Hyperledger Fabric to build a prototype library management system with a user-centric design approach. Development of the smart contracts and client application is ongoing, with the goal of demonstrating how blockchain can effectively support decentralized solutions.

Uploaded by

Antonio La Barba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Università degli studi di Palermo

Laurea magistrale in Ingegneria delle


Telecomunicazioni

A distributed library management


system based on blockchain

Candidato: Antonio La Barba


Relatore: Pierluigi Gallo

Anno accedemico: 2018-19


Abstract

Blockchain is a rather new technology which is generating growing interest due its
decentralized structure removing the need for a central authority while guarantee-
ing high level of security and trust between unknown parties. The most famous
application making use of this technology is Bitcoin; however the application fields
where blockchain technology can potentially bring value, go well beyond the cryp-
tocurrency.

Goal of this dissertation is to study the application of the blockchain technology to


a library management system in order to enable direct book exchange between
private users without the need of a physical library acting as central authority.

Reasons behind the project can be summarized into technological, cultural and
social.
From a technological point of view, on one side we are interested into exploring if
/ how the blockchain technology can support the use case above, while providing an
added value versus the need for decentralization, security and computerization. On
the other side we have experimented the use of a new framework called Convector
to simplify creation of smart contracts and configuration of the blockchain.
From a cultural point of view, we want to provide a simple tool to enable exchange
of books between private users in the belief that fostering such exchanges will lead
to increase cultural cross contamination and passion for reading.
From a social point of view, we believe that book exchange between privates is a
great way to improve social interactions including, but not limited, to exchanges:
between elderly people and younger generations, wealthy people and disadvantaged,
people with a physical disability and ”regular” ones.

Throughout this dissertation we encompass the design and architecture of the so-
lution starting from the requirements and the interactive behavior, continuing with
the analysis of the current state of the art, before proceeding with the definition of
the software architecture, the components and the tools.
In first place, starting from the idea to develop a distributed library management,
we have made an extensive research to document the state of the art both from a
technological and commercial perspective. While adhering to the best practices on
how to properly structure a scientific work, this step has allowed us to understand
better the limitations and the opportunities of our idea, letting us simplifying some
parts and expanding other parts. In the context of this study we have also validated
our initial idea to use Hyperledger Fabric as blockchain solution.
As second step we have defined high level requirements and translated them into a
study of the interactive design, producing a set of twenty-one pages sketching how

2
a client application should behave in terms of user experience. In this way, we have
build the basis to design and implement our work with a user centric approach
in mind.
In a third phase we have tried to assess the tools to be used in order to write the
smart contracts for the blockchain. We have discarded from the beginning the idea
to write the smart contracts using directly the Hyperledger Fabric API and looked at
Composer tool as first option. However following the recent news about disman-
tling the Composer project, we have turned our attention to Convector a complete
suite to develop smart contracts and configure the blockchain solution which is also
very new, being released for the first time beginning 2019.
Once confirmed the idea to use Convector, we have started the actual development
beginning from the server side and the smart contracts. After development of
the main functionalities on the server, we have started to develop a client appli-
cation. Development phase is currently ongoing and daily updates are publicly
available at the following address https://github.com/alabarba/bookswapy

Behind proving the opportunity and feasibility of the application above, our work en-
visions a specific architectural environment which can support the development
while maintaining the complexity low. In particular the use of Convector suite
provides an acceptable balance between abstraction for faster prototyping, mod-
ularity and flexibility to make the solution potentially scaled proof.

We hope that the approach envisioned in our work can be helpful to the scientific
/ software community as a starting point to design and develop effective solutions
based on blockchain.

3
Contents

1 Introduction 6
1.1 Structure of the document . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 The idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 The functionalities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Why blockchain? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 State of the art 12


2.1 Scientific literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.1 Characterization and design of a virtual management system . 13
2.1.1.1 The DELOS Digital Library Reference Model . . . . 13
2.1.1.2 The 5S model for digital libraries . . . . . . . . . . . 17
2.1.2 Applied research in decentralized library management system 19
2.1.2.1 Delos DLMS . . . . . . . . . . . . . . . . . . . . . . 19
2.1.2.2 LibChain . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.3 Blockchain decision models . . . . . . . . . . . . . . . . . . . . 23
2.1.3.1 A cost benefit approach . . . . . . . . . . . . . . . . 23
2.1.3.2 The ten steps decision path . . . . . . . . . . . . . . 24
2.1.3.3 The Wust model . . . . . . . . . . . . . . . . . . . . 26
2.1.3.4 The IBM model . . . . . . . . . . . . . . . . . . . . . 28
2.1.3.5 The Lewis model . . . . . . . . . . . . . . . . . . . . 29
2.1.3.6 Putting the pieces together . . . . . . . . . . . . . . 30
2.1.4 Blockchain technology evolution . . . . . . . . . . . . . . . . . 30
2.1.4.1 Improving security and scalability . . . . . . . . . . . 31
2.1.4.2 Tracking physical assets transactions . . . . . . . . . 33
2.2 Commercial landscape . . . . . . . . . . . . . . . . . . . . . . . . . . 38

3 Blockchain 40
3.1 Introduction and background . . . . . . . . . . . . . . . . . . . . . . 40
3.2 How does blockchain work? . . . . . . . . . . . . . . . . . . . . . . . 44
3.2.1 Identification, Authentication and Authorization . . . . . . . . 44
3.2.2 The data structure . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2.3 The communication protocol . . . . . . . . . . . . . . . . . . . 48
3.2.4 Adding new transactions . . . . . . . . . . . . . . . . . . . . . 49
3.2.5 The consensus mechanism . . . . . . . . . . . . . . . . . . . . 51
3.2.6 Smart contracts . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.2.7 Classification of blockchains . . . . . . . . . . . . . . . . . . . 53
3.2.8 Alternative consensus mechanisms . . . . . . . . . . . . . . . . 54
3.3 Hyperledger Fabric . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

4
CONTENTS CONTENTS

3.3.1 Overview and business requirements . . . . . . . . . . . . . . 56


3.3.2 The network . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.3.3 Identity and Membership service . . . . . . . . . . . . . . . . 57
3.3.4 Peers and ordering service . . . . . . . . . . . . . . . . . . . . 58
3.3.5 Smart contracts and chaincodes . . . . . . . . . . . . . . . . . 60
3.3.6 Ledger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

4 Implementation 64
4.1 The interactive design . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.2 The tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.2.1 Convector Smart Contracts . . . . . . . . . . . . . . . . . . . 70
4.2.2 Hurley . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.2.3 Convector CLI . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.2.4 Convector REST Server . . . . . . . . . . . . . . . . . . . . . 72
4.3 Smart contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.3.1 The lending chaincode . . . . . . . . . . . . . . . . . . . . . . 74
4.3.2 The participant chaincode . . . . . . . . . . . . . . . . . . . . 78
4.4 The client application . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

5 Conclusions and next steps 87

6 Appendix 88
6.1 The interactive design . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.2 The code: smart contracts . . . . . . . . . . . . . . . . . . . . . . . . 97
6.3 The code: client application . . . . . . . . . . . . . . . . . . . . . . . 98

5
Chapter 1

Introduction

In this chapter, we first define the structure of the document, we then describe the
idea and the added value that the blockchain technology can bring to it.

6
CHAPTER 1. INTRODUCTION 1.1. STRUCTURE OF THE DOCUMENT

1.1 Structure of the document


This document follows the following structure:

1. Chapter 1 describes the overall idea and the reasons why the blockchain
technology can be used to implement it.

2. In chapter 2 we describe the current state of the art both from a scientific
and commercial point of view

3. In chapters 3 and 4 we describe the technologies used, describing ar-


chitecture and behavior of respectively: Blockchain, Hyperledger Fabric and
IPFS

4. In chapter 5 we explain and analyze the architecture of our solution includ-


ing also the tools and the configuration. We highlight the design patterns and
the technical choices, describing how do they fit in the overall solution.

5. In chapter 6 we summarize the work done, highlighting the conclusions and


suggesting the envisioned evolution of our work.

6. In the appendix we add the complete UX design as well as the reference


the actual code and the related licenses.

7
1.2. THE IDEA CHAPTER 1. INTRODUCTION

1.2 The idea


When we think about the books you can find into a library, everybody knows that
the library itself owns the books. As there are multiple libraries around and they
have different catalogs, it makes sense to create large consortium of libraries and
provide end users with a single consolidated global view including all the books in
the consortium. Many successful attempts have been done in this sense and this is
great.
However most of us have a number of books at home and after reading, they often
remain in our bookshelf forever. If everybody of us was able to bring all of these
books into a unique physical library that would likely be the biggest library in the
world!
Luckily we don’t even need to bring all the books into a physical library... In the
same way as a library joins a consortium, making its catalogs publicly available
without moving the books, we might join a virtual community making our own
catalogs publicly available while keeping our books at our home.
This would make our home part of a giant virtual library consortium and enable the
direct exchange of our books with people close to us. Even more exciting we can
make this virtual consortium completely decentralized. This way, not only direct
book exchange between private users becomes possible but there is also no central
point of control so the system belongs to all the people who are willing to use it
rather than to a particular organization.
On top censoring it, dismantling it or switching it off becomes pretty hard.
Decentralization comes at the cost of increased complexity to make things working
and a tremendous fear that things might go wrong because nobody is really in
charge. Fortunately current technology can help us in making things happen while
keeping security and trust levels very high.
In short: by using the blockchain technology we want to develop the first virtual
decentralized library built on private users’ book collections.

8
CHAPTER 1. INTRODUCTION 1.3. THE FUNCTIONALITIES

1.3 The functionalities


Below we provide an high level overview of the main functionalities:

• Access to the system is allowed only to registered users, so a sign up and a


sign in procedure are requested.

• Users have roles that can be assigned by the administrators. User roles are:

– Administrator
– Arbitrator
– Regular user

• Administrator users should be able to assign and change roles to other users

• Users should be able to modify their profile by changing location, default


escrow and fee (only for arbitrator users)

• Each user has its own catalog and should be able to add a new book to the
catalog

• Users should be able to modify or delete a book in their catalog

• Users should be able to see the global list of books. The global list should
show the correct state of the book (owner, current owner, location etc..). On
the global list it should be possible to filter the books owned by the user and
the books borrowed/lent by the user

• Users should be able to search for a book. Search results should show: book
metadata, owner, location and owner contact

• Users should be able to borrow/return a book and register the transaction in


the blockchain.

• Borrowing procedure should support a way to agree and pay and escrow which
will be refunded when the book comes back to the owner. Both users must
pay the escrow. Escrow value can be set also to zero (no escrow) if the two
parties trust each other

• Users should be able to open a dispute on a book that they have borrowed or
lent.

• Borrow procedure should support a way to select an arbitrator who will be in


charge to solve any possible dispute.

• When a dispute is opened the book’s state should be moved to ”dispute” and
the arbitrator should be notified.

• If the book state is in ”dispute” the arbitrator should be able to split the total
amount in three parties:

– Arbitrator’s fee (fixed)

9
1.3. THE FUNCTIONALITIES CHAPTER 1. INTRODUCTION

– Amount to be returned to the borrower (can also be zero)


– Amount to be returned to the lender (can also be zero)

• When a dispute is opened, the arbitrator can move the funds (according to the
proposed schema in the point above) only with at least another party signing
(either the borrower, the lender or both)

• Users should be able to see all the book transactions.

10
CHAPTER 1. INTRODUCTION 1.4. WHY BLOCKCHAIN?

1.4 Why blockchain?


The choose of the blockchain technology is due to multiple reasons:

1. Decentralized architecture. The idea to use a decentralized solution is due


to ideological and technical reasons:

• From an ideological point of view by choosing a decentralized architec-


ture we want to promote a principle of freedom and to provide a solution
which is resistant to political censorship
• From a technical point of view choosing a decentralized solution brings
the benefit of not having a single point of failure

2. Need to bring an element of trust into a system where users do not trust each
others.

3. Security by design. Which means that if we implement correctly a blockchain


solution, we will inherit the security features that blockchain provides.

4. Opportunity based on use case assessment. As we will see in the next


chapter, different blockchain decision models indicate that we might have a
use case for using blockchain. This means that, in our specific scenario, a
blockchain solution might have a positive benefit cost ratio

5. Distributed nature of data. In our specific scenario data is distributed


by nature. If there are not additional costs, a solution which keeps data
distributed seems to be more efficient.

11
Chapter 2

State of the art

In this chapter we are going to discuss the current state, challenges and evolution
of virtual library management systems. While doing that, we will first analyze the
related scientific literature and then the related commercial landscape.

12
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

2.1 Scientific literature


Library management is a complex topic due to many actors involved and its multi-
disciplinary essence. Our journey in the related scientific literature begins with the
description of some important works done to characterize a virtual library manage-
ment system and properly design it. We will then continue by describing the aca-
demic efforts done so far to characterize, design and implement a distributed library
management system. After that we will look at some decision models developed
to assess the opportunity of using blockchain technology for a specific application.
Finally we will look at two interesting examples on how the blockchain technology is
evolving respectively to improve scalability /security and to secure also the exchange
of physical assets

2.1.1 Characterization and design of a virtual management


system
Multiple frameworks have been developed so far to characterize a virtual manage-
ment system. We will focus our attention on two of them:
• The DELOS Digital Library Reference Model
• The 5S model for digital libraries
Their idea is to provide a comprehensive model to formally describe a digital library
even in the most general cases. This is the base for designing the system in the best
possible way. In the next sections we are going to analyze them separately.
As a side note, the DELOS digital library reference model and the 5S formal model
are attempts to abstract the description of a digital library and as such they don’t
specify any particular approach in the architecture topology (centralized or decen-
tralized). This choose needs to be done by the system designers while translating
the formal model into a more concrete model fitting the specific system needs (for
ex. the Reference Architecture and the Concrete Architecture that we will describe
later).

2.1.1.1 The DELOS Digital Library Reference Model


The DELOS digital library reference model is a manifest supported by a network
of excellence on digital libraries and it exploits the collective understanding that has
been acquired on Digital Libraries by European research groups active in the Digital
Library field throughout many years, both within the DELOS Network of Excellence
and outside [21]
To summarize, the document can be considered as divided into three ideal major
sections [20]:
• The first section (Part I and Part II of the document) includes some back-
ground information and definitions .
• The second section (Part II and Part III of the document) introduces the
actual reference model
• The third section (Part IV) provides a checklist to confirm if a certain imple-
mentation is compatible with the DELOS reference model

13
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Background information and definitions The first section starts by distin-


guishing between:
• Digital library intended as the virtual organization managing digital content
with certain functionalities and policies

• Digital library system intended as the software implementation serving the


scope of the digital library

• Digital library management system intended as the software used by


administrators to set up configure monitor and upgrade the digital library
system
It then identifies the different users interacting with the above elements:
• Designers who are in charge to design and implement the digital library
system based on the specific needs of the digital library

• System administrators who control the digital library system through the
digital library management system

• End users which can be further divided into:

– Content creators who are the authors of the contents included in the
digital library
– Content consumers who are the consumers of the contents included in
the digital library
– Librarians who sell, lend and advice on the contents acting as a bridge
between creators and consumers

Next to that the model introduces six main and three auxiliary cross concepts, called
domains ,which are used to build a formal model for the digital library system.
The main domains are:
• Content: which relates to the nature of the digital resources

• User: which refers to users interacting with the system

• Functionality which refers to the supported features

• Quality which refers to all the quality aspects

• Policy which refers to the rules needed to support the features and the orga-
nization

• Architecture which refers to the design and the implementation of the digital
library system
The auxiliary domains are:
• Time which refers to aspects related to periods of time

• Space which relates to aspects related to physical location of users, content


and sub systems interacting within the digital library

14
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

• Language which relates to communication aspects

It is then introduced the development framework see figure 2.1 which is a way
to link the reference model down to more project specific artifacts.

Figure 2.1: The Digital Library Development Framework

The main elements of the framework are:

• The reference model which is a general abstract model and can be used to
describe any digital library

• The reference architecture which is the translation of the reference model


based on the peculiarities of a specific project. Different projects will have
different reference architectures but there is not yet any reference to the specific
technology used

• The concrete architecture which is the translation of the reference archi-


tecture into a document specifying also the technologies to be used

• The implementation which is the actual implementation of the concrete


architecture

The reference model In this section the actual reference model is presented as a
conceptual framework aimed at capturing significant entities and their relationships
in a certain universe with the goal of developing more concrete models of it [20]
So the reference model captures relationships between entities and is goal is to
develop more concrete models (reference architecture and concrete architecture
described in the previous section). The result is a relational model leading to define
a hierarchy of 226 ordered classes and 60 ordered relationships that can completely
define a digital library system. This relational model is a graphical representation
based on maps and it encompasses all the main domains described in the previous
section which are all inherited from a common entity called ”Resource”. For exam-
ple figure 2.2 refers to the user domain content map[20] Each class is then analyzed

15
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Figure 2.2: The user domain content map

separately by specifying a definition, the class relationships, the rationale and pos-
sibly an example. For example figure 2.3 refers to the class number 26 (the end user
class) [20]

Figure 2.3: The end user class

The checklist The checklist has been designed mainly:

• For auditing purposes

• As a tool for the designers

Seen the large applicability of the reference model through different contexts, it was
important to provide a tool to make sure that the reference architecture of a specific
project was inline with the reference model. The checklist is organized per the main
domains described in the previous sections. Each item includes the following fields:

16
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

• Criterion which highlights some conditions to be matched and whether or not


the presence of that particular condition is mandatory (MUST), recommended
(SHOULD) or optional (MAY)

• Why it is needed a short explanation on the reasons why the element is


considered as mandatory, recommended or optional

• DLRM Concept Identifier(s) Identifies one of the 226 classes

• DLRM Relation Identifier(s) Identifies one of the 60 relationships

• Examples

• Suggested Types of evidence a suggestion on what to check in order to


prove whether or not the specific criterion has been matched

To provide an example picture 2.4 shows the criterion about the presence of the end
user role.[20]

Figure 2.4: Criterion about the presence of end user role

2.1.1.2 The 5S model for digital libraries


The 5S formal model is another framework to abstract the structure of a digital
library. [25]
5S stands for Streams, Structures, Spaces, Scenarios, Societies.
The article introducing it [25] can be divided into two ideal parts

• The first part (Section2 and Section3 of the document) defines the concepts
of Streams, Structures, Spaces, Scenarios, Societies while also discussing in-
formally three possible applications.

• The second part (Section4 and Section5, Section6 of the document) introduces
the formal model and provides a couple of examples on how to apply it

Informal definitions and applications The first part of the article starts by
defining the 5S:

• Streams refer to the digital content that can be a written text but also, for
example, an audio visual file.

17
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

• Structures are oriented graphs that can be used to define relationships be-
tween different elements

• Spaces are group of elements in which some operations are defined.

• Scenarios Are use cases generating a change to the state of the system

• Societies are groups of users, with their roles, needs and social context.

Following that, they try to apply the model into three different scenarios. At this
stage the model is applied in an informal way just based on the informal definitions
provided above:

1. First scenario is a Digital Library Taxonomy built by researching and collecting


words about a digital library and then trying to cluster them in groups (like
in a brainstorm experiment). Although the clusters have been made without
the 5S model in mind, they can be fully explained through the 5S model

2. Second scenario is about two real use cases:

• Building a special digital library dedicated to Theses and dissertations


• Analyze the technical infrastructure of Open Archives Initiative which
is a multi-institutional project to address interoperability of archives and
digital libraries by defining simple protocols for the exchange of metadata
[25].

Again the article arguments as the 5S model is suitable to provide an abstract


description of both the systems. This is done by analysing all five domains of
the model in the context of the specific projects.

3. Third scenario is about generating an automatic tool to describe a digital li-


brary system with the 5S model. It all starts by defining 5SL.
5SL is an XML serialization of 5S and has a formal semantics, which can be
understood in terms of a translation of the language constructs and primitives
into the 5S formalisms. Its formal basis provides an unambiguous and precise
Digital Library specification tool, which facilitates prototyping, allows proofs of
assertions, and aids validation of implementations.
In the context of a specific project, after a first analysis based on 5S model, the
digital library designer will insert the specification for that particular project
into a digital library generator using the 5SL language and the generator will
return a set of components (classes, database schema) which are tailored to
interact with others pre built components to implement the requested specifi-
cations.
It is worth to note that this process of writing the project specifications us-
ing the 5SL language to generate artifacts that can be used to actually build
the system, resembles the development framework introduced in the previous
section 2.1. This is not by chance, as the DELOS model (which has been
published first time on 2007) has incorporated many of the principles included
in the earlier 5S model (published on 2004)

18
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Definition of the formal model In this part the 5S model is defined using
a rigorous mathematical formalism: for example figure 2.5 [25] shows the formal
definition of society:

Figure 2.5: 5S formal definition of society

The formal model defined in this second part is then used as starting point to
analyze two real case scenarios: the open archives Initiative already mentioned above
and the NDLTD union archive.[25]

2.1.2 Applied research in decentralized library management


system
In this section we are going to briefly explore two different implementations of a
distributed library management system done respectively in the context of the DE-
LOS network of excellence initiative and as research project lead by the university
of Berlin.

2.1.2.1 Delos DLMS


Delos DLMS is the implementation of a next-generation digital library system in-
cluding support for a number of advanced features like audiovisual research, per-
sonalized browsing, annotation and processing of received information etc.[16] It is
build on OSIRIS: a general purpose middleware software which implements a true
peer-to-peer process execution[32]
Processes are the way to manage aggregated web service requests in a certain or-
der and with certain constraints. The architecture of Osiris (see picture 2.6[32]) is
divided in two parts:
• A true peer to peer system of nodes implementing a fully distributed execution
engine where is running a layer called HDB (Hypermedia database). This
layer is able to manage SOAP service requests while exposing the services
globally provided by the system with a WSDL description. Each node is able
to assess, based on cost considerations, whether the requested work needs to
be executed entirely on the node itself or if it should be totally / partially
handed over to another peer in the network. In this way OSIRIS implements
a mechanism analogous the the IP routing where instead of delivering a packet
to the destination node, the network will deliver a process instance (or a single
activity inside a process) to another peer. This mechanism is called process
navigation [32]

19
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

• A global centralized repository to store the metadata information providing


the knowledge about which nodes can execute which activity. The global
repository also manages the replication of the metadata through the peers
and implements a publish and subscribe mechanism similar to UDDI.

Figure 2.6: The OSIRIS architecture

At the application level, DELOS DLMS presents a modular structure where


each module has been deployed from a European university and perform a specific
function of the digital library system as depicted in figure 2.7 [16]

Figure 2.7: Systems integrated in the DELOS DLMS

To summarize, by exploiting OSIRIS middleware, the DELOS DLMS has imple-


mented a decentralized library system. However this is done mainly to optimize the
overall performance by distributing the load of process execution on different peers
and an element of centralization is still present.

2.1.2.2 LibChain
LibChain is a digital library system entirely based on blockchain. The initial idea
came from the university of Berlin, was supposed to be developed in the context

20
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

of Atos challenge 2017 [17] [19] and it initially consisted into enabling free and yet
secure book exchange on global base both:

• Between privates and libraries

• Directly between privates without any library to intermediate

• Between libraries

In all above cases with the two parts of the exchange not necessarily trusting
each others. [17] As the application was supposed to manage both physical and
virtual books, a way to empower a trustful exchange also in the case of physical
books was needed. To achieve that, coloured coins were supposed to be used.
Practically the initial idea has been only partially implemented leading to a
simplified architecture where end users can exchange books only through the library
with the LibChain application running on top of the library software. On the other
side, the Publishers user has been added enabling creation and sale of new books.
The main architecture of LibChain is divided into three parts [18]:

• React is used to implement a prototypical library page

• Node.js provides a REST interface which enables the connection to the front
end

• Ethereum blockchain is used to deploy the following contracts. See figure 2.8:

– LibChain contract is used to instantiate new libraries and publish-


ers. It also provides getters for retrieving existing instances.

– Book contract collects meta-information on the books and defines how


to access the data (books) for example a link to the publishers book
repository.

– Publisher contract allows to instantiate new books and add them


to the publishers catalogue. It’s primarily used to publish books and
sell instances to libraries. (so it includes a buy function which is called
by the library buy function to make a note on the publisher site for each
purchase )

– Library contract contains functions to buy book instances from pub-


lisher contracts and to perform borrow and return requests.

21
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Figure 2.8: The LibChain architecture

Whisper protocol is used for the messaging. Communication between the Node.js
back-end and the blockchain are realised through the Web3.js api.
To buy a book, the library instance will call the buy function which in turn calls
the publisher buy function to record the purchase on the publisher site and invoice
it off chain. Then the book is stored in the ledger which makes the lending available
to the library users.
To borrow a book, the user has to authenticate on the library service in a clas-
sical way (e.g. username/password). The library therefore knows, that the user is
authorized to borrow books. If the user wants to borrow a book, he has to create
a RSA-key pair. The private key is stored on the client site while the public key
(together with the book id) is used as argument in the borrow request. Since the
user is already authenticated, the library will forward this request to the library
contract without any further verification. The contract checks the availability of
the requested book instances and stores the user public key into the book instance
itself. Once the end user has borrowed a book, he can access it using a gateway-
address (normally a link to the publisher’s site) stored into the book contract and
submitting a view request including:

• His public key (which he had already submitted to the library on the borrow
request)

• The book id encrypted with his private key to prove his identity.

The publisher will then decrypt the book id with the end user public key, to verify
that he is who he claims to be (authentication). If successful, he can then check
that the end user public key is inside the book instance to lend (authorization) and
allow access.

To return a book, the public key entry of the current owner of the book is deleted
from the book instance and the counter of available instances of the returned book
is increased by one.

22
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

2.1.3 Blockchain decision models


In this section we are going to analyze some frameworks that have been developed
to support designers and organizations in the decision whether or not to use the
blockchain technology for a certain project.

2.1.3.1 A cost benefit approach


The first approach is described in the article Blockchain-based platforms: Decen-
tralized infrastructures and its boundary conditions and it’s based on cost benefit
considerations in three areas [31]:

• Reduced transaction costs versus increased complexity.


Under the assumptions of uncertainty and opportunism, the cost of economic
transactions (TCE) are influenced by three factors:

– Asset specificity which represents the degree of mutual dependency be-


tween the two parts involved in the transaction. The higher the mutual
dependency the higher the TCE
– Uncertainty which relates to the likelihood of bargaining before and after
the transaction. The higher the uncertainty the higher the TCE
– Frequency which relates to the need of often monitoring the transaction.
The higher the frequency the higher the TCE.

For equal levels of asset specificity, using blockchain can often globally reduce
the TCE due to use of smart contracts which in general reduce uncertainty and
frequency. When the gains from reduced opportunism and uncertainty costs
outweigh the losses from increased costs of coordination and complexity, the
blockchain-based platforms are more advantageous than centralized platforms.
[31]

• Increased system integrity versus increased storage costs and in-


creased resource consumption
Blockchain provides data immutability and built in trust however increased
integrity does not come for free and there are at least three aspects to to be
considered:

– The consensus mechanism has a cost because often based on scarcity of a


certain resource. For example the proof of work has high computational
cost which makes scalability a challenge
– Without a central organization being able to make economic of scale while
offering storage space (ex. cloud services) and with the need to record the
full history of transactions the cost of the storage and the infrastructure
can become significant
– Tracking transactions of physical assets while keeping integrity is a chal-
lenge which increases verification costs (with third parties called oracles
making a verification off chain)
When the gains from immutability and transparency of transactions out-
weigh the losses from increased technology cost of verification and storage,

23
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

the blockchain-based platforms are more advantageous than centralized


platforms [31]

• Intrinsic motivations versus extrinsic motivations


More often than not, distributed communities are driven also from intrinsic
motivators (like common values, passions and interests) as opposite to cen-
tralized communities that are typically driven more by extrinsic motivators
(like rewarding mechanisms, increasing personal reputation etc..) Blockchain
is somehow different by harnessing incentive mechanisms anchored on both
intrinsic and extrinsic benefits. Levels of intrinsic and extrinsic motivation
however are constantly changing (for example typically new users who just
joined a community, have higher levels of intrinsic motivation while, with
time, their reputation increases and with it also the extrinsic motivation).
When the gains from intrinsic benefits outweigh the low extrinsic benefits in
the short term, blockchain-based platforms are more advantageous than cen-
tralized platforms. When the gains from extrinsic benefits outweigh the low
intrinsic benefits in the medium-term, blockchain-based platforms are more
advantageous than centralized platforms. [31]

In conclusion the model offers a framework based on cost profit assessment on each
of the above areas to understand if using the blockchain technology can be beneficial
for an organization.

2.1.3.2 The ten steps decision path

The article A Ten-Step Decision Path to Determine When to Use Blockchain Tech-
nologies [30] came out on June 2019 so it keeps into account all the other frameworks
that were developed before plus the latest evolution of blockchain technology and
commercial landscape. This framework consists of ten questions: first seven are
meant to exclude the use of blockchain, while last three are meant to understand
which blockchain to use (see picture 2.9

24
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Figure 2.9: The Ten Steps model

Within the article the authors explain in detail each step while in parallel apply-
ing it to a practical case (Danish maritime shipping industry). Let’s now see how
our project fits into this model:

1. Need for a shared common database? Not completely. Technically it


would be possible to use a central database. However a central database would
not cover the need for inherent distributed architecture to deploy the idea in
countries where political censorship is in place. As a side note the article
mentions that the blockchain is essentially a shared database [30]: while it is
indeed technically possible to implement a blockchain as a shared database,
saying that the blockchain is a shared database seems not completely accurate.
Blockchain is in fact a decentralized ledger which is able to control access
to data, the data itself can be stored in a centralized or decentralized fashion
independently from the choose to use blockchain.

2. Multiple parties involved? Yes. Being a distributed community based


project there are multiple end users with different roles. Another way to see
it is as two opposite parties in the exchange one party lends a book while the
opposite party borrows the book with the arbitrator kicking in when there is
a dispute.

3. Involved parties have conflicted interests /trust issues? Yes, in general


the user who lends the book and the user who borrows the book don’t trust
each other.

4. Parties can /want to avoid a trusted third party? Not completely.


Technically it would be possible to use a central server (where users have to
register) as TTP. However this would not cover the need for inherent dis-
tributed architecture to deploy the idea in countries where political censorship
is in place.

25
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

5. Rules governing system access, differ between participants? Yes.


Users have different roles and therefore they require different access rights.

6. Transacting rules remaining largely unchanged? Yes. Normally the


transacting rules (for example a book can be exchanged with another book
or with a token, lend duration etc..) will remain unchanged. As as note the
rational behind this question is that accommodating changes to the ledger is
difficult due to ledger immutability and that smart contracts offer less flexi-
bility than human interaction.

7. Need for an objective immutable log? Yes. Objective and immutable


log is needed to track ownership and properly manage control the exchanges

8. Need for public access? No. Registration is required to access the system
and on top users have different writing rights based on their role.

9. Are transactions public? Yes. All registered users can see all the transac-
tions.

10. Where is consensus determined? Intra-organizational. The community


using the application can be regarded as a single organization where some
users have a privileged role.

Result: The model indicates that private permissioned blockchain might


be the preferable choose.

2.1.3.3 The Wust model


In the article Do you need a blockchain? [33], the Wust methodology is introduced
and then applied to some prominent use cases where there is wider interest to adopt
blockchain technology:

• Supply chain management

• Inter bank and international payments

• Smart contracts

• Decentralized autonomous systems

• Intellectual property

• e-Voting

• Land titles

• Trading and fair exchange protocols

The model is based on the structured graph shown below in picture 2.10.

26
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Figure 2.10: The Wust model

Conclusion of the article is that depending on the application scenario, there are
indeed valid use cases for each, permissionless and permissioned blockchains, and
centralized databases that need to be determined carefully. [33] It’s worth mentioning
that while applying the model to the above use cases, a common challenge emerges
for many of them, being the interface between the digital and the physical
world: if we want to use blockchain to track physical assets we will always need
some kind of connection between the physical asset and its digital representation
and this connection should be tampered proof.
Our double escrow mechanism (inspired by the article described in the next section)
represents a possible way to mitigate/solve the problem in our specific scenario.
However the challenge at today remains opened and potentially represents a major
obstacle to effectiveness of blockchain systems in the real world.
Let’s now briefly analyze our idea by using the Wust model:
1. Do you need to store state? Yes. There is indeed a need to store the state
of a book in terms of which books and ownership history.

2. Are there multiple writers Yes. Being a distributed community based


project, different people with different roles can write into it.

3. Can you use an always online trusted third party? Not completely.
Technically it would be possible to use a central server (where users have to
register) as TTP. However this would not cover the need for inherent dis-
tributed architecture to deploy the idea in countries where political censorship
is in place.

4. Are all writers known? Yes. We assume that there will be a registration
mechanism so all writers are known.

5. Are all writers trusted? No, in general the user who lends the book and
the user who borrows the book don’t trust each other.

27
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

6. Is public verifiability required? Yes. All registered users can see all the
transactions.

Result The model indicates that a public permissioned blockchain might


be the preferable choose.

2.1.3.4 The IBM model


The IBM model [22] depicted in figure 2.11. highlights how the key features of the
blockchain fit into business processes and applications [23]

Figure 2.11: The IBM model

Let’s validate our project against it:

1. High performances, milliseconds transactions? No. No especially high


performances are required.

2. Are you managing contractual relationships? Yes. Exchange of books


can be regarded as a contractual relationship with the different parties ex-
changing assets in agreement with pre-specified rules.

3. Are you working with complex business logic? No. Business logic
should stay quite simple.

4. Does identity matter Yes. Users have different roles and requiring different
access rights, so identity matters.

5. Do you need to keep your transactions private? No. All registered


users can see all the transactions.

6. Does this require a market approach? Yes. As it is based on tracking


transactions.

28
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

7. Does this require greater than two parts? Yes. In some cases three
parties are requested (a lender, a borrower and an arbitrator)

8. Are you looking to reduce costs? Not completely. Cost reduction comes
as a nice to have. The real goal is to empower privates to exchange books
without any intermediation.

9. Are you looking to improve discoverability? Yes. Discoverability is key


to the project as one of its goals is to make private libraries discoverable by
other private users.

Result: The model indicates that there might be a use case for blockchain (steps
6, 7, 8 and 9)

2.1.3.5 The Lewis model


The Lewis model [27] offers a more entrepreneurs oriented framework (see figure
2.12), based on the author’s experience as venture capital business development
director.

Figure 2.12: The Lewis model

Let’s apply it to our project:

1. Can you articulate a real business problem that needs solving? Not
completely. Although we have a definition of a problem which has been par-
tially validated by talking with groups of readers who would need some kind
of tool to track exchange of books, it is not fully clear just yet how this can
translate into a viable business model.

2. Could this have been fixed before blockchain? Not completely. Tech-
nically it would have been possible to solve the problem before blockchain
by using a centralized architecture. However this would have not covered the
need for inherent distributed architecture to deploy the idea in countries where
political censorship is in place.

29
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

3. Is this a ”digital identity” and/or ”blockchain are free” play? No.


The main reasons behind the project are neither related to the digital identity
area nor to potentially lower cost of the blockchain technology.

4. Should or could a central entity have overall control? Not completely.


Technically it would be possible to use a central server (where users have to
register) as TTP. However this would not cover the need for inherent dis-
tributed architecture to deploy the idea in countries where political censorship
is in place.

5. Will all participants need to upgrade/replace existing systems? No.


The tool will work without any need to upgrade existing systems. Just a
simple software installation from scratch will be needed.

6. Will participants mind their data being visible? No. Our working
assumption is that participants will want to disclose their book’s collections
to exchange books with other participants.

Result The model indicates that there might be a use case for blockchain

2.1.3.6 Putting the pieces together


Let’s now try to summarize the results coming from analysis of the proposed decision
models above. All the frameworks converge indicating that there might be a use
case for a blockchain solution and that a permissioned blockchain might be
the preferable choose. There are however some points of attention:

• There are no specific technical constraints to not use an always online TTP so
the reason to still use blockchain turns out to be related with the ideological
choose to use a decentralized system. However, the same ideological choose
versus a decentralized system was the founding element of the bitcoin [28].

• The lack of a connection between the physical book and its representation
on the blockchain represents a potential challenge for the project. While this
is true for any blockchain system dealing with physical asset exchange, our
escrow mechanism is a potential way to solve the problem.

• Although the project might enable business profitability in different ways (tar-
get advertising, exchange based micro payments, off chain arbitration services,
oracles services, product as a service etc..) in this phase we don’t have a struc-
tured business model in mind. Business profitability is out of the scope of the
present dissertation and can be considered in a second phase.

2.1.4 Blockchain technology evolution


As a very new technology which (a part for the bitcoin application) is not yet broadly
adopted in real world scenarios, blockchain is constantly evolving and there is a lot
of research ongoing to improve its inherent limitations.
In this section we will look at two interesting works done in this sense:

30
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

• A modification of the blockchain data structure and consensus algorithm to


improve security and scalability

• A possible way to securely track the exchange of physical assets on the ledger

2.1.4.1 Improving security and scalability


In the interesting article TrustChain: A Sybil-resistant scalable blockchain [29] the
authors propose a modified blockchain to:

• Improve scalability by removing a major inherent limitation in the number of


transaction that can be written over a certain period of time

• Improve security by demonstrating that the resulting system is resistant against


various type of attacks including Sybil attack

We can ideally split the article’s dissertation (excluding conclusions) into four parts
:

1. In the first part (chapters 1 to 4) state of the art and the idea of a new data
structure and consensus algorithm for the blockchain is presented

2. In the second part (chapter 5) the NetFlow algorithm is introduced

3. In the third part (chapter 6) resistance to major known security attacks is


demonstrated

4. In the forth part (chapter 7) performances of the system are analyzed

In the following we are going to summarize them one by one.

New data structure and consensus mechanism After a brief introduction


on the technology and on current art of the state, the TrustChain architecture
is introduced: the idea behind is to bind the transaction around the two nodes
involved.
At the level of the blockchain data structure there are three main differences
versus a traditional data structure:

• Each transaction is signed by both participating parties rather than by just


one party

• Each block contains only one transaction rather than multiple transactions

• Each block also includes an hash reference to the the chain of the coun-
terparty, rather than just a reference to the previous block in the chain (note
that the additional hash reference to the Merkle tree is not needed anymore
because there is only one transaction per block)

At the level of the consensus algorithm the main difference versus the traditional
model is that every participant grows and maintain his own chain of transactions
rather than trying to converge on a unique chain based on the consensus mecha-
nism. Consensus is reached among participants of a specific transactions instead of
consensus on a global level [29]

31
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Figure 2.13: The TrustChain data structure

NetFlow algorithm The NetFlow algorithm is a way to build a weighted graph


based on a contribution score assigned to each peer of the network and indicating
the peer’s degree of contribution of the P2P network. The idea is to prioritize in-
teractions with peers who contribute more to the P2P network which should
lead to inherent marginalization of the ”free riders”.
As first thing, starting from a set of peers and interactions, a weighted interac-
tion graph for the system is formally defined basically representing the degree
of interaction of each node of the network with all the other nodes of the system.
Naturally this representation is just theoretic as nodes will mostly have a subjec-
tive view based on their partial knowledge of the network state. For this reason a
subjective work graph for node i is formally defined as the weighted interaction
graph related to a system where the set of interactions in the model is a subset of
all the interactions that includes at least all interactions of agent i [29] (plus all the
other interactions known to the node i).
Given a subjective graph for node i and knowing a subset of all the nodes composed
by only the nodes interested into making a transaction with node i, is then possible
to formally define:

• A score for each of the nodes in the subset

• An accounting mechanism which is used to calculate this score

• The informativeness defined as the fraction of nodes in the subset to which


the above accounting mechanism is able to assign a non zero value

• A function called allocation policy to select one of the nodes in the subset
based on the score. This node will then be selected to initiate the transaction.

Naturally the higher the informativeness the more accurate will be the decision
on which node to select for the transaction. Being the allocation policy based on a
max flow calculation, turns out that a simple way to increase informativeness is to
weight the work performed by other agents higher than the work consumed by them.
[29] which is taken into account by using a scale factor alfa . In the forth part
performances of the system will be measured for different values of alfa.

32
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Security analysis In this part security against the following attacks is demon-
strated:

• Double spending attack

• Replay attack

• Sybil attack here it is formally demonstrated as the profit of such attack has
an upper bound equal to the factor alfa.

• Hiding blocks

• Refusal to sign

• Whitewashing

turns out that a key value of the system is the need to just detect rather than
prevent a number of attacks, as based on the NetFlow algorithm violators will be
detected and lose the trust of others [29] This results in the possibility to execute
transactions in parallel which increases performances.

Performance analysis Overall performances of the system in terms of transac-


tions per seconds are first measured by using different machines (laptops and mobile
devices) and showing that the system is able to execute up to 4.9 transactions per
second on mobile devices and roughly one order of magnitude more on laptops
(against the 4.6 transactions per seconds of bitcoin which is achieved through high
performing and expensive hardware).
It is then shown as in the worst case computational complexity if O(n3 m) where
n is the number of peers and m is the number of edges in the network. Finally the
results of a real world trial with 917 volunteers. Results confirm that by increasing
the scaling factor alfa the informativeness of the system becomes higher, however
this comes at the cost of some agents with a ratio upload/download significantly
below 1 have a positive score (which does not happen when alfa=1).[29]

Document conclusions In conclusion the TrustChain system is effective in iden-


tifying ”free riders” without any central authority. This enables increased security
and increased scalability due to detection (instead of prevention) mechanisms being
sufficient to guarantee security which in turns means possibility to execute transac-
tions in parallel.

2.1.4.2 Tracking physical assets transactions


In the article Blockchain-based Proof of Delivery of Physical Assets with Single and
Multiple Transporters [26] the authors propose a mechanism to reliably deliver phys-
ical assets leveraging on the blockchain functionalities.
The work can be split into two ideal parts (excluding conclusions):

1. State of the art and description of the solution (Sections I to IV)

2. Testing (section V)

33
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Description of the solution The proposed solution is based on the identification


of:

• Roles involved in the delivery process

• Contracts used and their data structure

• Logic to guarantee proof of delivery

The identified roles are:

• Seller: an entity who wants to sell an asset

• Buyer: an entity who wants to buy an asset

• Courier Service(s): entities in charge for the shipment

• Arbitrator: an entity who will arbitrate off chain in case of dispute

• Smart contract attestation authority an entity attesting each contract in


the chain to ensure that the code satisfies the agreed upon terms and conditions
[26]

Three different type of contracts are defined along with a precise structure to
chain them [26]:

• Proof Of Delivery (PoD) contract

• Courier Services (CS) contract

• Buyer transporter (BT) contract

The CS contract needs to be used only in case there is more than one Courier
Service, the other two contracts must always be used.
There is a precise chain structure between the contracts including also the
roles involved in each contract see figure 2.14 [26]:

• The PoD contract is always the first contract of the chain and it is signed by
both the buyer, the first transporter and the seller. It includes:

– The address of its direct child (a CS contract if there is more than one
courier service or a BT contract otherwise)
– The address of the BT contract

• The BT contract is always the last contract of the chain and it is signed by
the last courier service and the buyer

• The CS contracts are in the middle of the chain and are signed by the two
courier services engaged in that part of the shipment

• Every parent contract has the address of its child contract and every child
contract has the address of its parent contract

• All the contracts have the address of the PoD contract

34
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Figure 2.14: The structure of the chain of contracts

The proposed mechanism is based on the following elements:


• A key, whose hashed value is included in each contract along the chain and
which is used to confirm that a package related to the shipment in the contract
has been received (the key cannot confirm that the package has not been
replaced or damaged)
• A protocol describing the order in which the operations, related to handing
over the package along the chain, are executed
• An escrow paid by both the buyer the seller and the courier service(s) which
is returned only after confirmation from the buyer that the right package has
been received and it’s not damaged
• A logic to put everything together
As first thing the PoD contract is signed, this contract includes also the hash
value of a key. The involved parts (buyer, seller and first courier service) make the
deposit and the package together with the not hashed key is handed over to the first
courier service.
When the first courier service completes his part of the shipment he does not
immediately handover the package with the key but first the following things
need to happen:
1. The first courier service creates a CS contract which includes also the key
2. Both first and second couriers make the deposit and sign the contract
3. The second courier service confirms that the first courier is arrived. This
confirmation is logged in the ledger and communicated to all the involved
actors in the chain. In this way the second courier service cannot receive the
package and then pretend he had never received it.
After confirmation of arrival, the package and the key are handed over to the second
courier service who calculates the hash of the key and compares it to the value in
the contract.
If the verification is successful the process continues with identical rules until the
package arrives to the buyer.
If the verification fails a dispute is opened and all the escrow are automatically trans-
ferred to the arbitrator who can then redistribute them after off chain verification.
The all process is described in figure 2.15

35
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART

Figure 2.15: Package handover

When the buyer confirms the proper reception of the package, he confirms the
payment(see figure 2.16), which triggers the PoD contract to:

1. Pay and return the escrow to the first courier service

2. Move the remaining funds to its child contract

3. Trigger the child contract to repeat again the steps from 1 to 3 versus the
other courier service (or versus the buyer if there is only one courier service)

Figure 2.16: Payment

36
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE

Testing In the second part of the article testing results are presented showing that
the system behaves as it is supposed to behave.
The security analysis highlights how the systems inherits resistance to some major
security attacks from the use of the blockchain.
A cost analysis is also performed showing that, using the average price of the
Ethereum Gas Station, the successful verification of the delivery has a cost of 0.46$
with one courier service, 0.65$ with two courier services and 0.83$ with three courier
services. So the marginal cost growth for the use of multiple courier services is in
the order of roughly 0.2$

Document conclusions In conclusion the article shows an effective way to im-


plement a Proof of Delivery for physical assets. The use of the key in conjunction
with the escrow represent an mechanisms to foster a correct behavior from all actors.
Moreover the dispute mechanism assure flexibility and off chain arbitration for the
use cases that cannot be covered with a smart contract.

37
2.2. COMMERCIAL LANDSCAPE CHAPTER 2. STATE OF THE ART

2.2 Commercial landscape


In this section we will analyze the commercial context trying to identify, describe
and categorise the existing companies / initiatives in (or close) to the digital library
management landscape.

OCLC OCLC is a global library cooperative that provides shared technology ser-
vices, original research and community programs for its membership and the library
community at large. [1] It hosts WorldCat which is the world’s most comprehensive
database of information about library collections. [1] Currently OCLC is targeting li-
braries rather than private users. Beside this, although OCLC does provide a unique
catalogue showing all the titles belonging to any library under the OCLC consor-
tium, it does not provide the possibility to borrow a book without intermediation
of the specific library owning it.

Goodreads Goodreads is a social cataloging website that allows individuals to


freely search its database of books, annotations, and reviews. Users can sign up
and register books to generate library catalogs and reading lists. They can also cre-
ate their own groups of book suggestions, surveys, polls, blogs, and discussions [2] We
might also say that Goodreads is the analogous of Facebook for the books. It targets
private users but it is currently neither offering any possibility to track ownership
of books nor providing any tool to exchange/sell books.

Google book Google Books is a service from Google Inc. that searches the full
text of books and magazines that Google has scanned, converted to text using optical
character recognition, and stored in its digital database [3] Google books targets
private users and it also allows creation and publication of a private library showing
the books that one owns however it currently does not provide any support to book
exchange.

Demco Demco is company targeting libraries and providing tools to better engage
a library’s community [4] (like tools to promote library events or engage library’s
users with games and challenges). On 2015 Demco has completed the acquisition
of Boopsie, a mobile app to locate the closest library owning a certain book and
they are now trying to develop a solution to build a global MARC based library
catalog on a blockchain platform [5] [6] The platform at today still in beta phase
and we didn’t manage to get further information from the company. Based on a
presentation made at library 2018 blockchain conference [5] looks like focus will stay
on libraries and there is currently no intention to start targeting private users.

Bookchain Bookchain is a brand-new platform bringing a refreshingly flexible way


to publish and distribute ebooks, based on blockchain technology. [7] The aim of
the platform is to create a direct link between publishers and readers by skipping
the publishing company with the goal of lowering the costs and increasing content
availability. They are targeting private users with a focus on only ebooks. Currently
they are not offering tools to support book exchange although having both readers
and authors in the same platform, we think that this might become an interesting
future use case.

38
CHAPTER 2. STATE OF THE ART 2.2. COMMERCIAL LANDSCAPE

Publica Publica is another startup working on a blockchain platform with the


idea of skipping the publishing companies.[8] Same considerations as for Bookchain
are valid.

Orvium Orvium is a platform to connect Connecting researchers and publishers


with trusted reviewers to accelerate publishing along with incentivized peer review.
[9] Also Orvium is built on a blockchain platform with a clear and exclusive target
on the research world.
Table 2.1 summarizes the considerations above, including also LibChain and
Delos DLMS that we have discussed in the past chapter.

Project Status Architecture Domain Target


OCLC GA Centralized Library management Libraries
Goodreads GA Centralized Social network Privates
Google book GA Centralized Content management Privates
Demco beta Decentralized Library management Libraries
Bookchain GA Decentralized Content management Privates
Publica GA Decentralized Content management Privates
Orvium GA Decentralized Research Privates
Delos Prototype Decentralized Library management Libraries
LibChain Prototype Decentralized Library management Privates

Table 2.1: Commercial landscape in summary

in figure 2.17 we provide a graphical classification of the positioning versus the


different commercial domains. To the best of our knowledge, our project has char-
acteristics of functional specificity versus other projects in the digital library area.

Figure 2.17: Commercial domain based classification

39
Chapter 3

Blockchain technology

3.1 Introduction and background


In its original and simplest form, Blockchain is a technology aiming to provide trust,
security and data integrity in a peer to peer network which is inherently opened to
integrity threats.
Although the idea of blockchain has been introduced recently, in 2008, with
the publication of the famous white paper by Nakamoto Bitcoin: A Peer-to-Peer
Electronic Cash System [28], it leverages on a set of technologies that have been
proving their effectiveness for about fifty years which allows to not over increase the
complexity while keeping robustness high.
To start explaining how blockchain works, we will first need to create some
common ground by highlighting some definitions [24]:

• Integrity can be seen as the result of the following factors being accomplished:

– Data integrity which means that data are complete, correct and free of
contradictions
– Behavioural integrity which means that the system behaves as it is
supposed to behave without any logical error
– Security which means that only authorized users are able to access and
use related data and functionalities

• Centralized vs decentralized architecture :

– In a centralized architecture there is one (or more) central component


to which all nodes are (directly or indirectly) connected and which has a
role of somehow coordinating or storing information.
In a centralized architecture when we remove the central component, the
system will not be able to work properly and to maintain its integrity.
– In a decentralized architecture instead, there is no such a central ele-
ment and all nodes are (directly or indirectly) connected with one another.
Without a central element managing the system, coordination, communi-
cation and maintaining the integrity are demanded to the node themselves
which increases the complexity and overhead of the nodes.

40
CHAPTER 3. BLOCKCHAIN 3.1. INTRODUCTION AND BACKGROUND

On the other side when removing one of the nodes in a decentralized


architecture, the system will still be able to work properly which makes
decentralized architectures more resilient , reliable and scalable.
– Peer to peer networks are special type of decentralized systems. They
consist of individual computers (also called nodes), which make their com-
putational resources (ex. processing power, storage capacity, data or net-
work bandwidth) directly available to all other members of the network
without having any central point of coordination. The nodes in the net-
work are equal in terms of rights and roles in the system. Furthermore,
all of them are both suppliers and consumers of resources. [24]

Blockchain has been initially conceived to help providing integrity in a peer to


peer network.
Being decentralized by definition, peer to peer networks are subjected to major
integrity threats that we can split for simplicity into:

• Technical failures: for a variety of technical reasons any of the nodes in


a peer to peer network might temporarily or permanently fail generating an
error or an unexpected result.

• Malicious nodes: any of the node in the peer to peer network might in-
tentionally misbehave in order to gain some personal advantage or to simply
compromise the network functionalities

This results also in a lack of trust between peers because peers are not known
to each other, they might misbehave for the reasons above and there is no central
authority that an guarantee for them. Blockchain comes to the rescue!
Since its beginnings, blockchain has been designed to clarify ownership in a peer to
peer network [28] and, although this might change in the future, clarifying ownership
remains one of the major goals of this technology.

Figure 3.1: Managing ownership

To properly understand this technology, it is then important to point out some


principles about ownership.
In doing so, we will try to highlight some high level concepts that one should keep
in mind while designing a solution to manage ownership. In the next section we will

41
3.1. INTRODUCTION AND BACKGROUND CHAPTER 3. BLOCKCHAIN

then analyze these concepts in greater detail and see how they fit in the blockchain
technology:

• In order to provide ownership we need at least three elements:

– An identification of the owner


– An identification of the object being owned
– A mapping between owner and object

• Ownership involves two inter related aspects:

– Proof of ownership which means being able to determine who is the


owner of a certain object in a certain moment. This essentially requires to
identify owners and properties and then map each owner to his properties
(see Proof of ownership blocks in figure 3.1)
– Use of ownership which means being able to identify and authenticate
a user to confirm if he is the owner of a certain object and then, based on
this, granting access to specific resources or services due to the charac-
teristics or properties of one’s identity [24] (see Use of ownership blocks
in figure 3.1)

• Ownership can be transferred. When this happens the owner of a certain


good will change from the old owner to a new owner.
Transactions are used to keep track of ownership changes and they must
be validated and executed in order to become effective. This means there
must be some kind of transaction proposal and some kind of transaction
approval mechanism.
In its simplest form, a transaction will include at least

– The initial state and the final state (after the ownership transfer) of the
mapping between owner and object.
– A date, to be able to order transactions based on execution time.
– A proof that the transaction has been authorized by the old owner

• In a decentralized network, we cannot assume transactions to be always


correct. In order to maintain integrity, only transactions fulfilling certain
criteria should be executed. In particular transactions should comply with:

– Formal correctness: rules about the way a transaction should be made


(for example as highlighted above a transaction must include the trans-
action date). Transactions not complying with such rules should not be
executed.
– Semantic correctness: depending on the specific application, addi-
tional rules apply (for example in an application for book lending, it
should not be possible to lend a book that had already been lent)
– Authorization: in general, only the owner of the object should have the
right to transfer the ownership.

42
CHAPTER 3. BLOCKCHAIN 3.1. INTRODUCTION AND BACKGROUND

• Full transaction history can be used to prove ownership: as we will


see, proof of ownership can be achieved by taking into account the ownership
triplet described above (old owner, new owner, object) and the history of
the related transactions: knowing the full history of who has owned a certain
object from the moment when the object was created up to now, allows us to
derive who is the current owner of the object without any ambiguity.

• Transaction order counts: it is fundamental to correctly determine own-


ership. If the order is not correct, the resulting history can be inconsistent
resulting in a wrong assessment of the ownership. To explain this point let’s
imagine I have 10 euros and I want to buy a book which costs 15 euros. I
first sell one of my books at 5 euro (transaction 1) so I can then proceed with
buying the 15 euros book (transaction 2). Let’s now imagine to record these
transactions into some kind of electronic ledger: if Transaction 1 comes before
transaction 2 everything will be fine. Should we instead record first transac-
tion 2 and only then transaction 1, in this case I would not have enough funds
to buy the 15 euros book (because I would have only 10 euros) so it would
not be possible to record transaction 2 (without transaction 1 being executed
first). After that, transaction 1 would be executed properly resulting in an
incorrect final state where I have sold one of my books but I have not bought
any.

• A ledger can, in principle, be used to track ownership. The ledger (ei-


ther in electronic or paper form) and the system managing it, should be able
to determine the proof of ownership and the use of ownership aspects without
any ambiguity. When used in a decentralized system the ledger itself
should be decentralized which means each node will have its own copy of
the ledger. To keep consistency, we will then need some kind of (decentral-
ized) coordination mechanism to make sure all the nodes in the system will
ultimately read the same sequence of transactions in their ledger and to make
sure that this sequence would be the right one (reflecting the real sequence of
transactions in the right order).

43
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

3.2 How does blockchain work?


In this section we are going to dive into the way blockchain works, we will try to
explain the basic concepts with a rather high level of abstraction and we will stick
to the initial PoW algorithm initially proposed by Nakamoto [28] before introducing
some of the currently available alternatives. In the next section, instead, we will
go more in details about how a real blockchain solution works, focusing on the
Hyperledger Fabric framework.
In its most basic and primitive form The blockchain is a purely distributed peer-
to-peer system of ledgers using a software unit that consists of an algorithm, which
negotiates the informational content of ordered and connected blocks of data together
with cryptographic and security technologies in order to achieve and maintain its
integrity. [24] To understand in details how it works we will analyze the following
components of a blockchain solution:

• Identification, Authentication and Authorization

• The data structure

• The communication protocol

• The transaction execution

• The consensus mechanism

• Smart contracts

• The different typologies of blockchains

• The consensus mechanisms alternative to PoW

3.2.1 Identification, Authentication and Authorization


Identification, Authentication and Authorization are three integrity aspects of any
system dealing with multiple users.
Identification relates to identify each user in a unique way so that the system,
without necessarily make their identity public, can recognize each user without any
ambiguity.
Authentication relates to making sure that the user is who he claims to be. This
goes beyond the simple identification as it involves proving the identity.
Authorization relates to granting access to specific resources or services due to the
characteristics or properties of one’s identity [24]
In the blockchain Identification, Authentication and Authorization are implemented
by means of public/private key infrastructure: each user is identified by a digi-
tal certificate which includes also the user’s public key and is signed by a certification
authority. Authentication and Authorization are performed by signing the message
with the private key (calculating the digest, encrypting it with the private key and
sending it together with the original message).
Anybody can decrypt the digest and compare it with the digest calculated from the
message to check if they are equal. Because the actual user is the only one who
owns the private key, he can be the only one who signed the message. This, in

44
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

combination with the use of digital certificates ensures also that the counterpart is
who he claims to be.

3.2.2 The data structure


The data structure is the way transaction data is stored in the ledger and it serves
the following purposes:

• Store transactions in an ordered way

• Make extremely difficult to change data which is already written in the ledger.
This point is achieved by means of the following:

– Making any manipulation to the data store stand out.


– Enforcing the need to rewrite the full transaction history if you want to
change any data already written to the ledger.
– Making adding data, computationally expensive.

To understand how all of this is achieved, we need to introduce the concept of hash
pointer, Merkle tree and cryptographic puzzle

A hash pointer (see figure 3.2) is a pointer which is comprised of two parts:

• Pointer to where some information is stored

• Cryptographic hash of that information

The pointer can be used to get the information, the hash can be used to verify that
information has not been changed [10]

Figure 3.2: The Hash Pointer

Whenever we try to change the information, the hash pointer automatically


breaks which means it will no longer possible to retrieve the actual information. So
an hash pointer can be used to understand if the information to which it is pointing
has been modified: if it has, the pointer will be broken and it will be impossible to
read the information from the pointer until when either the data are changed again
(to match the hash inside the pointer) or the pointer itself is modified with the new
hash value of the information to which the pointer is pointing to.

45
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

A Merkle tree (see figure 3.3) is a data structure where different pieces of data are
linked together in a tree structure using hash pointers

Figure 3.3: The Merkle Tree

Whenever any of the piece of data is modified, the ”Top Hash” pointer (also
known as the root of the Merkle tree) will break making all the linked data unreach-
able. The tree structure is very helpful when it comes to assess whether or not a
certain piece of data is part of the Merkle tree. Suppose we want to know if L3 is
part of the Merkle tree in figure 3.3, we just need to calculate the hash of L3 and
then combine it with Hash 1-1, calculate the hash and combine it with Hash 0. We
should then compare the resulting hash with the ”Top Hash”: they will have the
same value so we can conclude that L3 is part of the Merkle tree.
To perform this check, we only need to know the values of Hash 1-1 and Hash 0.
Had we not used a tree structure, we would have need to know all the hashes of
each single piece of data (namely Hash 0-0, Hash 0-1, Hash 1-0, Hash 1-1). When
the number of pieces of data composing the tree grows, the complexity to check if
a piece of data belongs to the tree will grow like O(log n) instead of O(n), so much
slower.
A cryptographic puzzle, in computer science is a kind of challenge which is very
easy to be created and verified but very difficult to be solved. Provided a peace
of data which includes a ”nonce”, whose value is initially unknown, the challenge
requires to understand which is the value that the nonce making the hash of the
data match a specific condition. The stricter the condition the more difficult to
solve the puzzle, for this reason the condition is called ”difficulty level” (see figure
3.4 [24]).

46
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

Figure 3.4: Cryptographic puzzle structure

Hash puzzles can only be solved by trial and error. This requires guessing a
nonce, calculating the hash value of the combined data and evaluating the resulting
hash value versus the specific condition. If the condition is matched, we have solved
the puzzle and the specific nonce value used represents the solution. If the condition
is not matched, we will need to try again with a different nonce value.

Figure 3.5: Cryptographic puzzle example

Figure 3.5 [24] shows a simple cryptographic puzzle example: the puzzle condi-
tion, in this case, requires the hash to present three leading zero. Data is represented
by the string ”Hello World!” which is combined with different possible nonce values.
As you can see in the picture, nonce value 614 solves the puzzle.
Now that we have explained the background ideas, we can introduce the blockchain
data structure which leverages on the concepts introduced above to provide im-
mutability: once transaction data has been written, it becomes extremely difficult
to modify it. At some cost, is still possible to add new transactions but it is very
very difficult to change the transaction history.
Transactions are grouped into blocks, each block basically contains:

• A hash pointer pointing to the root of a Merkle tree, including a number of


transactions.

• A timestamp indicating the transaction date.

• The nonce.

• The difficulty level.

47
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

• A hash pointer to the preceding block.


This generates a chain of blocks (see figure 3.6), all interconnected between each
other, with each block pointing to the specific Merkle tree which includes all the
transactions in the block.

Figure 3.6: Blockchain Data Structure

In order to generate the block, the hash puzzle must be solved which makes
creating blocks computationally expensive. Beside this, whatever modification is
performed to the transaction history, it will immediately break the chain invalidating
the related hash pointers, unless the modification is done by updating all the hash
pointers up to the chain from the point that we want to modify to the end of the
header of the chain. This means re create from scratch a part of the chain which
results in a very computationally high task. Hence the blockchain data structure
while guaranteeing the transactions to be ordered based on time (because of the
timestamp), provides immutability of data already written (because it is extremely
difficult to change transaction history).

3.2.3 The communication protocol


Being completely decentralized, each node in the blockchain will act autonomously
to update and maintain its own copy of the ledger according to a specific consensus
algorithm (that we will see later in this chapter). To do so, is essential that all the
nodes in the network ultimately share the same information, otherwise the
consensus algorithm will never converge.
Provided that not all the nodes are directly connected with each other, a commu-
nication mechanism is needed to make sure that information is propagated along
the network. Such communication mechanism should be robust enough to guarantee
spreading the information despite the unreliability of the network (congestion, loss,
wrong order of arrival etc..) and despite the fact that not all nodes are expected to
be permanently online.
We can split the analysis of the communication protocol in two aspects:
• What is sent: what is the content of the messages being sent.

• How it is sent: in which way messages are sent.


With regards to the content, messages should essentially serve the following pur-
poses [24]:

48
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

• Keeping existing connections alive. Each node maintains a list of its


neighbours, by use of keep alive messages. Such list can be updated in case
neighbours go offline or new neighbours are discovered.

• Establishing new connections. Whenever new neighbors are discovered


they will add each other to the respective neighbours’ list. This works with a
request/reply mechanism where the new node send a request to some of
the existing nodes and ask them to be added to the system. The nodes will
then reply with a confirmation reply, add it to their list of neighbours and
distribute the needed information. Note that a node will normally establish
a connection with more than one peer in order to account for any loss of
connection versus a specific peer (which can always happen because the peer
might go offline, crash etc..)

• Distributing new information. This is normally done in three flavours


[24]:

– In an ongoing fashion: new information are distributed as they occur (for


example when there are new transactions and new blocks)
– As an update: nodes that reconnect to the system, after they were
disconnected for a while, will receive all transaction data and blocks they
have missed out in the meantime
– As part of the on boarding procedure: new nodes, joining the system,
need to get the whole history of transactions that happened up to the time
they joined the system. This can be regarded as a full update (concerning
the full history)

With regards to the way messages are sent a gossip style protocol is used: every
node will forward the information (either new blocks/transactions, update or full
update) to all its neighbours that are currently present in its neighbours table. By
doing this, sooner or later all the nodes in the network should receive the
information.

3.2.4 Adding new transactions


When adding new transactions to the ledger, it is key to make sure that only valid
transactions can be added, discouraging nodes from trying to add invalid transac-
tions. Beside this, creating a new block comes at a cost because it requires solving
the computationally expensive hash puzzle.
In order to ensure that only valid transactions are added to the system, all nodes
of the system are allowed to also act as supervisors of their peers and reward them
for adding valid and authorized transactions and for finding errors in the work of
others. As a result, all nodes of the system have an incentive to process transactions
correctly and to supervise and point out any mistake made by any of its peers.[24]
Let’s see how it works. At any given point in time nodes are busy by either:

• Trying to build a valid block: in order to build a valid block nodes must
solve a cryptographic puzzle which requires basically a trial and error approach.
As soon as a node finds the right nonce value (that makes the hash of the block

49
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

to comply with the specified conditions), it sends the block around to all of
its neighbours.

• Evaluating a new block that was created and submitted by an other node:
evaluation means to check if the block is correct. This implies two types of
checks both keeping into account formal correctness, semantic correctness and
authorization:

– Checking the transaction data: this kind of check has to do with


data inside the transactions in the Merkle tree. Normally these checks
are application dependant.
– Checking the block headers: this kind of checks has to do with the
way blocks are created to generate the data structure described above.

Nodes are rewarded based on a kind of competition game which is split in two steps.
To get the reward a node should win both steps:

• Speed competition: the winner of the speed competition is the node who
manages to build a block in the shortest time possible. Once done, as discussed,
the node will send the block to all of its neighbours which will trigger the
quality competition.

• Quality competition : the quality competition starts as soon as the nodes


receive a new block: if the block is valid, the node who generated it wins the
competition and gets rewarded. However if the block turns out to not be valid
the block is just discarded. All the nodes will then start again with the speed
competition. Naturally the quality competition represents a kind of ”last
chance” for the other nodes to still get rewarded for that set of transactions
by finding a mistake and making the competition to start again. This insures
an high level of accuracy from the nodes verifying the block. It can also
happen that a new block is initially considered valid and added to the ledger
but later on it is discovered to be actually invalid. In this case the invalid block
and all subsequent blocks which had already been added to the ledger are
removed from the ledger and the related transactions are added back to the
inbox. Beside this, the reward is withdrawn from the node who created the
wrong block.

The above schema also guarantees the establishment of a common pace for all the
nodes in the network, as nodes are continuously busy between two states: they are
either trying hard to build the next block or verifying an already created block in
hope to find a mistake. So there is a kind of temporal synchronization between
nodes without using any external clock.
Summarizing: new transaction data are immediately sent around in a gossip
fashion, and collected by each node inside an inbox. Nodes are always busy building
a new block and sending it around, unless there is any block to be validated in
which case they have to switch to validation of the newly arrived block. If block
is considered to be valid, related transactions are removed from the inbox and added
to the ledger, else the block (possibly together will all subsequent blocks that were
meanwhile added on top) is discarded and related transactions are added back to
the inbox. The idea of solving the cryptographic puzzle to generate the blocks

50
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

(in combination with the competition mechanism described above and with the
consensus protocol described in the next section) is called proof of work (PoW).
All the operations above are carried out by each node independently and as a
result each node owns its own copy of the ledger which can be different from the
copy of other nodes due to not all the node having the same exact information at a
given time because of network adversaries.

3.2.5 The consensus mechanism


We have seen that, because of the decentralized architecture, each node will act au-
tonomously from the other nodes and so their copies of the ledger might be different.
Let’s try to better understand this concept: not all the nodes are in visibility, not
all the nodes are necessarily complying with the rules, messages might be received
at very different times (because of network adversaries), synchronization between
building a block vs checking a block is less than perfect and two (or more) nodes
might submit different blocks at the same time.
As a result, a certain node can end up into receiving and adding to the ledger a
certain block that other nodes have not yet received. This in turns yields the ledger
assume the shape of a tree with different branches rather than a chain.

Figure 3.7: Typical structure of the ledger

In figure 3.7 [24] we can see the (simplified) typical structure of a ledger inside
a node. To simplify, only the hash number of the block and the difficulty level have
been indicated inside the block while the arrows indicates the previous block in the
chain.
From the figure we can see that the node owning this version of the ledger has re-
ceived and validated different blocks whose history seems to show a contradiction.
After block A397, some nodes have submitted block DDO1 and other nodes have
submitted block AB12.
After AB12, some nodes have submitted block CCC1 and other nodes have submit-
ted block BB11. Now our node needs to decide which branch of the ledger it wants
to consider as the right one and try to build the next blocks on top of it.
In the specific case, there are three possible alternatives:
1. 0101 – BB11 – AB12 – A397 – 33FF

51
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

2. DD01 – A397 – 33FF

3. CCC1 – AB12 – A397 – 33FF

There are mainly two possible criteria to be used in order to select the right path:

• The longest chain selects the chain which has the highest number of blocks
(in our example chain 1 with 5 blocks)

• The heaviest chain selects the chain with the highest total difficulty (in our
example chain 3 with a total difficulty of 6)

Both criteria tend to select the path where most collective effort has been spent in the
assumption that this will be the right one. The selected path is called authoritative
chain
By selecting the path according to one of the two criteria above, nodes will eventually
converge to the same transaction history, this property of the blockchain is called
eventual consistency.
As a consequence: the deeper down a block is located in the authoritative chain the
more common effort has been spent on it and the more likely it reflects the actual
transaction history.

3.2.6 Smart contracts


When designing transaction based applications, more often than not, a certain de-
gree of automation can strongly help to reduce complexity and side problems while
increasing transparency.
A smart contract is just a piece of code that can interact with the ledger and
automatically generate a transaction every time certain conditions are verified. Nor-
mally smart contracts are used as a way to translate a business agreement into
code and when they are invoked with the right conditions (actors, authorization,
availability of funds etc..) they just enforce the business contract by executing it
and registering it in the ledger.
Figure 3.8 shows an example of smart contract enforcing the contract for the selling
of a car between two different organizations.

Figure 3.8: An example of smart contract

While smart contracts represent a great way to develop a logic on blockchain,


making the technology suitable to serve many real use cases, managing smart

52
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

contracts is a critical factor because the smart contract code interacts directly
with the ledger and can influence the transaction history in unwanted ways. Any
weakness in the code or in the way it is executed represent a potential target for
malicious users who want to exploit the system.
To guarantee consistency and integrity, execution of smart contracts is subjected
to the same consensus algorithm as the blocks. We will analyze this aspect in
greater detail in the next section.

3.2.7 Classification of blockchains


The first and more prominent application of blockchain technology has been Bitcoin.
To serve the needs of this specific application the system has been designed in such
a way that:
• Anybody could read any data from the ledger
• Anybody with a wallet and sufficient funds can generate new transactions
writing into the ledger
• Although users have an identity (a digital certificate including their public
key) no personal data are inserted into the system and so transaction’s parties
are anonymous.
After the success of Bitcoin, many attempts have been made in order to use the
blockchain technology to bring value in contexts other than cryptocurrencies. How-
ever there are use cases where the requirement of restricting the access only to
certain actors and being able to identify users with their personal data is a must
have. For this reason different blockchain solutions have been created, allowing a
greater flexibility on read/write permissions.

Figure 3.9: Classification of Blockchain solutions

Figure 3.9 shows one way to classify different blockchains solutions based on the
permissions for reading and writing. As we can see the Bitcoin application and

53
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN

Ethereum framework are public permissionless meaning that anybody can access
the system to read the ledger or to write into the ledger (provided compliance with
the rules specified by the application itself).
On the other side we have Hyperledger Fabric and Corda which are private per-
missioned, meaning that both access to data in the ledger and ability to modify
the ledger are restricted.
Alternative options are public permissioned (anybody can read data but writing
is restricted) or private permissionless ( reading is restricted but anybody can
write to the ledger, this option is less used)
In the next section we will talk in details about the Hyperledger Fabric solution.

3.2.8 Alternative consensus mechanisms


As we have seen, the proof of work algorithm is based on making it difficult to add
new transactions (as part of the immutability property) and a mechanism of reward
and punishment which is meant to generate a compensation for the nodes who are
contributing to write the ledger and a penalty for the nodes who are misbehaving.
However the proof of work algorithm comes with limitations:

• Because nodes with highest computational capacity tend to be rewarded most,


miners tend to be located in countries where energy is cheaper. Beside this,
only large organizations are able to effectively competing to make a steady
income out of mining activities. This creates a consolidation effect that
represents an element of centralization.

• With increasing consolidation, large data centers are used for mining and they
consume lot of energy. From an environmental point of view this is a waste to
be possibly avoided.

• PoW requires time to mine blocks, which makes the average transaction per
second quite low, limiting the scalability for applications where high number
of transactions per second is a must (ex. credit card transactions).

For the above reasons, alternative consensus mechanisms have been introduced
in attempt to mitigate the above problems. However the main idea remains, to make
adding new transactions difficult, based on scarcity of a certain resource which
is needed to be able to add new transactions.
Below we recap the most important alternative algorithm: [11]:

• Proof of stakes requires that a miner locks up some of the amount of their
coins to verify their blocks of transactions. In other words, you are only
required to verify (and stake) a certain percentage of the coins available in a
given currency in order to verify a block of transactions. For instance, you are
allowed to mine 2 percent of all transactions across Ethereum if you own 2
percent of all Ether. This method does not create a waste of energy to mine,
but still creates a consolidation effect versus the miners who own most of the
resources.

• Proof of elapsed time: to take part in a blockchain utilizing this mechanism,


users have to identify themselves to the network and prove that they are

54
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?

running a SGX, which is an Intel proprietary code running inside Intel CPUs.
In order to be eligible to validate a block, each computer takes part in a lottery-
style scheme where an internal randomized timer system assigns a random
timer to each participating computer. The first timer to wake up then gets
the right to validate the next block. The downside of this method is that it
is limited to Intel chipset and based on Intel proprietary technology which
represents an element of centralization.

• Proof of capacity: instead of actively mine during the validation process,


all the mining is done in advance and only once. This process is called plot-
ting and it works as follows: the mining is done on a hard drive in advance
and creates unique plot files. Compared to Bitcoin’s PoW, this mining is also
requiring more computational power, due to the use the Shabal hashing algo-
rithm but opposite to PoW this is done just once, so it is way more efficient.
Once these plot files have been generated, the software calculates a so-called
scoop number representing a kind of timer which refers to the amount of time
that has to pass since the last block before you can create a new one. Therefore
the hard drive that has the shortest “deadline” in the network gets to create
a new block and receives the financial reward.

• Proof of burn: burning coins is a terminology that refers to making coins


unusable. The basic idea of Proof of Burn is to create a “virtual mining rig”,
where the coins that are being burned represent an investment into those.
The more coins are burned, the bigger the virtual mining rig and therefore
the higher the chance of being selected as a block validator. In the context of
this consensus mechanism, the coins need to be send to a verifiable address,
also known as “eater address” — these are randomly generated addresses with
no associated private key. By creating a short term loss for a long term in-
vestment, the idea is to promote a long lasting involvement of the users. This
is supposed to lead to a greater price stability. On the other side there is a
similar downside to the PoS with a consolidation effect versus users owning
more coins.

• Proof of authority: this idea works by limiting the right to validate blocks
to a group of pre-approved participants. In order to be part of this group of
validators, the identities of the validators need to be formally identified on-
chain, as well as off-chain (for example through a public database) and there is
a rigorous process. Should validators act in a malicious way, they can be easily
removed through a governance process. PoA is used mainly in permissioned
blockchains and has the downside of introducing an element of centralization
in the group of validators.

55
3.3. HYPERLEDGER FABRIC CHAPTER 3. BLOCKCHAIN

3.3 Hyperledger Fabric


Hyperledger Fabric is an open source enterprise-grade permissioned distributed ledger
technology (DLT) platform, designed for use in enterprise contexts, that delivers
some key differentiating capabilities over other popular distributed ledger or blockchain
platforms. [12]
In the remainder of this section we will go in the details of the way Hyperledger
Fabric works and its architecture.

3.3.1 Overview and business requirements


Being designed for enterprise use, Hyperledger Fabric has been thought with the
following requirements in mind:

• Participants must be not only identified but also identifiable.

• Restricted reading /writing access to the ledger is required, so we need a


private permissioned blockchain.

• High transaction rate is required, so we need an alternative mechanism to the


traditional PoW and ability to scale.

• Privacy and confidentiality about business transactions are required, so we


need mechanisms for users to selectively access part of the information in the
ledger

Some of the relevant features of Hyperledger Fabric are:

• Modular architecture allowing an high degree of configuration versus:

– Consensus protocol
– Identity management protocols
– Cryptographic libraries
– Database management system

• Private, permissioned blockchain restricting access to the ledger both for read-
ing and writing operations.

• Implement an Execute-Order-Validate approach to eliminate non determinism.

• Due to removal of non determinism, standard programming languages can be


used to write the smart contracts.

• Channel architecture and private data to enforce privacy.

3.3.2 The network


At high level Fabric is made by the following components:

56
CHAPTER 3. BLOCKCHAIN 3.3. HYPERLEDGER FABRIC

• The ordering service is the first node being created when setting up the net-
work. It can be considered as an administration point which provides different
organizations controlled access to the network. [12] It also has a fundamental
role in the transaction request / transaction response mechanism as it imple-
ments the ”order” part of the Execute-Order-Validate approach.

• The Certification authority has the role to certify user’s identities (X.509
digital certificates are used to identify users), Fabric provides a built in CA
that can be used while building the network, before going in production, or
for use cases where an external CA is not needed. Alternatively an external
CA can be used.

• The Membership Service Provider (MSP) has the role to match identities
with roles inside an organization defining what a certain user is entitled to do
or not do.

• The Network configuration defines policies to grant actors specific rights


over network resources.

• The Peers are all the regular nodes participating in the blockchain network.
As we will see they belong to organizations.

• The Organizations represent real business organizations with their users,


their roles, their policies, their resources.

• The Channels are logical ways to segment communication between peers


making sure peers from different channels cannot talk to each other.

• The Chaincodes are entities allowing direct access to the ledger and they can
include one or more Smart Contracts.

• The Ledger is the entity where all transactions are written, normally there is
one ledger per node and to improve performances it is split into a world state
database storing the current state of the system and the actual ledger storing
the full transaction history.

• The Application is the entity which allows end users to interact with the
system by interrogating the peers and presenting the received data to the
user.

3.3.3 Identity and Membership service


Identities are assigned by means of X.509 digital certificates and they determine
the exact permissions over resources and access to information that actors have in
a blockchain network. [12] Fabric also defines the concept of principal which is
the union of the digital identity and some associated attributes that are used to
determine permissions in a more granular way.
On the other side we have the Membership Service Provider which provides the
information about:

57
3.3. HYPERLEDGER FABRIC CHAPTER 3. BLOCKCHAIN

• Whether or not a certain certification authority is trusted to define the


members of an organization. A certification authority, in fact, provides
an identification service by signing the digital certificate. However, not all the
certification authorities are trusted to define what are the members of a certain
organization as this goes beyond the typical responsibility of a certification
authority.

• The specific role a certain identity has inside an organization which maps the
attributes associated to the principal into a role.

Normally each organization has at least an MSP associated with it. We need to
distinguish between:

• Network MSP defined for the entire network. The configuration of a network
defines who are the members in the network — by defining the MSPs of the
participant organizations — as well as which of these members are authorized
to perform administrative tasks (e.g., creating a channel). [12]

• Local MSP defined for end users and peers. Node (including also the ordering
service node) local MSP defines the roles inside that node (for example if an
identity is an admin for that node). Users local MSP defines the role of the user
as member of a certain channel or as owner of a specific role into the system
(ex system admin). Every node and end user must have an MSP defined.

• Channel MPS defined for the channels. Channel MSPs define administrative
and participatory rights at the channel level [12] Logically there is only one
channel MSP however physically there is a copy of the channel MSP at each
node in the channel. This copy is updated via the consensus mechanism.

3.3.4 Peers and ordering service


Peers are important because they host the ledger and the chaincode.
Both the ledger and the chaincode are logically a single entity but practically each
peer hosts a copy of the ledger and a copy of the chaincode and updates them based
on the consensus mechanism.
In more complex systems, peers can host also more that one ledger and more than
one chaincode. Peers also work as ”access point” for the applications into the system
and they implement the logic for the Execute-Order-Validate approach that we are
going to explain below.
In figure 3.10 we can see an application which interacts with a peer and an orderer
(which is a special peer implementing the ordering service). The orderer interacts
with the peer and, on the peer, we have one chaincode and one ledger.
The dotted arrows are representative for a scenario where a modification of the
ledger is needed but not for the scenario where the ledger is simply queried. The
continuous arrows instead are representative for both scenarios.

58
CHAPTER 3. BLOCKCHAIN 3.3. HYPERLEDGER FABRIC

Figure 3.10: Execute Order Validate approach and interaction between peer and
application

When the application wants to make a request, it will contact the peer. After
the application connects to peer, it will invoke the chaincode (which includes one or
more smart contracts allowing some actions to the ledger):

• If the request is a query, the peer will in turn invoke the chaincode who will
run the query and return the results to the peer. At this point the peer can
generate a proposal response including the query results.

• If the request is a new transaction, the peer will in turn invoke the chaincode
who will try to first execute the transaction, determine the results and add
them in the proposal response that the peer will send back to the application.
Note that, in this phase, the ledger is not yet modified with the obtained
results.
The application will then group this proposal response with other proposal
responses that it might have received from other peers (the application needs
to collect a minimum number of proposal responses by peers in the network,
this minimum number depends on the policy defined for the network. In the
simplest case it can be just one. The peers providing the responses are called
endorsing peers) and builds a transaction, it will then send the transaction
to the orderer peer asking it to order.
The orderer peer receives many transactions from different applications. It
first checks them for validity, making sure the transaction includes a number
of responses equal to at least the minimum value requested by the network
policy, it also checks if the transaction is properly signed by the application
and if the responses inside it are properly signed by the peers. Finally it orders
the transactions based on the timestamp and organize them into blocks.
Blocks are then sent back to the peers (arrow 4.1) to update the ledger, however
before applying the results (calculated in the previous step) to the ledger, the
peers must execute a sanity check to make sure the state of the ledger has not
changed meanwhile. After that they can finally modify the ledger. This phase
is called validation

Execute-Order-Validate is a different approach from the Order-Execute which is


used in traditional blockchain solutions. The reason to adopt such approach is to
eliminate non determinism.

59
3.3. HYPERLEDGER FABRIC CHAPTER 3. BLOCKCHAIN

Non determinism happens when having the same inputs, a call to a function can
produce different outputs (for example depending on some external conditions). In
traditional blockchain solutions, non determinism is avoided by using proprietary
languages to write the smart contracts with the downside that developers have to
learn yet another language. This represents a barrier to the adoption of the product.
With Hyperledger Fabric non determinism is avoided by adopting the Execute-
Order-Validate approach allowing to write smart contracts with traditional pro-
gramming languages.
Another important aspect regarding peers is how do they relate versus the channel.
Channels allow a specific set of peers and applications to communicate with each
other within a blockchain network. [12] so they are logical entities allowing the com-
munication between applications and peers. Peers and applications that are
not on the same channel cannot communicate between them.
Peers also provide a control point to access and manage a channel.

Figure 3.11: Example of a network configuration with two channels

In figure 3.11 we can see a network which is configured with four organizations
R1, R2,R3 and R4 (indicated with the following colors: lilac, grey, yellow and green)
and two channels (indicated with the following colors: blue and red). Applications
are indicated with letter ’A’ inside the block, certification authorities with ’CA’,
ledgers with ’L’, chaincodes with ’S’, network configuration with ’NC’, channel con-
figuration with ’CC’ and orderer node with ’O’.
As we can see A1, A2, P2 and O4 despite belonging to different organizations
can communicate between each other being all on channel 1. On the other side A2,
A3, P2, P3 and O4 are on channel 2 and they can communicate between each other
but they cannot communicate with the entities in channel 2 (except A2 P2 and O4
which belongs to both channels)

3.3.5 Smart contracts and chaincodes


A smart contract is code that can access, query and modify the ledger.
Hyperledger makes a distinction between the functional aspect of the smart con-
tracts (the logic defining what will happen when a certain smart contracts is called)
from the operational aspect (installing and instantiating the logic on the channel
where it is supposed to live). There is a separated entity to perform this second

60
CHAPTER 3. BLOCKCHAIN 3.3. HYPERLEDGER FABRIC

aspect and this entity is called chaincode.


A chaincode normally will include multiple smart contract and it has to do with the
way smart contracts are put together to be instantiated in a channel. A chaincode
is then something that is normally managed by the system administrators whereas
a smart contract is just functional code which is normally managed by developers.
Associated with every chaincode there is an endorsement policy that applies to
all of the smart contracts defined within it.
An endorsement policy indicates which organizations in a blockchain network must
sign a transaction generated by a given smart contract in order for that transaction
to be declared valid. [12]
Endorsement policies represent a relevant difference between Hyperledger Fabric
and other blockchains like Ethereum or Bitcoin. In these systems valid transactions
can be generated by any node in the network. However Hyperledger Fabric more
realistically models the real world; transactions must be validated by trusted or-
ganizations in a network. For example, both the buyer and seller of a car must sign
a car transfer transaction. Endorsement policies are designed to allow Hyperledger
Fabric to better model these types of real-world interactions.
Finally, endorsement policies are just one example of policy in Hyperledger Fabric.
Other policies can be defined to identify who can query or update the ledger, or
add or remove participants from the network. In general, policies should be agreed
in advance by the consortium of organizations in a blockchain network, although
they are not set in stone. Indeed, policies themselves can define the rules by which
they can be changed. And although an advanced topic, it is also possible to define
custom endorsement policy rules over and above those provided by Fabric.

3.3.6 Ledger
For efficiency reasons the ledger, whose scope is to keep track of the transaction
history, is implemented with two distinct instances:

• On one side there is the world state which is a database holding a the
current values resulting from the last transaction.
The world state makes it easy for a program to directly access the current value,
rather than calculating it by analyzing the full transaction history. The world
state is meant to change frequently, as results of new transactions modifying
the state of the ledger. There are mainly two options to implement the world
state database:

– LevelDB is a particularly appropriate choice when ledger states are sim-


ple key-value pairs.
– CouchDB is a particularly appropriate choice when ledger states are
structured as JSON documents because CouchDB supports the rich queries
and update of richer data types often found in business transactions.

• On the other side there is the blockchain which records all the transaction
history resulting in the current the world state.
Transactions are collected inside blocks that are appended to the blockchain.
The blockchain data structure is similar to the typical blockchain structure
described in the previous section and makes the blockchain immutable. For

61
3.3. HYPERLEDGER FABRIC CHAPTER 3. BLOCKCHAIN

efficiency and architectural reasons the blockchain is always implemented as a


file, opposite to the world state, which is implemented as a database.

Figure 3.12: Blockchain data structure

In figure 3.12 we can see how the Hyperledger blockchain data structure is orga-
nized. As expected each block points back to the previous block. The block itself is
divided in three parts:

• Block header which basically includes the block number, the hash of the
current block and the hash of the previous block (see figure 3.13)

Figure 3.13: Block header structure

• Block data: the block data content reflects the Execute-Order-Validate ap-
proach. As we can see in figure 3.14 it is basically composed by:

– Header including mainly the name of the chaincode, and its version.
– Signature which is the signature of the application
– Proposal including the input parameters supplied by an application to
the smart contract in the proposal request
– Response including the before and after values of the world state. If
the transaction is successfully validated the after values will be applied
to the ledger (both to the world state and the blockchain)
– Endorsements this is a list of signed transaction responses from each
endorsing peer. Whereas only one transaction response is included in

62
CHAPTER 3. BLOCKCHAIN 3.3. HYPERLEDGER FABRIC

the transaction, there are multiple endorsements. That’s because each


endorsement effectively encodes its organization’s particular transaction
response meaning that there’s no need to include any transaction response
that doesn’t match sufficient endorsements as it will be rejected as invalid,
and not update the world state. [12]

Figure 3.14: Block data structure

• Block metadata which includes a timestamp to indicate when the block was
created together with the certificate, public key and signature of the orderer
node.

63
Chapter 4

Bookswapy: design and


implementation

In this chapter we will travel through the steps followed in the design and imple-
mentation of our project. In doing so we will try to explain the reasons for our
architectural choices, highlight the criticalities encountered in the design and devel-
opment phase as well as the tools used.

64
CHAPTER 4. IMPLEMENTATION 4.1. THE INTERACTIVE DESIGN

4.1 The interactive design


Our journey in the design of Bookswapy started with the analysis of the require-
ments introduced in the first chapter to define how the user should interact with the
application.
We decided to go for a simple web application and tried to map the requirements
into some kind of flow, defining how the user would interact with the system. As
a result we have sketched the pages to be designed and the related flow, producing
twenty-three pages which completely describe the interactive user experience.
In the remainder of this section we will try to summarize our results while the com-
plete work is visible in the appendix.
Being a multi user application, we have included login and sign-up pages. Once the
user logs in, he will be redirected to the home page from where he should be able
to access all the main functionalities

Figure 4.1: Home page

as we can see in figure 4.1 the home page exposes the following functionalities:

• Search a book, with search results appearing in the same page.

• Add a new book

• View the user’s books

• View the lendings/swaps

• View the messages

• View the balance

• View the account configuration

• Logout

We have decided to include the functionality of book modification and book


deletion inside the list of the user’s book in the ”My Books page” displayed below:

65
4.1. THE INTERACTIVE DESIGN CHAPTER 4. IMPLEMENTATION

Figure 4.2: User’s book page

Modification is offered by adding a button ”Edit” close to each row, while deletion
is offered through a multiple checkbox selection with a unique ”Delete” button to
allow multiple deletion.
In the MySwaps page users can visualize the list of books that are lent or borrowed.
As show in figure 4.3 we decided to organize this page with some filters that can be
activated through the buttons on the left side of the page.

Figure 4.3: Swaps page

In the bottom part of the page we expose other two important functionalities:

• The possibility to open a dispute. Since the dispute can only be opened for a
book which is lent or borrowed, it makes sense to add this feature here.

• The possibility to return a book

One critical point faced during the interactive design study, was the need to
define some kind of protocol related to certain operations. For example when a user
searches for a book and finds it, he cannot just borrow it straight away. Instead there
must be first some kind of confirmation by the counterpart. Our choice has been to
incorporate such protocol into fixed messages been sent automatically between the
users when certain actions are performed. For example, in the specific case, makes
sense to think about some kind of handshake where:

66
CHAPTER 4. IMPLEMENTATION 4.1. THE INTERACTIVE DESIGN

1. The borrower asks to borrow a certain book

Figure 4.4: New request message received by the lender

2. The lender gets notified (See figure 4.4) and can either refuse straight away or
confirm while at the same time proposing a value for escrow and the arbitrator
name.

Figure 4.5: Request accepted message received by the lender

3. The borrower can then refuse the proposal or accept it (see figure 4.5). If
accepted, the book is considered as lent and a transaction should be executed
to change the status of the book in the ledger. The lender will also get a
confirmation (see figure 4.6)

67
4.1. THE INTERACTIVE DESIGN CHAPTER 4. IMPLEMENTATION

Figure 4.6: Acceptance confirmed message received by the borrower

A similar approach has been applied to the procedures of returning a book and
opening/closing a dispute. (See appendix for the details)

68
CHAPTER 4. IMPLEMENTATION 4.2. THE TOOLS

4.2 The tools


Before starting with the actual development, we have looked at the available options
in terms of tools.

• Hyperleger Fabric exposes its own API, however, as a starting point, we were
looking for some kind of framework that could make our job easier.

• Composer has been our primarily choice. It provides an abstraction level to


developers and allows to organize the network by distinguishing:

– Model
– Functions
– Policies

In this way developers can basically work with the model file to define ac-
tors and assets, then create javascript functions in a dedicated .js file
and optionally specifying some policies (which participant can access which
resources) in a .acl dedicated file. This represents an option to easily create
our smart contracts without dealing with the complexity of the lower layer
Fabric API.
On the other side, on Composer, simplicity of use comes at a cost: complexity
in the implementation of the tool itself and growing difficulty into keeping it
aligned with new Fabric development. In fact already on August 2018, the
Composer team had communicated the intention of not developing any new
feature on the project [13] and rumors of an imminent deprecation of the prod-
uct (which then happened end of August 2019) were becoming stronger. We
then decided to not continue with Composer and started looking for something
else.

• Convector is a suite of brand new tools (released first time beginning 2019)
which was conceived with the same idea of Composer (create a level of ab-
straction to simplify the work for smart contracts developers) but whose ar-
chitecture keeps into account the lessons learned from the Composer failure.
The result is an architecture which is very close to Fabric and provides the
flexibility to configure the blockchain for a variety of different scenarios from
fast prototyping to a scaled proof solution.
Another strength of Convector is its software community. Although, at the
time of writing, likely less than ten people are actively contributing to it, they
are very engaged, they believe in what they are doing and they are normally
very responsive.
Finally Convector is used in such a way to become, in the near future, blockchain
solution independent, so people will be soon able to use it on Fabric as well as
on Ethereum or other blockchain solutions.

So we decided to give it a try and started to use it. Let’s see more in details how is
it made. Convector is a suite composed by the following tools [14]:

• Convector Smart Contracts a Javascript development framework for smart


contracts.

69
4.2. THE TOOLS CHAPTER 4. IMPLEMENTATION

• Hurley: a development end to end environment implementing the back-end


(statically configurable) and mimicking a client application.
• Convector CLI a CLI, integrated with Hurley, allowing to easily build a new
project.
• Convector REST Server a RESTful API generator which allows you to set
up an API server and bring it up with just a couple of commands.

4.2.1 Convector Smart Contracts


Convector runs natively in Hyperledger Fabric [15] so developers don’t have to
think about managing the complexities of communicating with Fabric directly, but
still running a native Node JS chaincode on it.
One of the key elements of Convector Smart Contracts framework is to use type-
script allowing mainly the possibility to define:
• Decorators are special properties allowing better control of our code. They
can be recognized as they start with @. For example in the snippet below
@Invocable() and @Param are both decorators. The first makes sure the func-
tion can be called when sending a transaction to the blockchain, the latter
validates the id parameter as a string.
• Types: as we know in Javascript the arguments of a function do not come with
their specific type. It’s a responsibility of the developer to call the function
using the right parameters type. This can lead to mistakes, runtime errors
and a lack of clarity in the code. Typescript extends Javascript by allowing
explicit use of types in the arguments of the function. In the example below
the function get will only accept a string for the parameter id :
@Invokable()
public async get(
@Param(yup.string())
id: string
) {
const existing = await Participant.getOne(id);
if (!existing || !existing.id) {
throw new Error(‘No identity exists with that ID ${id}‘);
}
return existing;
}

Another fundamental aspect of Convector Smart contract is that its architec-


ture follows a Model-Controller pattern. This pattern should be also used when
writing our own smart contracts: we will always define a model where we mainly
specify the assets or the actors with their properties and a controller where we
specify the corresponding behavior. Convector core is organized around two classes
having a specular structure as they include the necessary code to create respectively
our models and our controllers:
• convector-core-mode

70
CHAPTER 4. IMPLEMENTATION 4.2. THE TOOLS

• convector-core-controller

The core controller is very simple with only two parameters being defined:

export abstract class ConvectorController<T=any> {


protected sender: string;
protected tx: T;
}

• The sender which identifies the user invoking the controller function.

• The tx which identifies the transaction

The core model instead exposes some useful utility methods like:

• getOne which returns one model fetched by by its id.

• query which is used to query the storage layer.

• getAll which returns all the model of a certain type.

• update which given one model loaded into the instance, updates its content
with the object passed to the update method.

• fetch which retrieves the model from the storage.

• clone which makes a copy of a model.

The last, but maybe most important, aspect of Convector is that in its archi-
tecture models and controllers are decoupled from the actual implementation
layer that talks with the underlying layer (being for example a storage layer or
Fabric SDK).
In order to do that, adapters are used. Each adapter has its own internal logic, the
FabricControllerAdapter for instance, handles the network profile for communica-
tion with Fabric, but Convector is not tightly coupled with Fabric, so the community
can create different adapters based on their needs. [15]
In this way the model and the logic written with Convector can potentially be
extended to blockchain solutions other than Fabric by using a specific adapter.

4.2.2 Hurley
Hurley is a simple and yet powerful development tool to quickly create a blockchain
infrastructure. It must be used via CLI and it mainly provides the following com-
mands:

• hurl new which creates a new blockchain network. Through the arguments
it is possible to specify mainly:

– The path to the network configuration file: [-n –network <path>]


– The number of organizations in the network: [-o –organizations <amount-
of-organizations>]

71
4.2. THE TOOLS CHAPTER 4. IMPLEMENTATION

– The number of fabric certificates in the network [-u –users <users-per-


organization>]
– The number of channels in the network [-c –channels <amount-of-channels>]

• hurl install <chaincode> which installs and instantiates the chaincode into
our nodes. Below the main arguments:

– The organization: [-o –org <organization>]


– The channel on which to install the chaincode: [-C –channel <channel>]
– The path to the chaincode package: [-P –chaincode-path <path>]
– Start the chaincode in debug mode [-d –debug]

• hurl invoke <chaincode><function to be called>[args of the func-


tion to be called...] which emulates a client request by calling a certain
method of the chaincode. A part the arguments of the called function, the
most important arguments are:

– The organization: [-o –org <organization>]


– The channel: [-C –channel <channel>]

4.2.3 Convector CLI


The Convector CLI is used mainly to:

• Generate a skeleton of the project with the command conv new <ProjectName>-
c <chaincodeName>. Once done, a predefined structure is created inside a
new folder called <ProjectName>. This structure includes also:

– The packages folder where we can find the src folder with the model and
controller default files related to our chaincode.
– A package.json to manage dependencies via npm
– A .json file including the configuration of the network

• Add one/more additional chaincodes through the command conv generate


chaincode <additionalChaincodeName>. This command will generate an addi-
tional folder with the file structure related to the new chaincode under packages
folder described above

4.2.4 Convector REST Server


Finally the Convector REST Server generates and instantiate a REST API server
allowing a client to call the invokable methods of the chaincodes, via the REST API
server.
Once defined the code inside the chaincodes, setting up the server is straightforward:

1. First thing to do is to generate a file called api.json which basically describes


our methods by indicating the function name, the verb and the controller
file. Below an extract of the api.json of bookswapy:

72
CHAPTER 4. IMPLEMENTATION 4.2. THE TOOLS

...
{
"function": "updateBalance",
"verb": "post",
"controller": "ParticipantController"
},
{
"function": "get",
"verb": "get",
"controller": "ParticipantController"
},
{
"function": "createBook",
"verb": "post",
"controller": "LendingController"
},
{
"function": "updateBook",
"verb": "post",
"controller": "LendingController"
},
...

2. Second step is to launch the Convector REST server generator from the same
folder where the api.json file is located, with the command:
conv-rest-api generate api -c <chaincode> -f <path of
the network configuration json file>

3. We then need to compile using the command


npx lerna bootstrap

4. Finally we need to launch the REST server with the command:


npx lerna run start --scope server --stream

After running this last command, a process will be listening on localhost:8000


and it will be possible to use our preferred client to call the API.

73
4.3. SMART CONTRACTS CHAPTER 4. IMPLEMENTATION

4.3 Smart contracts


After having studied and experimented with the Convector tools we have started the
actual development of our smart contracts. Our first concern was how to architecture
the solution. We decided to create two chaincodes:

• A chaincode called lending which includes assets and logic related to the func-
tionalities of the virtual library system.

• A chaincode called participant which includes model and logic related to user
identification and authentication.

• We have then created an additional package called Administrative where we


put any utility which is common to the two chaincodes above.

Figure 4.7 shows the resulting structure of the packages folder.

Figure 4.7: Structure of the packages folder inside the Bookswapy project

4.3.1 The lending chaincode


Lending chaincode defines all the aspects related to the management and exchange
of books between users.
The model file defines two objects:

• The book which refers to the book asset with all its metadata.

• The transaction which refers to the many exchanges that can be done on
each book.

Let’s analyze each of them more in details by looking at the actual code:
The book asset includes some classical book’s metadata (title, author etc..) to-
gether with the ownerId and the borrowerId which are the id respectively of the
book’s owner and the book’s borrower (when the book is lent). Finally the book
asset includes a status property which reflects the current status of the book (lent,
available, dispute etc..)

74
CHAPTER 4. IMPLEMENTATION 4.3. SMART CONTRACTS

export class Book extends ConvectorModel<Book> {


@ReadOnly()
@Required()
public readonly type = ’io.worldsibu.lending’;

// Book (asset) definition


@Required()
@Validate(yup.string())
public isbn: string;
@Validate(yup.string())
public status: string;
@Validate(yup.string())
public title: string;
@Validate(yup.string())
public author: string;
@Validate(yup.string())
public publisher: string;
@Validate(yup.string())
public genre: string;
@Validate(yup.string())
public year: string;
@Validate(yup.string())
public ownerId: string;
@Validate(yup.string().nullable())
public borrowerId: string;
}
The transaction id, includes all data related to the transaction (like date, deadline,
escrow, etc..)
export class Transaction extends ConvectorModel<Transaction> {
@ReadOnly()
@Required()
public readonly type = ’io.worldsibu.lending’;

// Transaction (asset) definition


@Required()
@Validate(yup.string())
public id: string;
@Validate(yup.number())
public escrow: number;
@Validate(yup.string())
public arbitrator: string;
@Validate(yup.date())
public date: Date;
@Validate(yup.string())
public isbn: string;
@Validate(yup.date())
public deadline: Date;}

75
4.3. SMART CONTRACTS CHAPTER 4. IMPLEMENTATION

The controller file instead, defines a number of methods. At the time of writing, the
following methods have already been defined:

• CreateBook creates a new book by taking as parameters the book’s metadata


and basically assigning them to the respective properties of a new book object
@Invokable()
public async createBook(
@Param(yup.string())
ownerId: string,
@Param(yup.string())
isbn: string,
@Param(yup.string())
title: string,
@Param(yup.string())
author: string,
@Param(yup.string())
publisher: string,
@Param(yup.string())
genre: string,
@Param(yup.string())
year: string,
) {
...

let book = new Book(isbn);


book.id = isbn;
book.status = bookStatusEnum.AVAILABLE;
book.isbn=isbn;
book.title = title;
book.author = author;
book.publisher = publisher;
book.genre=genre;
book.year = year;
book.ownerId = ownerId;
book.borrowerId=null;
await book.save();
}

• UpdateBook updates the book’s metadata. The method is similar to the


create method, except for the fact that, before modification, the book to be
updated is fetched based on the id passed as parameter using the method
getOne inherited by the core-controller.
@Invokable()
public async updateBook(
@Param(yup.string())
isbn: string,

76
CHAPTER 4. IMPLEMENTATION 4.3. SMART CONTRACTS

@Param(yup.string())
title: string,
@Param(yup.string())
author: string,
@Param(yup.string())
publisher: string,
@Param(yup.string())
genre: string,
@Param(yup.string())
year: string,
) {
let book = await Book.getOne(isbn);

...

book.isbn=isbn;
book.title = title;
book.author=author;
}

• deleteBook Deletes the book. Naturally, by definition, nothing can be deleted


from the blockchain so what this method does is to change the status of the
book marking it as deleted.

• lendBook Allows a user to lend a book. At its core, the method updates
the status and the borrowerId, creates a new transaction and writes it to the
ledger:
@Invokable()
public async lendBook(
@Param(yup.string())
isbn: string,
@Param(yup.string())
borrowerId: string,
@Param(yup.string())
arbitrator: string,
@Param(yup.number())
escrow: number,
@Param(yup.number())
lendingDuration: number,
){
...

book.borrowerId = borrowerId;
book.status = bookStatusEnum.LENT;
await book.save();
let transaction= new Transaction(book.id);
transaction.date=new Date();
transaction.id="t" + book.id + transaction.date;

77
4.3. SMART CONTRACTS CHAPTER 4. IMPLEMENTATION

transaction.date.getDate;
transaction.arbitrator=arbitrator;
transaction.escrow=escrow;
transaction.isbn=isbn;
transaction.deadline=new Date(transaction.date.setMonth(
transaction.date.getMonth()+ lendingDuration));
await transaction.save();

• returnBook Allows a user to return a book basically at its core it is similar to


the lendBook updating the status (AVAILABLE) and setting the borrowerId
to null. Note that no transaction is created in this case, as the transaction
will be created only when the lender will confirm the book has been returned.
...
book.borrowerId = null;
book.status = bookStatusEnum.AVAILABLE;
await book.save();
...

• getBook Allows to retrieve a book based on the book id.

• getAllBooks Allows to retrieve all books from all users

• getParticipantBooks Allows to retrieve all books of a certain participant.

4.3.2 The participant chaincode


The participant chaincode should define all the aspects related to user registration
and authentication.
The participant model file defines two assets:
• Participant

• Public certificate
In the participant, besides the data of the user we have its certificate and the
msp:
export class Participant extends ConvectorModel<Participant> {
@ReadOnly()
public readonly type = ’io.worldsibu.examples.participant’;

@ReadOnly()
@Required()
@Validate(yup.string())
public username: string;

@ReadOnly()
@Validate(yup.string())

78
CHAPTER 4. IMPLEMENTATION 4.3. SMART CONTRACTS

public msp: string;

@Validate(yup.array(x509Identities.schema()))
public identities: Array<FlatConvectorModel<x509Identities>>;

@Validate(yup.string())
public name: string;

@Validate(yup.string())
public surname: string;

@Validate(yup.number())
public balance: number;

@Validate(yup.string())
public email: string;

@Validate(yup.string())
public city: string;

@Validate(yup.string())
public region: string;

@Validate(yup.string())
public state: string;

@Validate(yup.string())
public role: string;

@Validate(yup.number())
public defaultEscrow: number;
}

In the certificate we have basically the status (valid, expired etc..) and the finger-
print:
export class x509Identities extends ConvectorModel<x509Identities>{
@ReadOnly()
public readonly type = ’io.worldsibu.examples.x509identity’;

@Validate(yup.boolean())
@Required()
status: boolean;
@Validate(yup.string())
@Required()
fingerprint: string;
}

The participant controller, at the time of writing, defines four methods:

79
4.3. SMART CONTRACTS CHAPTER 4. IMPLEMENTATION

• register which allows the user to register specifying passing his data as pa-
rameters. Basically the method checks if a user with the same id already exists
and if not, instantiates the new user

// Retrieve to see if exists


const existing = await Participant.getOne(username);

if (!existing || !existing.username) {
let participant = new Participant();
participant.id = username;
participant.username = username;
participant.name = name;
participant.balance=0;
participant.email = email;
participant.city = city;
...
await participant.save();
} else {
throw new Error(’Identity exists already, please call
changeIdentity fn for updates’);
}
}

• changeIdentity Allows admin user to change the identity of a regular user.


At its core this method disables the current indentity and then sets a new
fingerprint and a new status, before saving to the ledger:
...
// Disable previous identities!
existing.identities = existing.identities.map(identity => {
identity.status = false;
return identity;
});

// Set the enrolling identity


existing.identities.push({
fingerprint: newIdentity,
status: true
});
await existing.save();
...

• updateBalance allows an admin user to update the balance of a regular user,


based on the operation (pay or add) specified as a parameter
if (operation=="add"){
existing.balance=existing.balance + amount;
existing.save();

80
CHAPTER 4. IMPLEMENTATION 4.3. SMART CONTRACTS

}
if (operation=="pay"){
if (existing.balance < amount){
throw new Error(’Unathorized. User has not enough funds
to perform this operation’);
}
else {existing.balance=existing.balance - amount;
}
existing.save();
}
}

• get returns a certain user by id

Summarizing: with the current methods implemented on the chaincodes we


are able to:

• Manage the books (create, update, delete)

• Manage the basic lending (lendBook, returnBook)

• Manage user registration (register)

• Manage change of identity (changeIdentity)

• Manage update of the balance (updateBalance)

Following macro aspects, at the time of writing, still need to be implemented:

• Dispute management

• Authentication management

• Confirmation of book returned

81
4.4. THE CLIENT APPLICATION CHAPTER 4. IMPLEMENTATION

4.4 The client application


Once defined the basic functionalities on server side, we have started the develop-
ment of the client application.
The app has been written in HTML and Javascript and the code is available in
github
Development has been driven by the study of the interactive design described in
the previous sections.
Let’s analyze the architecture, again, by looking at the actual code:
The file index.html defines the Home page (see figure 6.3) which is structure with
five <div>elements:

• The first two <div>are used to place some buttons related to the main func-
tionalities
...
div class="bookMenu" >
<input type="submit" value="Add Book" class="menuButton" id
="addBookButton"></br>
<input type="submit" value="My Books" class="menuButton" id
="seeBooksButton"></br>
<input type="submit" value="Swaps" class="menuButton" id="
seeSwapsButton"></br>
</div>

<div class="accountMenu" >


<div class="mail">
<img>
<!-- add mail icon -->
</img>
</div>
<div class="balance">
<a href="myBalance.html">Balance</a>
</div>
<div class="account">
<a href="myAccount.html">Account</a>
</div>
<div class="logout">
<a href="login.html">Logout</a>
</div>
</div>
...

• The third <div>is used as input for the search function:


...
<div class="search">
<input type="text" value="Search a book by title" class="
searchBox" id="searchBookBox"></br>

82
CHAPTER 4. IMPLEMENTATION 4.4. THE CLIENT APPLICATION

<input type="submit" value="Search" class="menuButton" id="


searchBookButton">
</div>
...

• The forth <div>is used to show the search results


...
<div id="searchBooksResults">
<table id="searchBookResultsTable">
<tr id="searchBookResultsTableHeader" >
<th></th>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Genre</th>
<th>Year</th>
<th>Status</th>
<th>Borrower</th>
<th>City</th>
<th>Region</th>
<th>State</th>
<th>Deadline</th>
</tr>
</table>
</div>
...

• The fifth <div>is used to show the output messages


...
<div class="output">
<p id="outputMessage"></p>
<div id="confirmationButtonBox">
</div>
</div>
...

After the page has been loaded a javascript function is executed to basically
add dynamic behavior to the buttons. In particular when the search button
is clicked a function is called to:
– Clean up results from previous queries, if any
– Call the API
...
//Call API to get all books
const response= await fetch(’http://’ + ip + ’:8000/lending/
getParticipantBooks/alabarba’)

83
4.4. THE CLIENT APPLICATION CHAPTER 4. IMPLEMENTATION

const json = await response.json();

console.log("response status= " + response.status + "


response type: " + typeof(response));
if (response.status===200){
// Re enable form and button
document.querySelector(’#searchBookBox’).disabled=
false;
document.querySelector(’#searchBookButton’).disabled
=false;
// remove in progress message
document.querySelector(’#outputMessage’).textContent
="";
}
else {
// else display an error message
document.querySelector(’#outputMessage’).textContent="Ooops
there was an error while searching";
return;}
...

– Parse the results, filter the results matching the string inserted by the
user and show them in the page
...
for (i=0; i<booksMetadata.length; i++){
let title=booksMetadata[i]["_title"];

if ( title.toLowerCase().includes(document.querySelector(’#
searchBookBox’).value.toLowerCase())){

matchFound=true;

// Make the table header visible


document.querySelector(’#searchBookResultsTableHeader’).
style.visibility="visible";

let isbn=booksMetadata[i]["_isbn"];
let author=booksMetadata[i]["_author"];
let publisher=booksMetadata[i]["_publisher"];
let genre=booksMetadata[i]["_genre"];
let year=booksMetadata[i]["_year"];

let string="<td><input type=’submit’ id=" + "’" + i +"’" + "


value=’Request book’ onclick=" + ’"’ + "borrowBook(" +
"’" + i + "’" + "," + "’" + isbn + "’" + "," + "’" +
title + "’" + "," + "’" + author + "’" + "," + "’" +
publisher + "’" + "," + "’" + genre + "’" + "," + "’" +

84
CHAPTER 4. IMPLEMENTATION 4.4. THE CLIENT APPLICATION

year + "’" + ")"+ ’"’+ "></td><td>" + booksMetadata[i]["


_isbn"] + "</td><td>" + booksMetadata[i]["_title"] + "</
td><td>" + booksMetadata[i]["_author"] + "</td><td>" +
booksMetadata[i]["_publisher"] + "</td><td>" +
booksMetadata[i]["_genre"] + "</td><td>" + booksMetadata
[i]["_year"] + "</td><td>" + booksMetadata[i]["_status"]
+ "</td><td>" + booksMetadata[i]["_borrower"] + "</td><
td>" + booksMetadata[i]["_city"] + "</td><td>" +
booksMetadata[i]["_region"] + "</td><td>" +
booksMetadata[i]["_state"]+ "</td><td>" + booksMetadata[
i]["_deadline"]+ "</td>"

let newTableRow=document.createElement("tr");

newTableRow.innerHTML=string;
document.querySelector(’#searchBookResultsTable’).
appendChild(newTableRow);
}
...

– Display proper messages (in progress, success, failure etc..) during and
after the research in the output div.

...
if (matchFound===false)
{
//window.alert("match not found")
document.querySelector(’#outputMessage’).textContent="Sorry, no
matching found";}
...

The file myBooks.html allows the user to visualize his own books (see figure
6.6). The structure and the logic of this file is not very different from index.html.
When displaying the data, per each row, this time we will add a multicheckbox
input and a key to edit the book.
The files createBook.html and updateBook.html are similar between them and
are used to allow the user to respectively add and update a book (see figures ).
They are structured with two <div>elements: one for the user inputs and one for
the output message. Once the user clicks on save button to either create or update
the book a function will be called which in the end calls the API to POST the data
inserted by the user.
//Call API to create book
const response = await fetch(’http://’ + ip + ’:8000/lending/
createBook’, {
method: ’POST’,
headers: {’Content-Type’ : ’application/json’},
body: JSON.stringify(data)
});

85
4.4. THE CLIENT APPLICATION CHAPTER 4. IMPLEMENTATION

Summarizing: at the time of writing the following functionalities have been


implemented in the client application:

• Ability to retrieve and display all the books whose title matches the string the
user’s research

• Ability to retrieve and display the books owned by the user

• Ability to create a new book

• Ability to update an existing book

Following macro aspects, at the time of writing, still need to be implemented:

• Authentication

• Ability to delete books

• Dispute management

• Account and balance

86
Chapter 5

Conclusions and next steps

In conclusion, although the application is not yet complete from a functional point
of view, our work has given us a chance to face some of the main challenges related
to the design of a full stack application on blockchain.

We started from a first evaluation of the idea and refined it while studying the
state of the art, adding some elements of innovation and simplifying some other
aspects.
From a technological point of view we have first studied the blockchain technology
in a more general manner to then deepen in the study of a real blockchain solution:
Hyperledger Fabric and the way it is implemented.
From a development perspective we have first assessed the available tools, briefly
experimenting with each of them, to then focus our attention on Convector. More-
over we have learned the how to develop smart contracts on Hyperledger Fabric
using Convector suite and developed a set of basic services exposed via a REST
API server.
To complete our journey, we have then faced also the development of a client ap-
plication ending up with a proof of concept where the client can retrieve and post
data from /to the server while displaying it properly to the user.
While we are conscious that a lot of work still remains to be done to complete
the set of functionalities that our application is able to provide, we believe that the
work done so far has been useful to understand some of the challenges related
to the development of a full stack application.
At the same time the idea to experiment with the Convector suite seems to guar-
antee an acceptable balance between abstraction for faster prototyping, modu-
larity and flexibility to make the solution potentially scaled proof.

We hope that the approach envisioned in our work can be helpful to the scientific
/ software community as a starting point to design and develop effective solutions
based on blockchain.

87
Chapter 6

Appendix

6.1 The interactive design

Below you can find:

• Two files defining the flow between each page of the application.

• Twenty-one files defining each single page

Application flow:

Figure 6.1: Flow between pages

88
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN

Figure 6.2: Flow of the messages

Application pages

Figure 6.3: Home page

89
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX

Figure 6.4: My Books page

Figure 6.5: Swaps page

Figure 6.6: My Books page

90
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN

Figure 6.7: Add Book page

Figure 6.8: Account page

Figure 6.9: Balance page

91
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX

Figure 6.10: Open a new dispute page

Figure 6.11: Message page

Figure 6.12: Login page

92
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN

Figure 6.13: New request page

Figure 6.14: Request accepted page

Figure 6.15: Request declined page

93
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX

Figure 6.16: Acceptance confirmed page

Figure 6.17: Acceptance rejected page

Figure 6.18: Dispute opened page

94
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN

Figure 6.19: Dispute closed page

Figure 6.20: Dispute resolution proposal page

Figure 6.21: Dispute resolution rejected page

95
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX

Figure 6.22: Restitution page

Figure 6.23: Restitution confirmed page

96
CHAPTER 6. APPENDIX 6.2. THE CODE: SMART CONTRACTS

6.2 The code: smart contracts


Latest code related to the smart contracts can be seen at the following address:
https://github.com/alabarba/bookswapy

97
6.3. THE CODE: CLIENT APPLICATION CHAPTER 6. APPENDIX

6.3 The code: client application


Latest code related to the client application can be seen at the following address:
https://github.com/alabarba/BookswapyClientApp

98
Bibliography

[1] https://www.oclc.org/en/home.html. [Online; accessed 17-July-2019].


[2] https://en.wikipedia.org/wiki/Goodreads. [Online; accessed 17-July-
2019].
[3] https://en.wikipedia.org/wiki/Google_Books. [Online; accessed 17-July-
2019].
[4] https://www.demcosoftware.com/. [Online; accessed 17-July-2019].
[5] https : / / sas . elluminate . com / site / external / recording / playback /
link/table/dropin?sid=2008350&suid=D.6136A254950CA8CB126224222264DD.
[Online; accessed 17-July-2019].
[6] http://blockchain.demcosoftware.com/. [Online; accessed 17-July-2019].
[7] https://www.bookchain.ca/. [Online; accessed 17-July-2019].
[8] https://publica.com/. [Online; accessed 17-July-2019].
[9] https://orvium.io/. [Online; accessed 17-July-2019].
[10] https://medium.com/@zhaohuabing/hash-pointers-and-data-structures-
f85d5fe91659. [Online; accessed 17-July-2019].
[11] https://medium.com/blockwhat/finding-consensus-4-4-alternative-
consensus-mechanisms-3b8817bd6d57. [Online; accessed 17-July-2019].
[12] https://hyperledger- fabric.readthedocs.io/en/release- 1.4/key_
concepts.html. [Online; accessed 17-July-2019].
[13] https : / / lists . hyperledger . org / g / composer / message / 125. [Online;
accessed 17-July-2019].
[14] https://github.com/worldsibu/convector/blob/develop/README.md.
[Online; accessed 17-July-2019].
[15] https://hackernoon.com/migrating-from-hyperledger-composer-to-
convector-framework-marbles-example-13a24a74faad. [Online; accessed
17-July-2019].
[16] Maristella Agosti et al. “DelosDLMS - The Integrated DELOS Digital Library
Management System”. In: Digital Libraries: Research and Development. Ed.
by Costantino Thanos, Francesca Borri, and Leonardo Candela. Berlin, Hei-
delberg: Springer Berlin Heidelberg, 2007, pp. 36–45. isbn: 978-3-540-77088-6.
[17] Juan Cabello, Gerrit Janßen, and Alexander Mühle. LibChain. Distributed
library management system based on the blockchain technology. https://www.
atositchallenge.net/wp- content/uploads/2016/11/LibChain- Atos-
IT-Challenge-2017.pdf. [Online; accessed 17-July-2019]. 2017.

99
BIBLIOGRAPHY BIBLIOGRAPHY

[18] Juan Cabello, Gerrit Janßen, and Alexander Mühle. LibChain. Distributed
library management system based on the blockchain technology. https : / /
github.com/libchain/libchain. [Online; accessed 17-July-2019]. 2018.
[19] Juan Cabello et al. LibChain. Open, verifiable and anonymous access man-
agement. https://www.slideshare.net/libereurope/libchain- open-
verifiable-and-anonymous-access-management-juan-cabello-peter-
janacik - gerrit - janen - tim - jungnickel - and - alexander - mhle - tu -
berlin-germany. [Online; accessed 17-July-2019]. 2017.
[20] L. Candela et al. D3.2b The Digital Library Reference Model. English. DELOS
Network of Excellence on Digital Libraries Project no. 231551. Apr. 2011.
[21] L. Candela et al. The DELOS Digital Library Reference Model. Foundations
for Digital Libraries. English. DELOS Network of Excellence on Digital Li-
braries Project no. 507618. Dec. 2007.
[22] Massimo Chiriatti. Blockchain. https://www.slideshare.net/DataDrivenInnovation/
blockchain-massimo-chiriatti-ibm. [Online; accessed 17-July-2019]. 2018.
[23] Vikram Dhillon, David Metcalf, and Max Hooper. Blockchain Enabled Appli-
cations: Understand the Blockchain Ecosystem and How to Make it Work for
You. Jan. 2017. isbn: 978-1-4842-3080-0. doi: 10.1007/978-1-4842-3081-7.
[24] Daniel Drescher. Blockchain Basics: a non-Technical introduction in 25 steps.
English. 2017. doi: 10.1007/978-1-4842-2604-9.
[25] Marcos André Gonçalves et al. “Streams, Structures, Spaces, Scenarios, Soci-
eties (5s): A Formal Model for Digital Libraries”. In: ACM Trans. Inf. Syst.
22.2 (Apr. 2004), pp. 270–312. issn: 1046-8188. doi: 10.1145/984321.984325.
url: http://doi.acm.org/10.1145/984321.984325.
[26] H. R. Hasan and K. Salah. “Blockchain-Based Proof of Delivery of Physical
Assets With Single and Multiple Transporters”. In: IEEE Access 6 (2018),
pp. 46781–46793. issn: 2169-3536. doi: 10.1109/ACCESS.2018.2866512.
[27] A. Lewis. Blockchain & Crypto: The brilliant basics and beyond. https://
bitsonblocks . files . wordpress . com / 2016 / 01 / 2016 - 01 - 26 - fintech -
finals - hk . pdf ? lipi = urn % 3Ali % 3Apage % 3Ad _ flagship3 _ pulse _ read %
3BQH2LGbmzRKy9rZY9N4nfsA%3D%3D. [Online; accessed 17-July-2019]. 2016.
[28] Satoshi Nakamoto. “Bitcoin: A Peer-to-Peer Electronic Cash System”. In:
Cryptography Mailing list at https://metzdowd.com (Mar. 2009).
[29] Pim Otte, Martijn de Vos, and J.A. Pouwelse. “TrustChain: A Sybil-resistant
scalable blockchain”. In: Future Generation Computer Systems (Sept. 2017).
doi: 10.1016/j.future.2017.08.048.
[30] Asger Pedersen, Marten Risius, and Roman Beck. “A Ten-Step Decision Path
to Determine When to Use Blockchain Technologies”. In: MIS Quarterly Ex-
ecutive 18 (June 2019), pp. 99–115. doi: 10.17705/2msqe.00010.
[31] Joana Pereira, M. Mahdi Tavalaei, and Hakan Ozalp. “Blockchain-based plat-
forms: Decentralized infrastructures and its boundary conditions”. In: Techno-
logical Forecasting and Social Change 146 (2019), pp. 94–102. issn: 0040-1625.
doi: https://doi.org/10.1016/j.techfore.2019.04.030. url: http:
//www.sciencedirect.com/science/article/pii/S0040162518319693.

100
BIBLIOGRAPHY BIBLIOGRAPHY

[32] Christoph Schuler, Roger Weber, and Heiko Schuldt. “Peer to peer process
execution with OSIRIS”. In: (Mar. 2004).
[33] K. Wüst and A. Gervais. “Do you Need a Blockchain?” In: 2018 Crypto Valley
Conference on Blockchain Technology (CVCBT). June 2018, pp. 45–54. doi:
10.1109/CVCBT.2018.00011.

101
List of Figures

2.1 The Digital Library Development Framework . . . . . . . . . . . . . . 15


2.2 The user domain content map . . . . . . . . . . . . . . . . . . . . . . 16
2.3 The end user class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Criterion about the presence of end user role . . . . . . . . . . . . . . 17
2.5 5S formal definition of society . . . . . . . . . . . . . . . . . . . . . . 19
2.6 The OSIRIS architecture . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.7 Systems integrated in the DELOS DLMS . . . . . . . . . . . . . . . . 20
2.8 The LibChain architecture . . . . . . . . . . . . . . . . . . . . . . . . 22
2.9 The Ten Steps model . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.10 The Wust model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.11 The IBM model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.12 The Lewis model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.13 The TrustChain data structure . . . . . . . . . . . . . . . . . . . . . 32
2.14 The structure of the chain of contracts . . . . . . . . . . . . . . . . . 35
2.15 Package handover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.16 Payment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.17 Commercial domain based classification . . . . . . . . . . . . . . . . . 39

3.1 Managing ownership . . . . . . . . . . . . . . . . . . . . . . . . . . . 41


3.2 The Hash Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.3 The Merkle Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.4 Cryptographic puzzle structure . . . . . . . . . . . . . . . . . . . . . 47
3.5 Cryptographic puzzle example . . . . . . . . . . . . . . . . . . . . . . 47
3.6 Blockchain Data Structure . . . . . . . . . . . . . . . . . . . . . . . . 48
3.7 Typical structure of the ledger . . . . . . . . . . . . . . . . . . . . . . 51
3.8 An example of smart contract . . . . . . . . . . . . . . . . . . . . . . 52
3.9 Classification of Blockchain solutions . . . . . . . . . . . . . . . . . . 53
3.10 Execute Order Validate approach and interaction between peer and
application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.11 Example of a network configuration with two channels . . . . . . . . 60
3.12 Blockchain data structure . . . . . . . . . . . . . . . . . . . . . . . . 62
3.13 Block header structure . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.14 Block data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

4.1 Home page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65


4.2 User’s book page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3 Swaps page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.4 New request message received by the lender . . . . . . . . . . . . . . 67
4.5 Request accepted message received by the lender . . . . . . . . . . . . 67

102
LIST OF FIGURES LIST OF FIGURES

4.6 Acceptance confirmed message received by the borrower . . . . . . . . 68


4.7 Structure of the packages folder inside the Bookswapy project . . . . 74

6.1 Flow between pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88


6.2 Flow of the messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.3 Home page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.4 My Books page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.5 Swaps page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.6 My Books page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.7 Add Book page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.8 Account page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.9 Balance page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.10 Open a new dispute page . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.11 Message page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.12 Login page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.13 New request page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.14 Request accepted page . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.15 Request declined page . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.16 Acceptance confirmed page . . . . . . . . . . . . . . . . . . . . . . . . 94
6.17 Acceptance rejected page . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.18 Dispute opened page . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.19 Dispute closed page . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.20 Dispute resolution proposal page . . . . . . . . . . . . . . . . . . . . 95
6.21 Dispute resolution rejected page . . . . . . . . . . . . . . . . . . . . . 95
6.22 Restitution page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.23 Restitution confirmed page . . . . . . . . . . . . . . . . . . . . . . . . 96

103
List of Tables

2.1 Commercial landscape in summary . . . . . . . . . . . . . . . . . . . 39

104

You might also like