83
POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software Advanced data management on Distributed Ledgers: design and implementation of a Telegram BOT as a front end for a IOTA cryptocurrency wallet Candidate: Francesco Longo Supervisor: Giovanni Malnati Co-supervisor: Edoardo Calia Academic year 2017-2018

POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

POLITECNICO DI TORINO

Master’s Degree Thesis

Computer Engineering - Software

Advanced data management onDistributed Ledgers: design and

implementation of a Telegram BOTas a front end for a IOTA

cryptocurrency wallet

Candidate: Francesco Longo

Supervisor: Giovanni MalnatiCo-supervisor: Edoardo Calia

Academic year 2017-2018

Page 2: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus
Page 3: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Summary

Nowadays the 98% of the information collected by humans in the world is recordedin digital format. Many of our daily actions generate data digitally stored some-where in the world. Often this process is automatic, due to the many devices andappliances equipped with sensors that we use every day (in contexts like automotive,home automation, industrial machines, up to consumer gadgets). As a consequence,digital data grow exponentially. Whoever owns this data can turn it into an enor-mous economic value (but only if they know how to analyze them). The collecteddata can be used to customize advertising for production optimization and productsdistribution, for the predictive maintenance of industrial machines and much more.Unfortunately the majority of these data sets are stored in a few global centers,generating an unsustainable inequality, and at the same time exposing the datato cyber attacks and subsequent threats to privacy and security of citizens. Thevalue which is associated to data is so large that someone proposed a comparisonwith the old economy saying that "Data is the new oil": data are extracted, re-fined and exchanged through a new generation of infrastructures represented by thetelecommunication networks, cabled or wireless. The data economy and the use ofDistributed Ledger Technologies (DLT) are the starting points of my Thesis. Mywork started with the analysis of different DLTs to find potential use cases at the in-tersection of these two topics, and later I focused on the design and implementationof an application prototype using a specific DLT. One of the greatest innovationsof the last 10 years is Bitcoin, the first digital cryptocurrency. We often hear aboutBitcoin for its economic value, which increased significantly since its introduction,and its volatility, which makes it very fluctuating and unstable, generating in timeboth gains and losses. This great volatility and the associated potential ease ofearning attracted many people (traders and investors), leading to record growth.The Blockchain is the architecture behind Bitcoin and it is the real innovation ofthis system. This architecture enables users who have no trust among each otherto create and maintain a shared network dedicated to the exchange of financialvirtual (crypto) assets, offering reliability, consistency, immutability without usinga central entity who takes the responsibility for the provided service. Bitcoin usesthe blockchain as a Distributed Ledger: a sequence of blocks linked to each other.Each block refers to the previous one and contains a set of transactions. Specialusers named miners validate new transactions and store them in the global ledger(the blockchain). On average, a block (the structure containing transactions) ismined every 10 minutes. The mining process consist in finding a complex solutionfor an np-complete mathematical problem that requires a lot of time and computerresources to be solved. Miners keep their own copy of the blockchain, synchronized

i

Page 4: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

with the entire network, and compete to solve this difficult mathematical problembased on a cryptographic hash algorithm, carrying out what is known as a Proof-Of-Work. This basically shows that a miner did spend a lot of time and resourcesto solve the problem. When a block is ’solved’, the transactions contained areconsidered confirmed, and the amount indicated in the transactions can be spentby their owners. Once a block is mined and confirmed by the other nodes in thenetwork, it cannot be modified or replaced in the future, because every block in-cludes the hash of the previous one. From a certain point of view, blockchain offersthe requested decentralization, but gives power to other entities (the miners) that,in fact, control this the network and maintain it. Considering the data-centralityvision of our modern economy, it is natural to think whether or not it is possibleto use a DLT structure for the storage of general purpose data (or sensitive en-crypted data) and not only financial transaction data. Currently the Blockchain isnot the only existing DLT, but there are several other architectures that, taking acue from Blockchain and offering the same advantages, aim to solve its weaknesses:high energy consumption, slow transactions confirmation, not-centrality of the data,limited scalability and high fees associated with each transaction. For my thesisI have chosen to study and analyze IOTA, a DLT created specifically for the IoTand focused on the data granularity. IOTA is called "a Blockchain without Blockand without Chain" because it promises the same advantages of a Blockchain us-ing, however, a different structure called Tangle. The tangle is basically a DirectedAcyclic Graph (DAG) where, instead of building a chain of blocks added at specificintervals, transactions are sent directly, and each one becomes a node of the graph.In IOTA there are no transaction fees. As the Tangle grows and more users maketransactions, the whole system becomes faster, more robust and more secure. Thegoal of my thesis was to understand and analyze data storage based on DistributedLedger Technologies (DLTs). After a little period studying the Blockchain archi-tecture I focused on IOTA. Nowadays the way to store and secure large amounts ofsensitive data is moving from the classical database to DLTs, where security, avail-ability and consistency are essential. The future is seen as a set of devices that savedata and interface through the web to store and exchange information with eachother: this is the IoT vision, where many features and scenarios become possible:machine economy, digital twin, faster transactions and all of this in a scalable envi-ronment. These goals can be reached in a more feasible way using DLTs. The maininnovation behind IOTA is the Tangle, a revolutionary new blockless distributedledger which is scalable, lightweight and for the first time ever makes it possible toperform a transaction, in which any kind of data can be stored without any fees.Differently from the Blockchain paradigm, in IOTA consensus is no-longer dele-gated to a sub-community of users (the miners) but is instead reached through theactive contribution of all users (therefore becoming an intrinsic part of the system),leading to a real decentralized and self-regulating peer-to-peer network. I startedby studying the theory behind the IOTA architecture and the Tangle structure un-derstanding the theoretical principles described in the IOTA whitepaper. Then Ihave studied how to start and maintain a full-node (IOTA application to retrieveand synchronize data on the Tangle) manually-managed using the IOTA ReferenceImplementation (IRI). I set up and managed 3 full-nodes fully synchronized, in-

ii

Page 5: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

stalled at ISMB. As an IOTA developer, I learned how to use the dedicated clientlibraries (JAVA, iota.lib.js) in order to interact with the Tangle. As my Master’sDegree Thesis project I developed a Telegram Bot managing an IOTA wallet foreach user. This bot permits to send and receive IOTA tokens easily from inside achat. I decided to develop my project using the IOTA Javascript library to exploitall the potential of nodeJS and npm packets manager.

iii

Page 6: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Acknowledgements

I would like to thank Professor Giovanni Malnati for giving me the opportunity tocontinue our academic relationship proposing me this research thesis about stimu-lating and advanced topics. I’m grateful to the ISMB research institute (IstitutoSuperiore Mario Boella), SiTI and Links Foundation for providing me with a com-fortable workspace and environment to accomplish this thesis project. A specialthank you to the deputy director of ISMB Edoardo Calia for assisting me in car-rying out this thesis and for always giving me all the necessary support during mystay in ISMB. Another special thank to Dr. Andrea Vesco for his advice and forhelping me in times of need.

A generous thank you thank you to Chris Dukakis, Lewis Freiberg and GiogioE. Mandolfo that helped me to understand details about IOTA libraries during mythesis.

A personal thank you to the members of “Links Foundation” team: AndreaVesco, Michele Osella, Gian Marco Toso, Alberto Buzio, Jure Rosso, Edoardo Caliafor sharing with me their experiences during the EUIPO Blockathon 2018 compe-tition in Brussels.

I would like to remind and thank you my colleagues, classmates, and friendsthat have cheered up those days spent working on my studies and thesis makingthis period a pleasant experience.

Thank you to my extended family (geographically near and far): grandparents,uncles, cousins for all their advices, positive and not, they gave me. A big thankyou to my family: my parents that allowed me to carry on all this giving me allthe necessary, material good and not, to move forward and my two sisters for theirsupport.

iv

Page 7: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Last but not the least, a special thank you to my life partner Alessia for al-ways being by my side and for supporting me throughout this my long journeyappreciating me as I am and never stopped believing in me.

v

Page 8: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Contents

Summary

Acknowledgements iii

1 Introduction: the new data-economy 11.1 The data-centrality of the new economy . . . . . . . . . . . . . . . 11.2 The data analysis process . . . . . . . . . . . . . . . . . . . . . . . 21.3 The data: a fundamental ingredient . . . . . . . . . . . . . . . . . . 31.4 Machine Economy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5 Data Economy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.6 Data wants to be free, but not for free . . . . . . . . . . . . . . . . 5

2 Distributed Ledger Technologies 62.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.1.1 Distributed ledger types . . . . . . . . . . . . . . . . . . . . 72.1.2 Double spending problem . . . . . . . . . . . . . . . . . . . 8

2.2 The blockchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2.1 Distributed consensus . . . . . . . . . . . . . . . . . . . . . 102.2.2 Block verification and mining . . . . . . . . . . . . . . . . . 102.2.3 Blockchain branches . . . . . . . . . . . . . . . . . . . . . . 112.2.4 Miners reward . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.5 Final considerations . . . . . . . . . . . . . . . . . . . . . . 142.2.6 Non financial application . . . . . . . . . . . . . . . . . . . . 15

2.3 Smart contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.4 Weaknesses of the blockchain . . . . . . . . . . . . . . . . . . . . . 162.5 IOTA DLT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3 IOTA 183.1 The Tangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

3.1.1 Structure of the tangle . . . . . . . . . . . . . . . . . . . . . 193.1.2 Tips selection . . . . . . . . . . . . . . . . . . . . . . . . . . 213.1.3 Consensus in the Tangle . . . . . . . . . . . . . . . . . . . . 213.1.4 Proof of Work . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.2 The IOTA token . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.3 Seeds, Private Keys, Accounts . . . . . . . . . . . . . . . . . . . . . 233.4 Anatomy of a Transaction . . . . . . . . . . . . . . . . . . . . . . . 24

3.4.1 Bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

vi

Page 9: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

3.4.2 Performing a transaction . . . . . . . . . . . . . . . . . . . . 273.5 IOTA nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

3.5.1 Light-nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.5.2 Full-nodes and IOTA Reference Implementation (IRI) . . . . 28

3.6 IOTA Client Libraries . . . . . . . . . . . . . . . . . . . . . . . . . 28

4 IOTA Wallet Bot 294.1 Project’s architecture . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4.1.1 Telegram Bot front-end . . . . . . . . . . . . . . . . . . . . . 314.1.2 Telegram Bot back-end . . . . . . . . . . . . . . . . . . . . . 314.1.3 Interfacing with IOTA and IOTA wallet issues . . . . . . . . 324.1.4 IOTA full nodes architecture . . . . . . . . . . . . . . . . . . 32

4.2 Managing seeds with security countermeasures . . . . . . . . . . . . 334.3 Telegram Bot Commands . . . . . . . . . . . . . . . . . . . . . . . 35

4.3.1 Creation of a new account . . . . . . . . . . . . . . . . . . . 354.3.2 Sending payment . . . . . . . . . . . . . . . . . . . . . . . . 414.3.3 Check the available wallet balance . . . . . . . . . . . . . . . 484.3.4 Receiving payment . . . . . . . . . . . . . . . . . . . . . . . 504.3.5 Other commands . . . . . . . . . . . . . . . . . . . . . . . . 53

5 Final considerations and conclusions 575.1 IOTA roadmap and future implementations . . . . . . . . . . . . . 58

5.1.1 Neighbor auto discovery . . . . . . . . . . . . . . . . . . . . 585.1.2 Automated snapshotting and permanodes . . . . . . . . . . 585.1.3 Identity of things . . . . . . . . . . . . . . . . . . . . . . . . 595.1.4 Masked Authenticated Messaging . . . . . . . . . . . . . . . 595.1.5 Flash network . . . . . . . . . . . . . . . . . . . . . . . . . . 595.1.6 Qubic and Oracles . . . . . . . . . . . . . . . . . . . . . . . 59

Appendices 60

A CAP theorem 61A.1 CAP theorem properties . . . . . . . . . . . . . . . . . . . . . . . . 62

A.1.1 Not consistent . . . . . . . . . . . . . . . . . . . . . . . . . . 62A.1.2 Not available . . . . . . . . . . . . . . . . . . . . . . . . . . 63A.1.3 Not partition tolerant . . . . . . . . . . . . . . . . . . . . . . 63

