A Distributed Library Management System Based On Blockchain
A Distributed Library Management System Based On Blockchain
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.
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
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
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
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. 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
7
1.2. THE IDEA CHAPTER 1. INTRODUCTION
8
CHAPTER 1. INTRODUCTION 1.3. THE FUNCTIONALITIES
• 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
• Each user has its own catalog and should be able to add a new book to the
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
• 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.
• 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:
9
1.3. THE FUNCTIONALITIES CHAPTER 1. INTRODUCTION
• 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)
10
CHAPTER 1. INTRODUCTION 1.4. WHY BLOCKCHAIN?
2. Need to bring an element of trust into a system where users do not trust each
others.
11
Chapter 2
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
13
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
• System administrators who control the digital library system through the
digital library management system
– 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
• 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
14
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE
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.
• The reference model which is a general abstract model and can be used to
describe any digital library
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
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]
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
• Examples
To provide an example picture 2.4 shows the criterion about the presence of the end
user role.[20]
• 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
• 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:
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:
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]
19
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
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 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]:
• 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:
21
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
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
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]
23
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
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.
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
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:
25
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
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.
• Smart contracts
• Intellectual property
• e-Voting
• Land titles
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
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.
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.
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.
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.
Result: The model indicates that there might be a use case for blockchain (steps
6, 7, 8 and 9)
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
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
• 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.
30
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE
• A possible way to securely track the exchange of physical assets on the ledger
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
• 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
• 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:
• 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.
2. Testing (section V)
33
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
Three different type of contracts are defined along with a precise structure to
chain them [26]:
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
34
CHAPTER 2. STATE OF THE ART 2.1. SCIENTIFIC LITERATURE
35
2.1. SCIENTIFIC LITERATURE CHAPTER 2. STATE OF THE ART
When the buyer confirms the proper reception of the package, he confirms the
payment(see figure 2.16), which triggers the PoD contract to:
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)
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$
37
2.2. COMMERCIAL LANDSCAPE CHAPTER 2. STATE OF THE ART
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.
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.
38
CHAPTER 2. STATE OF THE ART 2.2. COMMERCIAL LANDSCAPE
39
Chapter 3
Blockchain technology
• 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
40
CHAPTER 3. BLOCKCHAIN 3.1. INTRODUCTION AND BACKGROUND
• 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.
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:
– 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
42
CHAPTER 3. BLOCKCHAIN 3.1. INTRODUCTION AND BACKGROUND
43
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN
• Smart contracts
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.
• Make extremely difficult to change data which is already written in the ledger.
This point is achieved by means of the following:
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:
The pointer can be used to get the information, the hash can be used to verify that
information has not been changed [10]
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
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?
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 [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:
• The nonce.
47
3.2. HOW DOES BLOCKCHAIN WORK? CHAPTER 3. BLOCKCHAIN
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).
48
CHAPTER 3. BLOCKCHAIN 3.2. HOW DOES BLOCKCHAIN WORK?
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.
• 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:
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.
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.
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
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.
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.
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.
• 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.
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 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
– 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.
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 Peers are all the regular nodes participating in the blockchain network.
As we will see they belong to organizations.
• 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.
57
3.3. HYPERLEDGER FABRIC CHAPTER 3. BLOCKCHAIN
• 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.
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
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.
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)
60
CHAPTER 3. BLOCKCHAIN 3.3. HYPERLEDGER 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:
• 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
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)
• 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
• 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
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
as we can see in figure 4.1 the home page exposes the following functionalities:
• Logout
65
4.1. THE INTERACTIVE DESIGN CHAPTER 4. IMPLEMENTATION
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.
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.
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
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.
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
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
• 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.
– 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]:
69
4.2. THE TOOLS CHAPTER 4. IMPLEMENTATION
70
CHAPTER 4. IMPLEMENTATION 4.2. THE TOOLS
• convector-core-controller
The core controller is very simple with only two parameters being defined:
• The sender which identifies the user invoking the controller function.
The core model instead exposes some useful utility methods like:
• update which given one model loaded into the instance, updates its content
with the object passed to the update method.
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:
71
4.2. THE TOOLS CHAPTER 4. IMPLEMENTATION
• hurl install <chaincode> which installs and instantiates the chaincode into
our nodes. Below the main arguments:
• 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
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>
73
4.3. SMART CONTRACTS CHAPTER 4. IMPLEMENTATION
• 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.
Figure 4.7: Structure of the packages folder inside the Bookswapy project
• 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
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:
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;
}
• 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();
• 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
@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;
}
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
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’);
}
}
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();
}
}
• Dispute management
• Authentication management
81
4.4. THE CLIENT APPLICATION CHAPTER 4. IMPLEMENTATION
• 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>
82
CHAPTER 4. IMPLEMENTATION 4.4. THE CLIENT APPLICATION
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
– 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;
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"];
84
CHAPTER 4. IMPLEMENTATION 4.4. THE CLIENT APPLICATION
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
• Ability to retrieve and display all the books whose title matches the string the
user’s research
• Authentication
• Dispute management
86
Chapter 5
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
• Two files defining the flow between each page of the application.
Application flow:
88
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN
Application pages
89
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX
90
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN
91
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX
92
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN
93
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX
94
CHAPTER 6. APPENDIX 6.1. THE INTERACTIVE DESIGN
95
6.1. THE INTERACTIVE DESIGN CHAPTER 6. APPENDIX
96
CHAPTER 6. APPENDIX 6.2. THE CODE: SMART CONTRACTS
97
6.3. THE CODE: CLIENT APPLICATION CHAPTER 6. APPENDIX
98
Bibliography
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
102
LIST OF FIGURES LIST OF FIGURES
103
List of Tables
104