A.2 Consistency in a distributed system . . . . . . . . . . . . . . . . . . 63A.2.1 Distributed consistency model . . . . . . . . . . . . . . . . . 64

A.3 BASE property vs ACID property . . . . . . . . . . . . . . . . . . . 64

B EUIPO Blockathon 2018 66

C The IOTA Data Marketplace 69

vii

Page 10: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Chapter 1

Introduction: the new data-economy

Nowadays 98% of the information collected by humans is recorded in digital format.Many of our daily actions generate data digitally stored somewhere in the world.Often this process is automatic, due to the many devices and appliances equippedwith sensors that we use every day (in contexts like automotive, home automation,industrial machines, up to consumer gadgets). As a consequence, digital data growexponentially. Whoever owns this data can turn it into an enormous economic value(but only if they know how to analyze them).

1.1 The data-centrality of the new economyAvailability, Integrity and confidentiality of digital data are three essential require-ments for a correct management of the huge amount of information that companies,often unconsciously, already have available. In fact, what is missing most of thetime is the ability to extract useful and structured information by combining datathat already resides on the company IT systems.

The increasingly advanced interconnection of IT systems with each other is ac-companied by the increase and availability of software capable of analyzing andprocessing data. In fact, we are moving from accumulating raw data in big het-erogeneous repositories known as big data or data lakes , to a more sophisticatedparadigm where complex analyses are carried out on the same data, generatingsmart data (real information), processed and immediately usable by the company’smanagement. Those data can create competitive advantages on the market throughthe generation of significant information to establish the characteristics of a newproduct or service, set business strategies and evaluate the positioning on the ref-erence market. More in detail, the large amount of data generated from differentsources such as mobile phones, credit cards, web traffic, online purchases or otherdevices, has contributed to automatically generate a mass of information, withouthaving to go to collect them on demand, as happened previously, requiring ap-propriate acquisition activities. Today, what it is really needed is a proper wayto consult those data in an understandable format in order to satisfy the needsof consultation, representation and storage of information. It is also necessary toensure the information security of what constitutes a strategic company asset, thusmanaging the risks, the network, access control, privacy and system compliance. At

1

Page 11: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 1. INTRODUCTION: THE NEW DATA-ECONOMY

the same time it is necessary to develop or make use of analytical tools, moving onfrom the data collection to its processing to extract useful information, essentiallypassing from a quantitative accumulation of data to a selection aimed at achievingthe quality of the same as smart data.

1.2 The data analysis process

A typical analysis process consists of several phases:

• data collection, in which the data is acquired verifying its reliability;

• data management, in which the information is managed and stored according tothe needs of the subsequent phase (functional data science) aimed at extract-ing useful information for the company;

• data visualization, or how the extracted information is presented to make iteffectively usable.

Quality and ease of use constitute the added value that allows big data to becomesmart data that can actually be used as a company asset. The wide adoption ofsmartphones and mobile apps, together with tracking tools used in web sites makeit possible to perform an accurate profiling of Internet users. A user can be tracked

2

Page 12: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 1. INTRODUCTION: THE NEW DATA-ECONOMY

saving its IP address and saving data referring to each interaction, collecting moreand more details for each user in every browsing session. The youronlinechoices.comportal offers Internet users the possibility to check the amount of data collected fromtheir online activity, also offering the possibility to disable some of the tracking.Data is one of the most imperative ingredients in the machine economy and theconnected world.

1.3 The data: a fundamental ingredientDavid Sønstebø (Founder of IOTA) wrote the following text as part of the presen-tation of the IOTA Data Marketplace project:

“Data is one of the most fundamental ingredients in the machine economy andthe connected world. It is the foundation upon which the other strata of the Data,Information, Knowledge, Wisdom (DIKW) Pyramid are dependent. Without thisprimary substrate, nothing can be established about the world. A datum (plural:data) is the raw value of a qualitative or quantitative variable; a pure unfilteredinput from reality. Data sets that are structured and thus have had meaning ex-tracted from them constitute what we consider to be information. Informationtells us something concrete and coherent about the world through context. Con-textualized information thus makes up what we know as knowledge, which in turngives rise to our (and our machines’) ability to make wise decisions. Wisdom isknowledge applied. The illustration above shows how the different echelons of thishierarchy are intertwined. The sensors, here cameras, monitoring the road are re-ceiving signals from the photons reflecting off the surface of their environment. Thisis data. The measured speed of the moving objects and their relative positions isthe meaningful information extracted from these datum inputs. This informationis next contextualized and distilled into knowledge, telling the drivers on the roadvia Over-The-Air updates that the road may be congested due to a crash, whichallows drivers to apply the wisdom to take an alternative route.”

3

Page 13: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 1. INTRODUCTION: THE NEW DATA-ECONOMY

1.4 Machine EconomyIn the next 10 years there will be more than 75 billion connected devices that in-teract each other in different manners. This will increase the so-called “machineeconomy” where devices will be enabled to autonomously trade resources like stor-age, computation/analytics to electricity and sensor data.

In 2017 more data was generated than in the past 5000 years. Of course the“digital age” started recently but these numbers are destined to grow exponentiallyin the next decade.

1.5 Data EconomyThe sheer magnitude of data and the influence it has had - and increasingly willhave - on our society comes with huge business opportunities that will be worthtens of billions over the next few years. Trading data will be a mutually beneficialexercise that boosts innovation for companies and creates entirely new revenuestreams from data that would otherwise simply be ignored or eventually deleted.The largest obstacle preventing the fulfillment of the grandeur envisaged by ‘BigData’ is the fact that the overwhelming majority of data remains locked in what arecalled ‘Data Silos’. Data silos do not, or at best very rarely, share data outside theirown closed environment. This leads to enormous quantities of wasted data: oftenover 99% of available data is lost to the void (source: McKinsey 2015), data thatcould potentially contain extremely valuable information if allowed to flow freely indata streams that create an open and decentralized data lake made accessible toany compensating party.

4

Page 14: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 1. INTRODUCTION: THE NEW DATA-ECONOMY

1.6 Data wants to be free, but not for freeThere are several reasons for the cumbersome and wasteful status quo. On the onehand, data wants to be free in the sense that its storage and transmission costsless and less over time; on the other hand, large quantities of data are extremelyvaluable and are not free to generate. These diametrically opposed conditions causea gridlock that needs to be broken in order for Big Data to become truly big. Amajor cause of this is the fact that, while data sharing is becoming cheaper froma technological perspective, it is prohibitively expensive to sell fine, granular datain real-time due to intermediary fees, not to mention all the red tape one has tocut through in order to complete a single data purchase. These conditions makereal-time data trade all but possible. By 2025 it is projected that around 95% of alldata will be generated by IoT devices in real-time (source: IDC 2017), so this is apressing issue. A third obstacle is the lack of ensured authenticity and audit trailsof data. Before adoption of Distributed Ledger Technologies, data transmissionprotocols and databases were susceptible to various attacks, including ‘man in themiddle’ attacks and data tampering. Data is only as valuable as it is valid. In short,if the data input is garbage, the output will also be garbage (GIGO).

This is why the IOTA architecture and protocol (see IOTA in chapter 3 andmore details regarding Data Marketplace in appendix C) play a key role in unlockingdata’s gigantic potential.

5

Page 15: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Chapter 2

Distributed Ledger Technologies

A distributed ledger (the concept behind the emerging distributed ledger technolo-gies or DLT) is a peer to peer solution aimed at safely maintaining a list of recordsin a robust and secure way. A DLT is characterized by the lack of a central author-ity or maintainer, replaced by a community of peer participant nodes. One of thekey goals of DLTs is the ability to function properly in a trustless environment (pro-vided that a majority of the participating nodes are not malicious). Thanks to thedistributed consensus mechanism, the DL guarantees the immutability of recordsand the proper identification of the users that originated every single transaction.Many DL architectures and protocols implement BFT (Byzantine Fault Tolerance),meaning that they tolerate up to 1/3 of nodes to be malicious.

2.1 Introduction

In a centralized environment there is one entity that controls data integrityand guarantees accuracy. All the users must trust their relationship with suchcentral entity. Typical examples in our day to day life are represented by banks,insurance companies, public administrations, service providers etc On the other

6

Page 16: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

hand, in decentralized environments the main objective is to operate without atrusted central authority: the system is built around a network of anonymous peerswho do not know each other, neither they trust each other (trustless environment).In this type of architecture the trust is needed in order to know the identity ofthe originator of a transaction to avoid that a malicious node can generate faketransaction and, of course, to make sure that the sender of a transaction actuallyhas all the assets needed to complete the transaction itself. The first issue can besolved by requiring to include in the transaction the sender identity, and that alltransactions must be digitally signed using the sender’s private key. In this wayeverybody can verify that the transaction has been generated by the sender usinghis public key. Most cryptocurrencies on DLT do not keep balance information.Instead the information about the available amount is calculated going back intime following all the transactions that had an influence on the balance.

2.1.1 Distributed ledger types

Distributed ledgers can be public (also called permissionless, meaning that everyonecan join the community and become part of the network) or private (permissioned,where the possibility to join the network is subject to approval by the ledger’sowner). They also vary in their structure and size. Permissionless blockchainsrequire computer processing power to confirm transactions. Distributed ledgers canbe composed by anonymous users (nobody trusts anybody) and in this case it iscalled permissionless blockchain or identified users (users can trust each other) andin this case it is called permissioned blockchain. In the first case each user has acopy of the ledger and participate in confirming transaction independently, while inthe second case a permission is required for users to have a copy of the ledger andparticipate in confirming transactions.

7

Page 17: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

2.1.2 Double spending problem

In this type of architectures one of the most known issues to avoid is the “doublespending” problem: a user can spend money only if he has not yet spent it. It ispossible that a malicious user tries to generate a transaction to send money to adifferent user and then immediately after generates another transaction to send backto himself the same amount of money. This is not an easy problem to solve, and evenif you can think of adding a timestamp this can be easily manipulated. The absolutetimestamp may be needed for some applications. For financial transactions theorder of arrival of transactions is used to establish priorities. Ordering transactionsis not easy because while transactions propagate over the network, they may reachdifferent nodes in different order.

8

Page 18: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

Ordering transactions is needed on a distributed ledger to reach a common con-sensus on the network. Essentially, a ledger is an ordered list of legitimate transac-tions (not necessarily of financial type). In a ledger the rules used to reach consensuson the legitimacy and the order of the transactions must be clearly defined, and allthe nodes will update their copy of the ledger according to such decisions.

2.2 The blockchain

The Blockchain represents one of the first solution to the distributed consensusproblem. Transaction are taken from a common pool (sometimes called the mem-pool) and grouped in blocks. The blocks are used to order transactions (all theblocks are linked to each other to represent time ordering). In common applica-tions, a transaction represents and tracks the change of ownership. Transactions tooare linked to each other: more specifically a transaction’s output specifies a spentamount, while a transaction’s input specifies an amount earned. When sendingmoney from A to B the output of A is connected to the input of B.

9

Page 19: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

2.2.1 Distributed consensus

As soon as a block is added to the blockchain, all the nodes participating in thedistributed consensus procedure enter a competition to generate the next block.Each node, known as a miner, takes a group of transactions from the mempooland starts to create a block activating a complex procedure to verify the legitimacyof the selected transactions: by following the chain of transactions backwards itis possible to verify the consistency of all the amounts that were spent or earned,therefore verifying the current balance and the validity of the transaction beingchecked. Once the block is complete with the desired number of transactions, theminer generates the hash of the block content by performing what it is called Proofof work. The first node (miner) succeeding in this completion among all otherminers has a next valid block for the blockchain. This block is broadcast to all theother nodes, and each of them will add the block at the head of the chain afterverifying the legitimacy of all the included transactions continuing the consensusprocess.

2.2.2 Block verification and mining

The Proof of Work (Pow) is part of the verification process of a block. It iscarried out by running a complex algorithm requiring significant resources. This isthe process that is performed by miners to maintain this type of network.

10

Page 20: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

During the mining process, the new block is built including:

• All the (unconfirmed) transactions selected from the mempool;

• The digital signature of the current last block;

• A nonce, a special variable whose value can be changed by the miner in order tosolve the cryptographic puzzle described below.

The algorithm consists in repeatedly applying a SHA256 hash function to thewhole data set, incrementing the nonce value at every iteration until the resultingoutput (the hash) is smaller than a predefined value. This procedure is commonlycalled block mining, and its result consists of the proof of work for that block.

2.2.3 Blockchain branches

The mining process is completely distributed and executed locally by each miner in-dependently (not synchronized with the other nodes). Because of this, it is possiblethat two nodes come up with a new valid block (containing different transactions)roughly at the same time.

In this scenario several “next blocks” (all valid) can be broadcast to the network,generating one or more branches in the chain. The dark blue chain represents theconsolidated chain, while the other 3 blocks represent 3 new (just mined) blockscandidate to continue the chain.

11

Page 21: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

In case of a fork, a miner tries to build the next block on top of the first validnext block received from the network. As soon as one of the chains of the forkbecomes longer than the others, that one is selected as the main valid chain Inthe picture below, if a new block is received for the top branch of the blockchain(even if it is not the first received/generated), the corresponding branch prevailsover the others. In this case the light blue chain becomes the most likely candidateto continue the chain.

Once the longest branch of a fork has been identified, all the blocks on theother branches are automatically discarded by the network. All the transactionsincluded in the discarded blocks are sent back to the unconfirmed transactions set(mempool). In this case the green block and the dark blue block are discarded andthe chain continues with the 2 light blue blocks.

2.2.4 Miners reward

Carrying out the mining process is extremely expensive in term of computing powerand energy. According to the Digiconomist, Bitcoin’s annual electric use is approx-imately 24 TeraWattHours per year (TWh/yr). It is estimated that for a Visatransaction the power used is just 0.01 Kwh, around 37 Kwh for an Ethereumtransaction and around 200 Kwh for a Bitcoin transaction. A compensation mech-

12

Page 22: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

anism must be provided so that the miners are encouraged to keep bearing this highcost. Such compensation comes in two forms: the block reward and the transactionfees.

The block reward

In the Bitcoin Blockchain the block reward is an amount of Bitcoin awarded bya miner for the completion of a block. This amount, originally equal to 50 BTC,decreases in time: more or less it is halved every 4 years (today the block rewardis 12.5 BTC). The Bitcoins paid as block reward are created from thin air (hencethe name of mining). At the genesis of all Bitcoin, a part of those tokens were putaside to be mined as block rewards, and therefore keep the mining process activeover time. Those Bitcoins are earned just by the miner who completed a validblock which becomes part of the official blockchain. Since this amount of Bitcoindecreases in time, at some point in the future all miners will have to give up thisreward and the mining process will be less appealing. The reward will be equal tothe sum of the fees associated with all the transactions included in the mined block.

13

Page 23: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

Transactions’ fees

Every user who wants to make a transaction, of any amount, must include afee to be associated with the transaction. All the transactions’ fees, related to thetransactions included on the block just mined, are earned by the miner who minedthat block. This system will allow to maintain the structure of the blockchaineven when the block reward ceases to exist. Depending on the amount of theincluded fee, transactions can have shorter or longer confirmation time. Sometimesthe information is given to the users about the minimum suggested amount to beincluded as fee in order to see your transaction approved in a reasonable time. Sincethe miner can choose any transaction to approve from the mempool, it is foreseeablethat the transactions with higher fees will be given precedence over all the othersbecause each fee is equivalent to a profit for the miner. The price of the suggestedfee follows the economic law of supply and demand: if at a specific time the networkhas a high number of transactions to approve, the average of associated fees will behigh, otherwise if the number of transactions per time unit is low, also the averagefee will be lower. The rewarding policy can have an impact on the overall operationof the mechanism, also with some risks. If mining becomes a business, larger andlarger miners will show up aiming at getting a larger slice of the pie, creating newconcentration of power and leaving out smaller miners. If the reward is too small,miners would leave the system. If the reward is high enough, more miners would join(interestingly, the equilibrium in case of zero cost for joining and leaving happenswhen the miners’ profit is 0).

2.2.5 Final considerations

Coming back to the double spending problem it is impossible that a node can beable to generate a legal transaction from A to B and then a transaction to himselfto have back the spent tokens. The only possible way to perform this attack is toforce a longest branch to bury the second transaction causing the first transactionto become invalid. But pre-calculating a long branch is not feasible because its firstnode’s hash is influenced by the hash of the current “last node” of the chain. Andalso because calculating a branch cannot start before the rest of the network starts

14

Page 24: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

mining the same “next node”, and beating the network requires a huge amount oftime and resources.

2.2.6 Non financial application

Once the power of the DLT architecture able to store data in secure, a tamper-proof, certified way is understood, it is possible to imagine other useful applicationsin addition to the most known financial ones. DLT structures can be used to storesensitive data or to create a shared database in order to have data shared amongmany people in environments without trust.

2.3 Smart contracts

Another interesting application of these DLT structures can derive from thepossibility to store on them some code. This type of application are called smartcontracts. After the contract is in the blockchain, anyone can use it by sendinga transaction to the address of the contract. Every transaction (except the onesused to store the contracts in the ledger) specify a recipient (destination) address.The effect of receiving a transaction for a contract is to execute the code usingthe data and parameters specified inside the transaction. In order to avoid therisk represented by infinite loops in the code, a contract has a limit to the time orresources (also called “gas”) it can use. While the contracts run, it uses gas unitsup to the limit. If the limit is reached, all the actions are rolled back. Applying thesame mechanism of the transactions’ fees, miners give precedence to transactions

15

Page 25: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

specifying higher gas unit price and higher maximum gas.

In the picture above a potential use of a smart contract is shown, referring tothe use case of management of an insurance agreement. The usual contract signedwith an agency guarantees that, if certain conditions apply or specific events occur,the user gets a pre-defined compensation. A contract like this could be stored in ablockchain, making it visible to any party interested in checking all its clauses (atransparency feature not commonly found in traditional contracts). In case some ofthe events covered by the contract actually happen, the code written in the contractstarts execution evaluating conditions and then performing the transaction if theconditions are satisfied.

2.4 Weaknesses of the blockchainBitcoin is the most famous DLT architecture and since its introduction in 2009 it hasgenerated great interest for the new features introduced. Nowadays the blockchainis considered as the most famous DLT architecture to be taken as an example in thiscategory and many other technologies are rising trying to emulate its advantagesand overcome its drawbacks.

The main advantages of this specific DLT structure have been already covered.The list below includes some of the weakness of the blockchain, which led me toconsider a different type of DLT:

• Transaction fees;

• Energy consumption (due to the high work caused by the complexity of the PoW);

• Low scalability (transactions confirmation rate limited by design);

16

Page 26: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 2. DISTRIBUTED LEDGER TECHNOLOGIES

• Not really decentralized: the miners’ community actually controls the networkoperation and performance;

The impact of the above mentioned limits depends on the specific applicationcontext and requirements. My thesis is referring IoT (which requires low costs,high scalability and fast transaction confirmation time), for which Blockchain isdefinitely not the best solution.

2.5 IOTA DLT

Several families of DLTs have been designed and implemented in the past fewyears (permissioned, permissionless, private, public, etc...). After a starting periodwhere I analyzed DLT basic functionalities and major advantages they can offer, Idecided to focus entirely on a DLT architecture called IOTA.

IOTA is:“A next generation permissionless distributed ledger that utilizes a novel inven-

tion, called a Tangle, at its core.”In the next chapter I analyze the IOTA main features, with some references

to Blockchain in order to underline the advantages and disadvantages of IOTAcompared to the most known DLT architectures.

17

Page 27: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Chapter 3

IOTA

Due to its innovative architecture IOTA offers a range of unique features:

• Scalability: IOTA can achieve high transaction throughput thanks to paral-lelized validation of transactions with no limit as to the number of transactionsthat can be confirmed in a certain interval;

• Decentralization: IOTA has no miners. Every participant in the network whowants to put a transaction on the tangle actively participates in the consensus.This makes IOTA more decentralized than any Blockchain;

• No Transaction Fees: IOTA has no transaction fees;

• Quantum-immunity: IOTA usesa next generation trinary hash function calledCurl-p, which is quantum immune (based on Winternitz one time signatures).

3.1 The TangleThe Distributed Ledger used by IOTA is a data structure based on a DirectedAcyclic Graph that the project team decided to call tangle. Sometimes referred toas “a blockchain with no block and no chain”, the Tangle has also no miners: everyparticipant has to carry out his/her own (small) proof of work therefore contributing

18

Page 28: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

directly in the consensus procedure. This radically new architecture solves some wellknown issues shown by BlockChain-based systems and other Distributed LedgerTechnologies.

3.1.1 Structure of the tangle

A directed graph is a collection of vertices (squares on the picture above), andedges (arrows that connect squares). The tangle is a particular kind of directedgraph in which the vertices are transactions. When a user wants to add a newtransaction she chooses 2 transactions already present on the tangle and confirmsthem by creating 2 new references (which become two arcs going from her newtransaction to the two selected ones). In this picture, for example, the transactionnumber 5 is linked to transactions 2 and 1, (meaning that it confirms those 2transactions). Unconfirmed transaction are called tips: in the tangle shown in thepicture above the 4 gray transaction at the rightmost end are all tips (the last addedtransactions). While the picture above shows a simple representation of a part ofthe tangle, the picture below shows a real part of the tangle in the IOTA mainnetdisplaying how complex this structure can become.

19

Page 29: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

The main motivation for the choice of a DAG structure is scalability: a blockchainhas an inherent transaction rate limit related to two fundamental parameters: theblock size (which limits the number of transactions that can be included in a block)and the block issuance rate. If blocks are issued too frequently, or are too large, theblockchain will experience frequent forks. When a fork happens, several new blocksare added to the chain at similar times, and the network must eventually decidewhich ones belong to the actual chain and which ones must be discarded with arollback action. In a DAG, many forks are accepted and they occur often. Unlikeblockchains, a fork is not final. Diverging branches can be merged back together,as long as they are consistent with each other. The transaction rate is thereforebounded only by the nodes’ latency. DAG is an alternative ledger architecture seenas a variance of blockchain. With reference to the CAP theorem of distributed sys-tems, this new structure favors Availability over Consistency, which is guaranteedeventually.

The first transaction in the Tangle is referred to as the genesis. All the IOTAtokens were created in the genesis, and no new ones will ever be created. Alltransactions in the tangle reference the genesis directly or indirectly (see section3.1.2).

As said before, the last transactions added to the tangle that have not yet beenconfirmed by other transaction are called tips. The IOTA consensus algorithm isexpected to chose tips to approve, rather than older transactions already referencedhelping to move the consensus forward through the tangle.

Each transaction contains payment information, in the form of "A paid B XIOTAs". Approving a transaction implies verifying that it does not break theconsensus rules: in particular, that none of the accounts have negative balances. It

20

Page 30: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

also checks that the two chosen transactions are not conflicting with each other.

3.1.2 Tips selection

As was said before, the nodes of the DAG represent transactions and the edgesrepresent approvals. 2 types of approvals are possible:

• Direct approval: If there is a direct connection from a Tx A to another Tx B(A directly references B);

• Indirect approval : Tx A is said to indirectly confirm Tx B if there is a multihoppath along the graph from A to B.

The IOTA network is composed by nodes connected in pairs using a P2P protocolthrough which they continuously interact each other. Each node is capable of storinga portion or the whole tangle, and it keeps in sync with all its peers. Each noderepresents an entry point to interact with the tangle, and offers features such as theselection of the two tips to be confirmed by a new Tx that is being sent to the tangle.Node are designed to follow a recommended tip selection algorithm. Tip selectionis done by performing a weighted random walk from the genesis towards the tips.The walk stops when it reaches a tip. The walk is performed twice, and so two tipsare chosen. This tip selection algorithm is designed to not favour transactions thathave been longer in the DAG,therefore creating an incentive to select and confirmnewer transactions.

3.1.3 Consensus in the Tangle

As a payment network, IOTA provides a method to know when a transaction canbe considered, without error, as confirmed. When a Tx is considered confirmed itis accepted by the public consensus and cannot be removed from it since other Txsrefers to it and it is considered a solid part of the ledger.

Currently there are two approaches to establish consensus in the tangle: thedistributed approach suggested in the whitepaper and the current (temporary),centralized procedure orchestrated by a coordinator.

The coordinator

The coordinator is an entity controlled by the IOTA Foundation, which issues azero-valued transaction (called a milestone) every two minutes.. Referring to thismethod, the definition of consensus is very simple: any transaction referenced by amilestone is confirmed, and the others are not. Since IOTA structure it is completelybased on decentralization, this method cannot be a long term solution, because itis centralized. This is a temporary solution introduced to allow the Tangle to growin a controlled and secure way. When the tangle is large enough it will be able toself-maintain, and the coordinator will be turned off.

21

Page 31: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

Markov chain Monte Carlo (MCMC)

In the IOTA whitepaper a probabilistic and distributed approach is described toguarantee the consensus of a transaction approval, based on the MCMC algorithm.This is similar to Bitcoin and other distributed ledgers, where at any given time atransaction has a confirmation confidence, which is an indication of its acceptancelevel. In order to know the confirmation confidence for a particular transaction, thetip selection algorithm is performed 100 times. Then it is computed how many ofthe 100 selected tips reference the considered transaction. If it is referenced by 60tips out of 100, for example, the transaction is considered confirm with a confidenceof 60%. Currently, in the IOTA network, if a transaction has not been confirmedin 30 minutes, the probability that it will be confirmed in the future drasticallydecreases. If this happens, It is necessary to rebroadcast the transaction or make anew one with the same data.

3.1.4 Proof of Work

IOTA uses Proof of Work to protect from spam. This PoW is similar (but muchsimpler) to the Hashcash1 mechanism used for the same purpose. PoW is a shortcomputational operation which consists in finding a number of trailing zeroes (intrytes) in a transaction hash. The number of trailing zeroes is called Min WeightMagnitude (MWM) and is directly related to the difficulty of the Proof of Work.The MWM is proportional to the Pow difficulty and every extra zero to be foundincreases the difficulty by 3 times. A device that does the PoW will bruteforce thetransaction hash (changing a dedicated field called “nonce” at every iteration) untila hash with the required number of trailing zeroes is found. For the IOTA Mainnetthe MWM parameter is equal to 14, while the value for the testnet is 9.

3.2 The IOTA tokenThe IOTA architecture has an associated “crypto-token” that has the same name(IOTA). This token is built upon the Tangle technology.. The token operates on apermission-less Tangle network known as the Mainnet. Everyone is able to interactwith this network by operating a personal full node that is peered with neighboursmanually added or by relying on a node operated by a third party. All IOTA coinswhich will ever exist have been created with the genesis transaction. This meansthat the total supply of IOTA will always stay the same (no mining allowed). Thetotal supply of IOTA tokens is:

(333 − 1)

2= 2779530283277761

1Adam Back. Hashcash, May 1997. Published at http://www.cypherspace.org/hashcash/.

22

Page 32: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

Since the IOTA architecture was thought to support IoT, it is specifically de-signed to collect data at a high throughput: the high supply of the associated tokenmakes it optimal to support a high number of very small transactions while stillkeeping efficiency. IOTA use the SI notation to write in a convenient way a largenumber of tokens. In all the trading sites IOTA is referred as MIOTA (Mega IOTA)referring to 1,000,000 IOTA.

3.3 Seeds, Private Keys, AccountsAn account in the IOTA system is identified with a seed. The seed is a numberrepresented using 81 trytes, and it is the unique access key to the proper account andto the corresponding funds. The seed has to be securely stored and never shared.A seed isn’t associated to any information about its owner. Its property is basedon ownership: if someone has a seed, he or she can access to the token associatedto that seed. IOTA allows to choose among 3 security levels. Each security level isassociated to an average number of rounds for hashing. This means that a singleseed can correspond to 3 different accounts. The client libraries make it possibleto easily switch and choose a security level. A user having access to a seed cangenerate a private key, and from that an address. Incrementing a parameter calledkey index it is possible to generate an almost infinite number of private keys andaddresses from the same seed. To guarantee security, all sensitive functions areimplemented client side and thanks to this it is possible to generate private keysand addresses securely in the browser or on an offline device. IOTA uses Winternitzone-time signatures: it is strongly advised to not reuse a previously used privatekeys. Continuous reuse of private keys can disclose part of the private key andultimately the seed, having access to the associated founds.

23

Page 33: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

3.4 Anatomy of a TransactionA transaction in IOTA consists of 2673 trytes (if encoded). When you decode thetrytes you get a transaction object which has the following structure:

24

Page 34: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

25

Page 35: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

3.4.1 Bundle

IOTA uses an account-like scheme. This means that we have inputs (addresses)which you have to spend in order to transfer tokens. Addresses are generated fromprivate keys, which in turn are derived from a tryte-encoded seed. A transfer inIOTA is a bundle consisting of outputs and inputs. Bundles are atomic trans-fers, meaning that either all transactions inside the bundle will be accepted by thenetwork, or none.

The construction of bundles is done by client software. To manually create abundle it is necessary to retrieve all the available input addresses (all the addressescreated from the seed with a value greater than 0 of IOTA coins) for the consideredseed and then choose a set or all of those addresses to satisfy the requested amountof IOTA for that transaction. If the sum of IOTA of the provided input addresses islarger than the requested amount of IOTA, it is necessary to provide an address towhich all the unused IOTA will be sent. Inside the bundle there is the transactionmoving the requested amount from input to the recipient address (the one wherewe want to sent IOTA) and then a set of transaction to set the balance 0 from thepreviously used input address. It must be noticed that all used input address shouldnot be used twice for security reason. All of those operation can be performed in anautonomous way (some function performs everything in background) or manually,so an algorithm must be implemented to store all used inputs and provide correctinputs when needed.

26

Page 36: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

3.4.2 Performing a transaction

In IOTA there are no miners, and the process to build a valid transaction is differentfrom the Blockchain out there today. Here are the steps needed to perform atransaction :

1. “Signing”: sign the transaction inputs with a generated private keys (this canbe done offline);

2. “Tip Selection”: the MCMC tip selection algorithm is used to randomly selecttwo tips, which will be referenced by the new transaction. The 2 selectedtransaction are called “branchTransaction” and “trunkTransaction”;

3. “Proof of Work”: in order to have your transaction accepted by the network,you need to do some Proof of Work - similar to Hashcash (spam and sybil-resistance). This usually takes around 30 seconds on a modern PC.

After these steps, the 2 tips selected and the “nonce” leading to a hash whichsatisfies the MWM are written in the transaction object. At this point this objectis ready to be sent to the network. Then it will be further confirmed when othertransaction reference it, directly or indirectly.

3.5 IOTA nodesWhen participating in the IOTA network it is possible to choose to operate a lightnode or a full node. With the GUI wallet (available on the official IOTA GitHubrepository) it is possible to choose to run it as a light wallet or as a full wallet(corresponding to a light or full node).The information provided so far shows thatin IOTA it is possible to identify 2 abstraction layers. The first is represented by theP2P network built around the IOTA full nodes, and the second represented by theTangle. Every full nodes keeps a copy of a portion or of the complete tangle. Fullnodes continuously synchronize with their peers exchanging information about thelast tips, and they broadcast the transactions generated by light nodes application(like the light wallet wallet) that are linked to full nodes. A full node is neededto interfacing with the tangle but it is not necessary for a user to run his own fullnode.

3.5.1 Light-nodes

A light node is a simple application that relies on a IOTA full node to carry outthe most complex functions needed to attach transactions to the tangle.. The mostconvenient (but complex) way is to run and manually manage a full node and thenuse other applications, such as the IOTA GUI wallet, referring to that full node. Inthis way it is possible to have the complete control of the process and it is the bestway to understand the complete process to interface with the tangle. It should benoted that all sensitive functions (such as hashing and signing) are performed clientside. This means that the use of a light wallet (even if provided by a third party)

27

Page 37: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 3. IOTA

guarantees anyway that the seed or the private keys never leave the local deviceNot even the light wallet provider can access the IOTA funds

3.5.2 Full-nodes and IOTA Reference Implementation (IRI)

A full node can be runned with the IOTA Reference Implementation, a java appli-cation that stores locally its own copy of the tangle and synchronizes with other fullnodes added as neighbors. This application can be retrieved on the IOTA GitHubpage and can be run in background to start the synchronization phase. This is afull featured IOTA node with a JSON-REST HTTP interface. It allows users tobecome part of the IOTA network as both a transaction relay and network infor-mation provider through the easy-to-use API. The IRI has a lot of parameters thatcan be set in a initialization file (iota.ini) passed as input parameter to the javaprocess. In this file it is possible to specify port numbers dedicated to the APIs orudp/tcp connections to other neighbors. Among the parameters it is also possibleto include a static list of neighbors. The IRI offers the possibility to build othermodules called ixi modules that support extended features. Among the existing IXImodules one is dedicated to making the neighbor discovery procedure automatic orto checking the status of the current neighbors (for example CarrIOTA is one of themost used for the autodiscovery). All those modules are welcome from the IOTAFoundation but are not part of the official provided code and are in beta version.

3.6 IOTA Client LibrariesCurrently there are some IOTA client libraries available to set up an interface withthe tangle and many others are a “work in progress” or in a beta version. With Clientlibraries it is possible to read and write from and to the tangle. One of the most used(and stable) libraries is the Javascript library called iota.lib.js. A python libraryand a Java library are also available. For my thesis project I decided to use theJS library because it implements both the official API and some newly proposedfunctionality (such as signing, bundles, utilities and conversion). The iota.lib.jsoffers the possibility to use convenient functions to send a transaction calling justone wrapping method, but also to manually write the entire process to create atransaction by manually calling all the needed methods. In this way it is possibleto customize data inside a transaction or to perform a zero-value transaction andto choose how to broadcast it and when to rebroadcast the transaction if it doesn’tget confirmed within the desired time.

28

Page 38: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Chapter 4

IOTA Wallet Bot

After spending a few weeks studying the IOTA architecture and the main func-tionalities of the tangle, my thesis’ project concentrated on a specific application:the design and development of a Telegram Bot able to manage an IOTA wallet foreach user. This bot allows to send and receive IOTA tokens easily directly from in-side a chat. I decided to develop this application using the official IOTA Javascriptlibrary to exploit all the potentials of nodeJS and npm packets manager. When Istarted thinking about the the bot features I imagined 4 different use cases:

1. Private chat between a user and the bot: to send/receive IOTA the user needsto manually copy/paste the required addresses;

2. Enhance the function mentioned at the previous item permitting to send IOTAto a username. The bot will manage all the process in the background avoidingthe manual handling of addresses;

29

Page 39: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

3. Open multi-user wallet for users belonging to a Telegram group: each userbelonging to this group can perform any operation and the correspondingtransactions will remain on the chat history showing who has performed it;

4. Restricted multi-users wallet for a group of user on the same Telegram group:all users must authorize each operation inside this group.

For my Master’s Degree Thesis project I focused and analyzed all the aspectsreferring to use case n°1. The other use cases will be analyzed and developed infuture releases. The goal of this bot is to facilitate the exchange of IOTA withouthaving to use a dedicated wallet application. The Bot isn’t intended to store andhandle a large amount of IOTA to avoid unpleasant situations.

Particular attention was dedicated to the bot usability: starting using this Botjust requires to open a new chat with the user “@IOTAWalletBot”. The bot iscurrently in beta version and for this reason I do not consider myself accountablefor the misuse and/or malfunctions caused by the use of libraries under development- even if in stable versions.

All the details about this Bot project it is available on the IOTA Ecosystem site(https://ecosystem.iota.org/projects/iotawalletbot) and all the code is released asopen source code on GitHub (https://github.com/france193/IOTAWalletBot).

4.1 Project’s architecture

30

Page 40: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

The picture above represents the architecture with all the parties involved in myproject. Five different elements can be identified, depicted each one with a differentcolor. The core is the server, which includes the sw needed to interact with theTelegram server and with the IOTA full node(s). The server runs an applicationdeveloped in Javascript with nodeJS and using the node packet manager (npm) itimports all the required libraries to interact with Telegram and with IOTA.

4.1.1 Telegram Bot front-end

This bot is designed to work with telegram, so the front end application (Telegramchat client) cannot be changed. This can be a big advantage because you canreach many devices with different OS without doing any work, because Telegram isavailable on Windows phones, Android devices, iOS devices and has a web browserversion (compatible with the most common browsers) as well as some “app“ versionsavailable for Mac OS and Windows and Linux. The only (major) drawback is thatit is not possible to implement any function in the front-end: all the logic has to beimplemented on the server and it is not possible to modify the Telegram application.

4.1.2 Telegram Bot back-end

The concept of a Telegram bot is really simple: it is considered as an account peoplecan chat with, but without a real user behind. You must then plan and design all theexpected commands a real user may send to the bot, and the corresponding answers.A command is a string starting with a “/” with the mnemonic name describing thefunction it is intended to perform (for example “/send_hello_world”). When theuser sends something to the bot, all messages pass through the Telegram serverusing a 100% secure and encrypted channel. The Telegram bot application receivesall the commands from the Telegram server using the same mechanism (100% secureand encrypted channel). There are 2 possible paradigms the bot application canuse to receive commands: polling mode or webhook. The polling method consistsin continuously attempting to check (every few milliseconds) if there are messagessent by the telegram server. This method is easy to implement and fast, but ituses a lot of communication resources and power. It is also possible that, in casethe internet connectivity is lost, the bot goes into an inconsistent state possiblyrequiring manual intervention. The second method is more efficient and resistantto network errors. It consists in creating a server on the Telegram Bot applicationand setup this information on the Telegram server. When an update is availablefor the Bot, the Telegram server knows where to send them. For this method it isrecommended for the Telegram Bot server to have a static IP address and a SSLcertificate. The certificate can be self-signed since its only purpose is the creation ofa secure channel between Telegram server and the Bot: you can trust yourself andonly the Telegram server will use this certificate to contact the bot. I developedmy telegram Bot using the webhook paradigm using the “telebot” Javascript librarythat helps implement Bots and all the responses to the commands the bot needs torespond to.

31

Page 41: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4.1.3 Interfacing with IOTA and IOTA wallet issues

In order to interact with IOTA directly from the bot I adopted the official library“iota.lib.js”. This library implements all the functions necessary to interact withthe IOTA full node. Each command made available by the Bot is mapped to asequence of commands that call the IOTA APIs in order to set up a transaction,build the bundle for that transaction and send it to the Tangle in order to wait forthe confirmation. Since my application simply consists in a digital wallet with aTelegram Bot front-end, I started by studying all the mechanisms behind the IOTAGUI wallet made available by the IOTA Foundation. The features offered by awallet are just a few, but they are very complex because (due to the cryptographicalgorithm used by the tangle) the sender address needs to be changed with a newone after every transaction sent with that source address. I had to implementa mechanism in order to store - for each wallet - all the addresses created andused, each one having its own balance. Whenever a certain amount of IOTA needsto be sent, I had to select some of those balances so that their cumulative valueis greater or equal to the amount to be sent. In case it is not possible to puttogether exactly the required amount (which happens in the majority of real cases)the remainder amount must be stored (sent) to just another new address. Onlyat this point the transactions’ bundle can be created, and all addresses used asinputs for that transaction must be marked, on my storing system, as already used.It is also necessary to check the confirmation state of the transaction: only whenit is confirmed the user can be sure that the tangle balance for that account isconsistent. A potential risk of “double spending” occurs if another transaction isgenerated before the approval of the previous one. The IOTA algorithms would notallow double spending anyway, so one of the two (conflicting) transactions wouldremain forever “pending”. What is not taken into account by the IOTA algorithmin the above described situation is the possibility that source addresses are usedmore than once, leading to a potential security breach due to possible detection ofthe account seed or private key (this risk is a consequence of the use of Winternitzone time signature).

4.1.4 IOTA full nodes architecture

As said before, the interface with the Tangle is always demanded to a full nodecapable to perform the heavy computations associated with the PoW. When usingthe client library it is possible to create a transactions bundle and send it to a fullnode to do the rest of the tasks needed to attach the transaction to the Tangle. Ihave developed a set of scripts in order to set up and manually manage 3 differentfull nodes, currently hosted in ISMB. The management of full nodes was quite acomplex task because the nodes require frequent maintenance and checks. Currentlyfull nodes do not have access to an auto discovery feature to find neighbors so it isnecessary to interact frequently with the IOTA community and manually exchangeIP addresses. This task is even more complicated by the fact that not all thecommunity members know how to perform some of the delicate tasks needed tomanage their own full nodes. After a long research I finally managed to create aconnection with a very stable and high performing IOTA Foundation’s node.

32

Page 42: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

I attached the iotanode0 directly to the IOTA foundation node ensuring fastsynchronization and efficiency. On this node I limited the maximum number ofAPIs requests in order to avoid to overload that node: in other words this nodecannot be used as a full interface to the Tangle but it only synchronizes the Tanglestructures with its neighbors. Then I set up 2 other full nodes (IRI applications):iotanode1 and iotanode2. These 2 are linked together and with the previous nodein order to have them easily synchronized with iotanode0. On these 2 full nodesall the API are available and can be used to interact with the Tangle. Using thisconfiguration the workload is split between the two nodes, and they stay correctlysynchronized.

4.2 Managing seeds with security countermeasuresIn IOTA every account is identified with a seed, which must be kept secret. Forsecurity reason I decided to store all the seeds in encrypted form on the samemachine hosting the telegram bot application. In this way the seed does never needto be sent over the network / chat, even if the chat is encrypted. All the encryptionsare performed using the SHA256 algorithm. As explained, all the seeds resides onthe server but only in encrypted form and are never sent outside the server. All thefunctions requiring the use of the seeds are executed locally by the Bot server, whichacts as a client in the interaction with the IOTA network. At the first interactionwith the bot (after sending “/start” command) a seed is created and stored locallyon a server DB; the encryption key is sent back to the user. To increase security, a

33

Page 43: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

salt (a random generated string) is appended to the key and the result is hashed;the hash is stored on the server (hashed_key). The encryption key of the seed isnever stored in any form on the bot server, and after it is sent back to the userit is erased forever. At each interaction the encryption key is requested to theuser; the seed is deciphered using that key and it is used to execute the requestedcommand; then the seed is encrypted again with another random generated keywhich is sent back to the user and erased from the server (repeating the processdescribed earlier). The key is not stored in any form on the bot, but it is visibleon the chat history on the user’s device. If that key is lost, it it is not possiblein any way to access to the associated wallet, and all the funds on that wallet arelost forever. For this reason it is advised to never delete the bot chat history. Toensure that the seed is correct, whenever the seed is decrypted on the bot serverthe reverse of the previous operation is performed. The salt is retrieved from thelocal DB; the salt is appended to the key sent by the user, and the result is hashed.The obtained hash is compared with the value stored in the DB (hashed_key), andif the results match the seed is considered correct, otherwise an error is generated.This is the complete mechanism developed to store in a secure way the encryptedseed.

34

Page 44: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4.3 Telegram Bot CommandsThis section describes all the commands I implemented for the Bot, explaining foreach one the data flow exchanged among the various entities involved in the process.Since this Bot’s main function is to provide a user friendly interface for a an IOTAwallet, these basic actions are needed:

• Create a new account (as said before, in IOTA an account is created with thegeneration of a new seed, see section 3.3).

• Send a payment.

• Receive a payment (create an address on which to receive a payment).

• Check the available wallet balance.

In addition the Bot has some “general purpose” commands to get the currentIOTA token value in USD and to get information about the full node the bot usesas a relay to interact with the Tangle.

4.3.1 Creation of a new account

The creation of a new account (generation of a new seed) is performed with the“/start” command. This is the starting point of any interaction with the bot as youcan guess from the name of the command itself. Before performing any commandwhere the use of the seed is required it is necessary to have a wallet: a check ismade in case a user does not have a wallet and will be asked to launch the startcommand to create a new account. When, for the first time ever, a user opens a chatwith a Bot this “/start” command is automatically sent. This command basicallylets the bot know that there is a new user. In my case I used this command tocreate a new wallet for the new user sending back the first encryption key used tostore the encrypted seed. The next time that a user wants to perform some actionsrequiring the seed it is necessary that the user sends this key back to the Bot . Ateach interaction it is used a different key and the number of the key is stored inorder to let the user understand how many operations have been done. To make theuser more comfortable, each key is written in the form “#KEY_n”. Using the #(hashtag) it is very easy in telegram to come back to the requested n KEY withoutscrolling all the chat history. Of course the user can use this counter as a securitycheck to know how many times he used his seed. If, between 2 consecutive request,the key number is not consecutive (request n require KEY_n and KEY_m requirekey m, where m must be equal to n+1) there may be some problem with your seedand your account can be compromised. This number is updated in every commandwhere the seed is needed and not in every commands (when the seed it is not used,the key it is not required).

35

Page 45: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

36

Page 46: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

This is the entire process for the “/start” command identifying which entitiesare involved:

37

Page 47: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

Here there is a more accurate temporal explanation of the process for the “/start”command:

Notice that in this case it is imagined a use case where the user has a smartphonewith Telegram mobile application but the procedure is the same in any Telegramclient chat (mobile, computer, browser, etc...). Here is all the explanation:

1. The User sends the “/start” command.

2. The command is received from the telegram server (once a message from theuser is received from the telegram server, the server will maintain and managethis message to the Bot). If for any reason the message does not arrive to theTelegram Bot, the message will be kept for 24 hours on Telegram server andit will be will be sent again within the next 24 hours. If the Telegram Bot isoffline for more than 24 hours this message will be lost. If a message is losthere it is not critical, the user will send another request to the Bot until hereceives some answers.

3. The command has been received from telegram Bot, then if the user hasalready a wallet the flow will follow the light blue arrow answering to the userthat has already a wallet and it is not necessary to continue with a new walletcreation.

4. If the user has not got any wallet the process will go on.

38

Page 48: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

5. A new seed is created using the IOTA library.

6. A new randow key K (32 characters long) is created and the seed is encryptedwith this key k.

7. This key K is sent to the user and then it will be deleted (the key will bedeleted only when the Bot it is sure that the user has received this key).Using telebot library it is possible to exploit all the JS power of Promises.The key it is sent using a promise: a background activity that will returnwith a success or an error when the request has been performed. In this casewhen the Telegram server receives this message (with the key K) from the Bot,the promise will be returned with a success status, otherwise an error will begenerated. In this way it is possible to check programmatically if a message(that has been sent from the bot) has been received from the Telegram serveror not. When the Telegram server has received a message from the bot, theproblem is solved because it will manage to send the message to the user incase of error retransmitting until the message is received.

8. The Telegram server has received the message and forwards it to the user.The server also returns a confirmation to the Telegram bot in order to updatethe Promise status.

9. The User receive the message from the Telegram server and the key K isdisplayed on the telephone screen by the Telegram mobile application.

10. The Telegram application sends back a confirmation to the Telegram server(otherwise the server assumes that there was an error).

11. The Telegram server receives the confirmation and knows that the messagehas been displayed on the user’s application.

12. At the same time of the point 8 (as described on the point 7) the Telegramserver sends a confirmation to the Telegram bot updating the promise statusof the request sent by Telegram bot.

13. Once the seed has been encrypted with K, we must store K on the server (notin clear) to be sure that the key that will be sent from the user is correct anddeciphers the seed on demand.

14. A new randow salt (64 characters long) is generated and appended to the keyK. Then, the result is passed to a hash function to create the hashed_key.

15. The Telegram bot will wait for the answer from the Telegram server to un-derstand if it has received the message with the key K.

16. If the promise returns with an error (the bot is not connected, network error,or any type of error), all the process is aborted and an error message is sentto the user to let him know that all the operation is canceled and if he wantshe has to try in another moment. In this case the seed has just been createdso nothing is lost but imaging the situation that a user has a seed and he

39

Page 49: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

has already used this seed (so it has some founds on it) and when the seedhas been deciphered and a new key has been created to crypt again this seed,before being stored into DB, here it is necessary to roll back all the operation.In this way the user sees that there was an error and nothing changes fromthe previous encryption key K. In this way it is avoided that a seed is storedencrypted with a new key and the new key is lost (this can cause the loss ofthe entire account). So, to access to his account he can use the last receivedkey that has been confirmed to be active. (after receiving a key, a user mustreceive a message that confirms its activation).

17. Of course if the seed has been used and then a transaction has been writtenon the tangle, this operation cannot be canceled and in this case the rollbackis only not to lose the account and the tokens present on it .

18. If the promise returns without any error the process can go on and now itis sure that the user has received the new encryption key. Now, the seedencrypted with the new key, the hashed_key and the previous used salt (ap-pended to the new key before performing the hashed_key) are stored in thelocal DB.

19. A message indicating that the new key has been activated is sent to theTelegram server using promises.

20. The Telegram server manages this message as described before and forwardsit to the user.

21. The User receives this message

22. Confirmation is sent back to the Telegram server.

23. When the server receives the message (at point 18) it sends back a confirma-tion to the Telegram Bot.

24. The Telegram bot receives the return status of the promise.

25. If the promise status has no errors the process can continue.

26. The key K, considering the status of the promise, is definitely canceled andnot stored in clear anywhere on the server.

40

Page 50: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4.3.2 Sending payment

For all other commands the process is slightly different, because it is no morenecessary to create a new wallet but only to check if the user, that is sending acommand, has a wallet or not and then to check if the encryption key is correct anddecrypt the seed (checking also if the seed is valid). Finally if all the checks havebeen passed the bot performs the requested command sending results to the user.

41

Page 51: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

Here there is a more accurate temporal explanation of the entire process for ageneral command which involves the use of the seed (this is not shown for eachcommand since the behaviour is very similar):

Notice that this scheme has been simplified avoiding to repeat all the same ar-rows and processes already explained on the previous schema (everytime the Tele-gram bot sends a command to the Telegram bot the command is sent with a JSpromise and the bot will evaluate this result, when ready, managing all the errorsas described before). The same error management is automatically done by theTelegram server when sending some messages to the user. When the message ar-rives to the telegram server (both from the user to the server and from the bot tothe server, in practice when the sender is the telegram server the message sendingis all managed by Telegram) it is considered “safe and arrived” since all the rest isdone by Telegram server taking into account when to send again a message (if themessage was not received).

Here it is all the explanation:

1. The User sends a message using the telegram application and this commandinvolves the use of his seed (a payment for example).

2. The Command is received from the telegram server and it is forwarded to thetelegram bot application.

3. The Telegram bot checks if the sender has already a wallet, if not it invites torun the proper command (“/start”) to create a new wallet, otherwise it takes

42

Page 52: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

into account the command. The blue part is not considered here not to repeatthe already described process.

4. If the user has a wallet it is requested the latest received encryption key todecipher his wallet.

5. The user sends the latest received key K (the process it is not described here)to the Telegram Bot.

6. The bot retrieves from the local DB all the user information stored (hashd_key,encrypted seed, salt used inside the hashed_key).

7. The key K is received by the user. the salt is appended to this K and it isperformed the hash to the previous result, then this hashed key is comparedto the hashed_key previously stored inside DB. If the two hashed keys arethe same the key, sent by the user, is valid.

8. If the key is not valid there is some error, the error message is sent to the user(probably the user sent the wrong encryption seed).

9. If the key is valid the process can go on.

10. The encrypted seed can be deciphered and another check is performed (usingthe iota function to check if the seed is a correct 81 trytes-encoded string).

11. The seed is now used (in this sample the seed is used for perform a payment).See the next schema for more details.

12. A new randow key K* (32 characters long) is created.

13. The new key K* is sent to the user with the same mechanism described before.

14. After the promise returns, if there aren’t any errors, the telegram bot knowsthat the telegram server has received the new key.

15. The seed, previously used, is encrypted with the key K*.

16. A new randow salt (64 characters long) is generated.

17. The salt is appended to the key K*. Then, the result is passed to a hashfunction to create the hashed_key.

18. If the key is correctly received by the telegram server, the telegram bot knowsthat the telegram server has received the new key.

19. If there is some errors on the returned promise, an error message is sent tothe user, rollback is performed on all the actions (the payment performed inIOTA cannot be canceled because it is not possible to delete/modify what hasbeen written on the tangle, all the rollback actions are referred to the actionperformed on local DB).

43

Page 53: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

20. Everything goes well, so it is possible to store in the local DB: the new K*,the new encrypted seed, and the salt used inside the hashed key.

21. A message is sent to the user informing that the new key is now active.

22. Telegram server has received the message from telegram bot, so the promisereturns correctly.

23. K* is deleted from server.

Here it is reported in detail what happens between Telegram Bot and IOTAwhen a command (like send payment) is requested from the user. Previously Ianalyzed the interaction between the user, the server telegram and the bot, now Idescribe how the interaction with the tangle happens:

Here it is the description of the process:

1. All the process before is skipped (the user sends the command so some iotais sent to an address, then the encryption key is requested to the user...).

2. Now, after the seed has been decrypted, and having the amount to be sentand the recipient address, the process to build this transaction can start. TheBot server needs to check the address (associated to this seed) to be used.

3. The Bot server requests to search those addresses in the tangle using the fullnode. It Performs findTxObjects.

44

Page 54: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4. A call to the full node API is performed (findTxObjects).

5. The full node performs this search on the tangle.

6. The results are then sent back to the caller.

7. Telegram bot receives all the transactions attached to the tangle that arerelated to the requested addresses (previously taken from DB).

8. Now I can use, for each address, the group of transactions retrieved fromTxObjects (in the case that a transaction has been reattached more times) tocompute a provisional balance for each address.

9. From these addresses I choose the address with the minimum balance re-moving it from the group of the TxObjects and then, this is repeated untilthe requested amount of IOTA is reached (if there aren’t enough IOTA, thetransaction cannot be performed).

10. If it is needed, a remainder address is added to the transaction (in the casethe amount of inputs balances considered is more that the requested amountof IOTA for the requested transaction).

11. Create a new TxObject in trytes with prepareTransfer function.

12. Trytes are sent to the full node that will broadcast them as a new transactionwhen it finds and verifies 2 tips.

13. The full node receive trytes just created.

14. The full node search 2 tips from its pool or ask tips from its neighbors.

15. The 2 tips are verified.

16. If the tips are valid and verified the process can go on.

17. If one ore both tips is/are not valid (for example cannot be verified becauseof a double spending problem). The full node repeats the research.

18. The full node performs the PoW finding a nonce for this transaction.

19. The transaction is signed.

20. The transaction is then broadcast to the IOTA full node’s neighbors.

21. The results are sent back.

22. The results of the requested transaction arrives to the Bot.

23. The application updates all the address balances marking the input addressesas used and the remainder (if used) in the local DB with the new balance.

24. All the rest of the process to communicate to the user all the results is skippedhere since it is the same described previously.

45

Page 55: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

Here it is a screenshot from the Telegram Bot:

To perform the payment in IOTA it is necessary to generate the bundle andthen do all the requested work (get 2 tips and verify them, find a nonce doing thePoW, attach this nonce to the transaction object, attach the bundle and tips to thetransaction and post everything to the tangle. After having signed the transaction,it is then transmitted to the full node’s neighbors.

I implemented (as an experimental feature) an algorithm to manually compose aIOTA transaction before broadcast it. IOTA library offers the possibility to createa transaction by specifying only the amount of IOTA to send and the recipientaddress: this is very convenient but not enough (currently) in term of efficiency. Iwant to take into account also the balance of the pending transactions related tothe proper account instead of waiting for all the transaction confirmation. I triedto speed up this process because the approval time of IOTA transactions is stillhigh (on average) and fluctuates based on network performance and updates. Thespeed of IOTA network is higher that other DLTs and promises very well but itis not yet at the best levels promised. Imagine that a seed has 2 addresses A andB, the address A has a transaction pending (not yet confirmed: not yet referenced

46

Page 56: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

by other transactions on the tangle) where it is receiving 30 IOTA and address Bhas another transaction pending where it is receiving 20 IOTA. The user owningthis wallet wants to perform a transaction of 40 IOTA but at this moment it hasan account balance of 0 IOTA. To speed up these two transactions it is possible toperform a reattach and/or a rebroadcast of them. This increments the probabilitythat these two transactions can be selected as tips to be confirmed. To receive thesetwo transactions, the two recipient addresses were generated and stored in the localDB. When a new transaction has to be done from this seed all the addresses, notused as inputs, must be checked. A research on the tangle has to be done tocheck if there are some pending transactions and then it is needed to remove, fromthe results, the duplicate transactions. Due to the reattach and rebroadcast donebefore in the tangle there are many transactions duplicates. When one of thesetransactions will be verified, just one among all the duplicates will be selected andverified, all other will remain forever in the pending state.

This is the complete procedure of the algorithm:

1. The situation is the one described above, with two incoming transactions inpending (total 50 IOTA incoming) and a requested transaction outcoming (tobe sent 40 IOTA) to be created.

2. Before replying that this transaction cannot be done because of missing fundsI check all the previously generated addresses and if there are some incomingpayments in pending state on the tangle.

3. From the local DB are retrieved addresses A and B that are not yet used asinputs so can be used, as inputs, for this transaction.

4. For each address a research on the tangle is performed returning all the trans-actions’ objects related to the searched address.

5. Then, if some object has the transaction confirmed it is immediately used tocompute the balance of that address, if all of those objects are in pending allduplicate transactions must be removed from each group. Since the algorithmdoesn’t permit to use an address twice or more times as inputs this can bedone easily. Then a provisional budget of that address is computed.

6. All the provisional budgets for each researched address are used to satisfythe requested amount of IOTA to perform the transaction to create the newbundle.

7. If it is needed a remainder address it is added to the bundle. Then it is addressto the local DB with the balance (the sum of the provisional balance - therequested amount to perform the transaction).

8. The other used addresses are marked as used with a 0 balance on the localDB.

9. Then when the transaction is broadcast it is needed to check if the previoustwo transactions have been confirmed and broadcast them otherwise since thenew transaction depends on those 2 old transactions.

47

Page 57: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

This is what is done to speed up the process without waiting anymore for anytransaction confirmation.

4.3.3 Check the available wallet balance

Interacting with the bot It is possible to know the proper wallet balance just running“/wallet_balance”. Notice that here it is reported the available balance and not theaccount balance. Like a bank account, in IOTA there are two different balances:the available balance and the account balance. The available balance is referredto the balance taking into account all the confirmed transactions related to theproper account. In IOTA it is not possible to compute in a secure way the accountbalance since a transaction that can be in a “pending” state can be rebroadcast orperformed many times. A transaction is approved on average in 5 minutes or lessbut it is possible that it remains in a pending state longer than that. Currently atransaction can be approved in two different ways: if the Coordinator (see section3.1.3.1) references this transaction or if another node (that wants to send anothertransaction) takes this transaction as a tip to approve. If the transaction is validatedfrom another transaction is then confirmed. If a transaction remains on a pendingstate for more than 30 minutes (nobody chose this transaction to confirm or thereis some inconsistent information regarding this transaction), the possibility thatthis transaction will be selected decreases drastically. So a solution, to speed upthis process, can be to perform another 0-valued transaction, or to rebroadcast thistransaction to our full node neighbors or to create another transaction with thesame bundle (see section 3.4.1). All of these possibilities to duplicate a transaction(to speed up the verification process) make the same transaction appear severaltimes in the tangle. These possibilities are allowed and are not a malicious attemptto generate double spending attack. In fact when someone validates one of theseduplicates just the first will be validated and confirmed, all the other copies will bediscarded and never validated (this is part of the verification process, see section3.1.2). In IOTA it is not possible to trigger the transaction confirmation event andthe only possibility is to check the balance considering only the valid and confirmedtransaction related to the considered seed. I tried to develop, as experimentalfeature, a way to retrieve the account balance trying to delete duplicates from allthe same transactions on the tangle (see section 4.3.2). The bot returns also thecorresponding balance in USD doing a simple multiplication of the available IOTAon the proper bot and IOTA prices retrieved from Bitfinex trading site (see section4.3.5.2).

Here a screenshot from the Telegram Bot:

48

Page 58: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

49

Page 59: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4.3.4 Receiving payment

To receive a payment in IOTA it is necessary to generate a new address from theproper seed and share it in order to receive it on this address. The command is“/get_address”. With this command it is possible to generate an address and then,of course, it is required the encryption key. The address is generated using theproper function of the iota.lib.js library. From a seed it is possible to generateinfinite addresses changing a parameter called “index”. To generate the address allthe indexes and the addresses already generated are stored on the local DB andthis makes the procedure much faster. With iota library it is possible to generatean address for a seed without knowing the index but this process can be very slowbecause it starts a search on the tangle for every address starting from the addresswith index 0 and if that address is not found on the tangle it is considered as a“new address”. This method is not so fast and secure because can be a problem afterIOTA Foundation performs a snapshot and this process can slow down even more.Currently the fastest solution is to store and manage indexes of the addresses foreach seed. On the local DB, as said before, it is stored the last index used and theaddress associated. Thanks to this when a new address is requested it is possibleto have a completely new address. It is not recommended to use an already usedaddress instead a new one to avoid the possibility to use many time the same addressas the source (used as input address) in many transactions. Imagine that an addressA it is generated and it is used to receive a payment. After receiving this paymenton this address will reside X IOTA. It is allowed to use this address A to receiveanother payment of Y IOTA and then in this address will reside all the receivedIOTA (X+Y). If I use this address A to receive another payment of Z IOTA and inthe same time I decide to perform a transaction of (Y+X) IOTA, the address wherereside all the received IOTA (Y+X) is used as input address. After the payment isperformed in the address A there will be 0 IOTA but then the other Z IOTA willarrive. In conclusion, to perform another payment and use the remaining Z IOTAfrom address A it is mandatory to reuse address A as input again and it is allowedbut in IOTA it is very dangerous because on each payment it is discovered a partof the private key used to perform the sign of the transaction. So this must beavoided and for each payment in this bot it is advised to use a new address. On thebot other features are implemented to understand if it is reusing an address alreadyused as input. Each address is stored with its proper index and when a payment isperformed from that address it is marked as used and is never taken into account.

Another important experimental feature, that I implemented on my project, isthe algorithm that permits to reuse the remainder address (if present) of a previouspending transaction just performed from this bot as input for another transaction.On the classical scenario this is the situation: the wallet has an address A with 20IOTA, then a transaction is performed and 15 IOTA are spent. The bot takes theaddress A and uses it as input for the transaction, then it creates another addressB and uses it as remainder address to put back the remaining 5 IOTA (not used onthe previous transaction). The transaction is not immediately confirmed but theuser needs to perform another transaction of 10 IOTA. Using the available IOTAfunction, when you want to perform a transaction, input addresses are retrieved

50

Page 60: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

automatically searching on the tangle among the confirmed transactions (using thegetInputs function) to understand what are the available addresses related to thatseed that contains some IOTA and that can be used as inputs for a transactions.Considering the example described before, the address B is not considered becausethe transaction is not confirmed and the “getInputs” function found just addressA with 20 IOTA available and then address A it is used (twice) as inputs addressfor another transaction. Following the IOTA rules this is not correct because theaddress is used twice and if one of the two pending transaction is confirmed the ad-dress A will be erased moving the remaining IOTA to a remainder address and thenone of the two transaction doesn’t find enough IOTA to perform the transaction.

To avoid this mess I developed an algorithm, modifying also the iota.lib.js, thatpermits to take into account all pending transactions:

1. The User has 10 IOTA on address A and wants to send 6 IOTA to anotheruser.

2. The Bot sends 6 IOTA, as requested, and then generates an address B, asremainder address, to put back the remaining 4 IOTA.

3. On a local DB all addresses are stored with useful information:

(a) Address A has been used as input address: marked as used (never reuseit).

(b) Address B has 4 IOTA (in the tangle all of this information is not con-sidered until the transaction won’t be confirmed but I have all saved inthe local storage).

4. The User wants to send 3 IOTA.

5. I check my local DB if I have enough IOTA to satisfy the requested paymentby checking my addresses and related balances.

6. In this case I know that address B has 4 IOTA (if I check this address on thetangle has a balance of 0 IOTA).

7. I use address B as input address for the next requested transaction creatingmanually a new bundle:

(a) Address B is used as input for the 3 requested IOTA.

(b) Address B is the marked as used and has the updated balance of 0 IOTA.It is created a new address C with the balance of 1 IOTA (the remainderof this

(c) transaction).

8. After creating this bundle I can continue the process of the transaction cre-ation and broadcast to my neighbors.

51

Page 61: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

This is the solution that I developed to permit multiple transactions even ifthe previous is not confirmed. Of course all of these pending transactions must beconfirmed checking every tot time if they have been confirmed or not. We need tomake sure that this chain of transactions is confirmed in order.

Every time a new address is generated it is directly attached to the tangleperforming a 0-value transaction. This permits to see this address on the tangleeven with a balance of 0 IOTA.

52

Page 62: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

4.3.5 Other commands

These are the general purpose commands not directly related to the wallet essentialfeatures.

“/node_info”

With this command it is possible to retrieve all the information regarding the IOTAfull node to which the bot is connected. With this command it is possible to un-derstand if the full node is fully synchronized or not. Notice that, referring tothe “Milestone” index, that represents the latest milestone emitted from the Co-ordinator, and checking the “SolidSubtangleMilestone”, which represents the latestmilestone considered on the Tangle copy of the node, it is possible to understandthe percentage of synchronization. If the 2 values are the same the node is fullysynchronized.

53

Page 63: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

“/iota_prices”

Sending this command the Bot uses the JS “bitfinex” library to exploit the avail-able API of the famous trading site Bitfinex to get IOTA prices. After the requestcompletion the IOTA prices, in the form MIOTA/USD and USD/MIOTA, are re-turned. Remember that the basic tradable unit of IOTA is intended as MIOTA(Mega IOTA = 1,000,000 IOTA).

54

Page 64: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

“/help”

This command can be useful to get a shortcut for all available bot commands.

55

Page 65: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 4. IOTA WALLET BOT

“/help_help”

This command is the same of the previous command but has a detailed descriptionof each command.

“/donate”

With this command it is possible to donate some IOTA to the developer of theTelegram bot. It is requested to the user to specify the last encryption key andthe amount of IOTA he wants to donate. (the process is the same of the sendpayment previously described without the specification of the address since it isautomatically generated from the developer’s wallet).

56

Page 66: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Chapter 5

Final considerations and conclusions

IOTA is a relatively new ecosystem and it is still difficult to express final opinionsabout its architecture and performance. Many features are still being implemented,and even the tangle is not yet fully functional in a comòletely decentralized way.What can be definitely said is that it is very promising and the team behind theproject always showed great enthusiasm, competence and attention to the technol-ogy implementation and improvement more than to other aspects such as specula-tion. The basic architecture is ready and stable and the IOTA Foundation developerteam is carrying out constant tests to make it more and more secure and stable,so that soon it will be possible to remove the coordinator process and have a trulydecentralized system. It is really impressive to see how from an innovative ideathey have managed to create a group of people scattered all over the world who arevery organized and collaborate on different topics, keeping themselves constantlyupdated. Technologies for collaboration allow all this to work fine and the passionand dedication of the team has allowed people interested in the subject, like me, toget in touch with the core developers, be accepted in the community and thereforehave a priority lane to quickly learn the principles of this new technology. Nowa-days there are still issues regarding the storing of non transactional data, and sinceIOTA is designed for IoT, this can be a big problem for users interested in usingthe tangle as a decentralised database. We must keep in mind that some solutionsare already designed and are waiting to be implemented and tested: permanodesand automated, local forms of snapshots. Currently all of these type of problemscan be addressed with the support of a traditional database. Nowadays the IOTAFoundation team is working to strengthen the IOTA base structure by releasingfrequent updates of the core components such as the full-node software (IRI) andthe client libraries. The IOTA Foundation is currently searching for new passionateand talented people to carry on this project collaborating and working on all theproject and this is the right way to obtain great results in a short time. Asidefrom the development of libraries and core applications, the IOTA foundation offersmany possibilities to participate in different funded initiatives such as hackathonsand projects aimed at trying and testing the future applications that will be de-veloped, such as the already mentioned IOTA data Marketplace. Our thesis groupparticipated in this project from the very beginning when it was launched in Decem-ber 2017: we connected several devices equipped with sensors configured to send

57

Page 67: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 5. FINAL CONSIDERATIONS AND CONCLUSIONS

sensors’ data (weather and environmental parameters in our case) to the tangle. .The purpose of this simple project was testing the MAM (Masked AuthenticatedMessaging) mechanism learning how to create a data stream that could be later re-trieved (possibly for a fee) directly from the tangle. As previously discussed in theIOTA section about their roadmap, another really important feature is the Qubicproject, currently being implemented (work in progress). Qubic is a protocol thatspecifies IOTA’s solution for oracle machines, smart contracts, outsourced compu-tations, and more. Finally, due to its focus on the new, data-centered economy, ,technologies like IOTA will definitely be among the protagonists of the next dig-ital revolution by enabling major disruptive paradigm like the so called machineeconomy.

5.1 IOTA roadmap and future implementationsIOTA was initiated with the very clear and focused vision of enabling the paradigmshift of the Internet of Things, Industry 4.0 and a trustless ‘On Demand Economy’through establishing a de facto standardized ‘Ledger of Everything’. Since the veryfirst lines of code that were written in mid 2015, the project has come a long way,but still the IOTA development has only barely begun. The IOTA roadmap isfull of new features and functionalities that have been announced or are in thedevelopment and testing phases. The IOTA main features are available and themainnet is in a stable version but many more announced features are currentlyunder development.

5.1.1 Neighbor auto discovery

Among the new features in the IOTA roadmap a relevant one is the release ofan auto-discovery algorithm. Currently IOTA full nodes can add neighbors onlymanually. The availability of auto discovery would permit a fast way to becomepart of the IOTA network.

5.1.2 Automated snapshotting and permanodes

Tha tangle allows to use transactions also to store information different from a tokentransfer, by just attaching to a Tx any data type in a specified format (like a jsonobject). This type of transactions (zero-iota transactions) can be lost if a snapshotevent occurs. Snapshotting is a technique (currently centralized and carried out bythe IOTA Foundation) introduced to reduce the size of the tangle. When a snapshotoccurs, all the non-zero-iota transactions are compacted in the resulting balances;all the zero-iota transactions are simply removed.. This is a major problem forprojects where the tangle is used just for data storage. IOTA is working on a sortof “Automated Snapshots” instead of the centralized actual snapshot version and onan implementation of “permanodes”. Each user will be able to decide when and howto perform his own personal snapshot and will decide, with a personal permanodeimplementation, which data to keep and which to delete.

58

Page 68: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

CHAPTER 5. FINAL CONSIDERATIONS AND CONCLUSIONS

5.1.3 Identity of things

The IOTA project is offering its contribution to the concept of digital twin forIoT devices by supporting the so-called Identity of things. Rather than perceivingmachines/devices as lifeless amalgams of metal and plastic with a specific purpose,they can be considered as having an identity with different attributes associated.A sensor should not only have its unique identifier, but also its accompanyingattributes such as: who manufactured it, when it was deployed, what is the expectedlife time cycle, who owns it now, what kind of sensor data it is gathering, at whatgranularity and many other information. This is imperative for an efficient way toindex and enable the Machine Economy and Industry 4.0 services such as the socalled predictive maintenance.

5.1.4 Masked Authenticated Messaging

As mentioned above, the MAM makes it possible for sensors and other devicesto encrypt entire data streams and securely attach them to the IOTA Tangle ina secure, quantum-proof way. Only authorized parties will be able to read andreconstruct the entire data stream. In essence it works a lot like a radio where onlythose with the right tunercan listen in: with MAM only users in possess of the rightchannel IDs can get access to the data. It is possible to imagine its applicability toindustries such as Supply Chain, Banking and Industry 4.0.

5.1.5 Flash network

Since IOTA is thought for IoT devices, it is possible to perform many transactionsat high speed and finer granularity. It is possible to imagine different scenarios inwhich many transactions can be inserted in a “private” channel between two parties(off tangle) in a faster way. When the channel is closed, a single transaction willbe attached to the Tangle containing the summary of all the transactions includedin the channel. This can be applied, for example, in a car park where each minutea small payment is performed (transaction) by the customer. The off-tangle trans-actions allow to keep track of the payments made, but just the last transactionis stored in the ledger. In this way it is possible to avoid the waste of time andresources for each transaction by doing the proof of work only once at the end.

5.1.6 Qubic and Oracles

Qubic is the last announced set of features for the tangle, a protocol that specifiesIOTA’s solution for oracle machines, smart contracts, outsourced computations,and more. Qubic is still under development. It was announced in June 2018 andsome details about its future implementation and development are coming out inthese days (July 2018). No software is available for practical implementation yet.

59

Page 69: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus
Page 70: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Appendices

60

Page 71: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Appendix A

CAP theorem

This theorem was enounced by Professor Eric Brewer from Berkeley universityduring the Principle of Distributed Computing (PODC).

This theorem describes the trade-off involved in the world of distributed systems.This is the statement of the following theorem:

‘It is impossible for a distributed data store to simultaneously providemore than two out of the following three guarantees: Consistency, Avail-ability, Partition Tolerance.”

61

Page 72: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX A. CAP THEOREM

• Consistency: Every read receives the most recent write or an error;

• Availability : Every request receives a (non-error) response, without guaranteethat it contains the most recent write;

• Partition tolerant : The system continues to operate despite an arbitrary num-ber of messages being dropped (or delayed) by the network between nodes.

A.1 CAP theorem propertiesA correct understanding of the CAP theorem is essential for making the right deci-sions during the design phase of a distributed system. Those are all the properties’definitions:

• Consistency: ability to have a single updated copy of data, on all replicationnodes (serializability);

• Availability: ability of a system to always provide a negative or positive responseto a query;

• Partition tolerant: ability of a distributed system to continue to operate evenin the presence of network errors.

A.1.1 Not consistent

A and B have a complete copy of the data. In the case of a partition, they do notreceive updates from each other and return inconsistent data. This system has theavailability and partition tolerant property (AP) but not the consistent property(C).

62

Page 73: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX A. CAP THEOREM

A.1.2 Not available

A and B use an internal protocol to keep synchronized.In the case of a partition,they can not hear and refuse to respond to requests until they synchronize again.This system has the consistency and partition tolerant property (CP) but not theavailability property (A).

A.1.3 Not partition tolerant

If A and B do not force mutual listening and synchronization, they can respondeven in the presence of a partition. Any updates received from a node while thenetwork was partitioned, are lost. This system has the consistency and availabilityproperty (CA) but not the partition tolerant property (P).

A.2 Consistency in a distributed systemMoving from a centralized to a distributed system, the concept of consistency mustbe reviewed. The consistency model Defines the set of rules that a system mustfollow to guarantee the type of consistency described by the model adopted. The

63

Page 74: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX A. CAP THEOREM

level of consistency between the different operations has a strong impact on theoverall performance of the system and also on its usefulness in a given applicationdomain.

A.2.1 Distributed consistency model

Moving from a centralized to a distributed system, 4 new types of consistency areneeded to be defined:

• Eventual Consistency: sooner or later, all the replicas will have the same copyof the data;

• Session Consistency: within a session, a real order can be guaranteed;

• Casual Consistency: this model guarantees that the operations will be appliedto the datastore in ’causal’ order;

• Serializability: a global order of operations on all is guaranteed on all the replies.Each reading on a data always returns the most updated value of the same.

A.3 BASE property vs ACID propertyFor completeness, I report the definition of ACID propertie.

In computer science, ACID (Atomicity, Consistency, Isolation, Durability) is aset of properties of database transactions intended to guarantee validity even inthe event of errors, power failures, etc. In the context of databases, a sequence ofdatabase operations that satisfies the ACID properties, and thus can be perceivedas a single logical operation on the data, is called a transaction.

• Atomicity: transactions are often composed of multiple statements. Atomicityguarantees that each transaction is treated as a single "unit", which eithersucceeds completely, or fails completely: if any of the statements constitutinga transaction fails to complete, the entire transaction fails and the databaseis left unchanged. An atomic system must guarantee atomicity in each andevery situation, including power failures, errors and crashes;

• Consistency: ensures that a transaction can only bring the database from onevalid state to another, maintaining database invariants: any data written tothe database must be valid according to all defined rules, including constraints,cascades, triggers, and any combination thereof. This prevents database cor-ruption by an illegal transaction, but does not guarantee that a transactionis correct;

• Isolation: transactions are often executed concurrently (eg. reading and writingto multiple tables at the same time). Isolation ensures that concurrent execu-tion of transactions leaves the database in the same state that would’ve beenobtained if the transactions were executed sequentially. Isolation is the maingoal of concurrency control; depending on the method used, the effects of anincomplete transaction might not even be visible to other transactions;

64

Page 75: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX A. CAP THEOREM

• Durability: guarantees that once a transaction has been committed, it will re-main committed even in the case of a system failure (eg. power outage orcrash). This usually means that completed transactions (or their effects) arerecorded in non-volatile memory.

After stating the CAP theorem, E. Brewer proposed the BASE properties asopposed to the existing ACID:

• Basic Available: indicates the ability of a system to guarantee availability interms of the CAP theorem;

• Soft State: indicates that the system state may change over time even withoutinput, due to the eventually model;

• Eventually Consistent: the system will become consistent according to theCAP theorem. For example, all replication nodes will have the same copy ofthe data, in a certain time interval during which the system will not receiveinput from the outside.

Many NoSQL DBs follow the BASE properties just mentioned thus providingthe possibility, to those who use them, to have an architecture capable of scalinghorizontally.

65

Page 76: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Appendix B

EUIPO Blockathon 2018

In the Spring 2018 the EUIPO (EU Intellectual Property Office) organized a com-petition to select the best and most pioneering teams to join a hackathon dedicatedto design innovative solutions for anti counterfeiting based on DLT., The 11 selectedteams gathered in Brussels and worked for three days directly with manufacturers,logistics companies, customs, retailers and consumers. Our team, composed by An-drea Vesco, Michele Osella, Gian Marco Toso, Alberto Buzio, Jure Rosso and mewas selected as 1 of the 11 teams to join this 4-day challenge (22 June 2018 - 25June 2018) in Brussels.

66

Page 77: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX B. EUIPO BLOCKATHON 2018

For this competition we designed and implemented a prototype of an ecosystemto keep track of a product from the producer to the consumer, giving differentgroups of users (end user, logistic operator, custom operator) the possibility tocheck whether the product they handle is original or not. The highlights of thisecosystem was the use of two innovative technologies: IOTA as blockchain-likearchitecture to store trusted and immutable information about the product alongall the process, and a special, unforgeable QR code created by the Italian startupVidiTrust. One such QR code is associated by the manufacturer to each originalproduct. At each step of the shipping process (including the times when the originalproduct is packaged in bigger container or unpacked) the QR code is scanned and theretrieved information is saved in the tangle using a transaction. The IOTA MaskedAuthenticated Message, one of the IOTA expansion modules, offers the possibilityto create a virtual chain by connecting transactions which are part of the samestream. In our project this gives the possibility to follow each product along thewhole logistic path. Since at each scan it is verified the integrity of the product,checking the authenticity of the QR code, and storing the result on the tangle, itis possible to detect where the product has been substituted or counterfeited alongthe entire process. As already described, IOTA offers all the requirements to beused as a DLT to store sensitive information about a product. For this challenge wedeveloped a proof of concept proving how it is possible to read/write from/to thetangle some information about the product. We developed an Android applicationto scan the QR codes using VidiTrust technology and then, passing the results toour server, write the data to the tangle. Then we developed a web-based applicationto read for each product all the information generated by all scanning events, givingthe possibility to analyze all the traffic regarding original or counterfeit products.

67

Page 78: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX B. EUIPO BLOCKATHON 2018

The picture below shows the impact canvas used to illustrate the impacts of thesolution, the go-to-market strategy, and its competitive implications.

The EUIPO Blockathon was a great opportunity to propose the use of IOTA ina real and modern use case.

68

Page 79: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Appendix C

The IOTA Data Marketplace

The Data Marketplace is IOTA’s most comprehensive pilot study thus far. Thegoal is to enable a truly decentralized data marketplace to open up the data silosthat currently keep data limited to the control of a few entities. Data is one of themost imperative ingredients in the machine economy and the connected world.

I was able to participate to the datamarketplace as part of the research team inISMB studying IOTA for my thesis. This project consists in setting up a series ofdevices with some sensors and then using the IOTA Masked Authenticated Messag-ing to post streams of data. As you can see, this project involved most importantcompanies all around the world:

69

Page 80: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX C. THE IOTA DATA MARKETPLACE

Then, after setting up some devices it is possible to use the portal, developed by

70

Page 81: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

APPENDIX C. THE IOTA DATA MARKETPLACE

IOTA developers, to see a little demonstration showing how to buy some interesteddata from the choosen device. You can select a device from a map and then afterclicking on it, if you already bought the data you will see all the history of thatdevice, otherwise you will be asked if you want to buy related data. Here it is anexample of some data bought from my device BerryPi_RuuviTag.

My device is a Raspberry Pi 2 B that reads every 10 minutes some data (tem-perature, humidity, pressure, battery percentage and accelerations of all axes of theaccelerometer) from a RuuviTag device. This Ruuvitag is a device with some sensorthat transmits data over Bluetooth to all devices listening.

71

Page 82: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

Bibliography

[1] Il sole 24Ore cybersicurezzahttp://www.ilsole24ore.com/art/tecnologie/2018-02-26/come-difendersi-minacce-informatiche-guida-sole-cybersicurezza-193316.shtml

[2] IoT data marketplacehttps://blog.iota.org/iota-data-marketplace-cb6be463ac7f

[3] Practical Byzantine Fault ToleranceMiguel Castro, Barbara Liskov, "Practical Byzantine Fault Tolerance", Proceed-ings of the Third Symposium on Operating Systems Design and Implementation,New Orleans, USA, February 1999

[4] HashcashAdam Back. Hashcash, May 1997. Published athttp://www.cypherspace.org/hashcash/

[5] Centralized vs Decentralizedhttps://medium.com/@shyamshankar/centralized-ledgers-vs-distributed-ledgers-layman-understanding-52449264ae23

[6] Telegram Bothttps://telegram.org/blog/bot-revolution

[7] npmjshttps://www.npmjs.com

[8] mullwar/telebothttps://github.com/mullwar/telebot

[9] bitfinex api nodehttps://github.com/bitfinexcom/bitfinex-api-node

[10] france193/IOTAWalletBothttps://github.com/france193/IOTAWalletBot

[11] iotaledger wallethttps://github.com/iotaledger/wallet

[12] iotaledger irihttps://github.com/iotaledger/iri

72

Page 83: POLITECNICO DI TORINO - Home - Webthesis · POLITECNICO DI TORINO Master’s Degree Thesis Computer Engineering - Software ... Differently from the Blockchain paradigm, in IOTA consensus

BIBLIOGRAPHY

[13] iotaledger iota.lib.jshttps://github.com/iotaledger/iota.lib.js

[14] iotaledger docshttps://github.com/iotaledger/docs

[15] iotaledger mam clienthttps://github.com/iotaledger/mam.client.js

[16] iotaledgerhttps://github.com/iotaledger

[17] iota ecosystemhttps://ecosystem.iota.org

[18] iota docshttps://docs.iota.org

[19] iota readmehttps://iota.readme.io/

[20] iota data marketplacehttps://data.iota.org

[21] links foundationhttps://linksfoundation.com/en/

[22] Mastering Bitcoin: Programming the Open Blockchain Paperback AndreasM. Antonopoulos

[23] IOTA whitepaperhttps://iota.org/IOTA_Whitepaper.pdf

73