0% found this document useful (0 votes)
26 views

BlockChain_ project

Jdjdksbsbbb djdbdnjas bhdndjkd. Djdjksksmdbbs snaks nsks djzjasbd bzjzk anskxnnajasdnske sbj s Bahvas z bab asjJ dabashjajbda zbbs sahBsaVha as bzbas da xb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

BlockChain_ project

Jdjdksbsbbb djdbdnjas bhdndjkd. Djdjksksmdbbs snaks nsks djzjasbd bzjzk anskxnnajasdnske sbj s Bahvas z bab asjJ dabashjajbda zbbs sahBsaVha as bzbas da xb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Price ` 300

| 1

B LOC KC HAIN
FOR DEVELOPERS
| 3

Table of Contents
4 The Beauty of the Blockchain.....................................Swapnil Kulkarni

8 Demystifying Blockchains......................................Abhinav Nath Gupta

13 Rout Risk Out of Network.....................Janani Gopalakrishnan Vikram

21 Tools for Blockchain Developers................................. Pragati Aggarwal

24 Developing Blockchain Applications...........................Dr Anand Nayyar

35 Blockchain and Data Security........................................Shakshi Talwar

47 Discover Ethereum........................................................ Prabal Banerjee

44 Hyperledger: An Overview...........................................Swapnil Kulkarni

48 Hyperledger Fabric......................................................Swapnil Kulkarni

54 Transaction Flow in Hyperledger Fabric......................Swapnil Kulkarni

59 Hyperledger Sawtooth Framework..............................Swapnil Kulkarni

63 Hyperledger Iroha........................................................Swapnil Kulkarni

68 Blockchain In The Energy Sector................................ Prashant K. Sing

72 Geospatial Applications of Blockchain...........................Miren Karamta

76 Blockchain and Cloud Storage.........................................Maulik Parekh

79 Applying Blockchain in Gaming Industry...................... Pragati Agrawal

83 IoT Based Management of Shared Resources.............. Venkatachalam


Subramanian and Sumanta Basu

Printed, published and owned by Ramesh Chopra. Published from D-87/1, Okhla Industrial Area,
Phase I, New Delhi 110020. Copyright © 2019. All content in this book, except for interviews, verbatim
quotes, or unless otherwise explicitly mentioned, will be released under Creative Commons Attribution-
NonCommercial 3.0 Unported License. Refer to http://creativecommons.org/licenses/by-nc/3.0/ for
a copy of the licence. Although every effort is made to ensure accuracy, no responsibility whatsoever is
taken for any loss due to publishing errors. The content published in this book was first published in the
print edition of Open Source For You Magazine. Disputes, if any, will be settled in a New Delhi court only.
4|

Chapter 1

The Beauty of the Blockchain


The meteoric rise in the value of bitcoins has put a spotlight
on the blockchain, which is the primary public, digital ledger for
bitcoin transactions. A blockchain allows digital transactions to be
transparent and distributed, but not copied. It is thought to be the
brainchild of an anonymous person or group operating under the
pseudonym Satoshi Nakamoto.

The bitcoin network has attracted attention from almost all industries and
experts due to its variable market value. These captains of industry and the
experts are trying to figure out how this technology can be adapted to and
integrated with their work. The dictionary definition of blockchain is, “A digital
ledger in which transactions made in bitcoin or another cryptocurrency are
recorded chronologically and publicly.” This definition is derived from the
most popular implementation of blockchain technology—the bitcoin. But
blockchain is actually not bitcoin. Let’s have a look at blockchain technology,
in general.

Distributed ledger technology (DLT)


Distributed ledger technology includes blockchain technologies and smart
contracts. While DLT existed prior to bitcoin or blockchain, it marks the
convergence of a host of technologies, including the time-stamping of
transactions, peer-to-peer (P2P) networks, cryptography, shared computational
power, as well as a new consensus algorithm. In short, distributed ledger
technology is generally made up of three basic components:
ƒƒ A data model that captures the current state of the ledger.
ƒƒ A language of transactions that changes the ledger state.
ƒƒ A protocol used to build consensus among participants around which
transactions will be accepted by the ledger and in what order.

What is blockchain technology?


Blockchain is a specific form or sub-set of distributed ledger technologies,
which constructs a chronological chain of blocks; hence the name ‘blockchain’.
Chapter 1: The Beauty of the Blockchain | 5

A block refers to a set of transactions that is bundled together and added


to the chain at the same time. A blockchain is a peer-to-peer distributed
ledger, forged by consensus, combined with a system for smart contracts
and other assistive technologies. Together, these can be used to build a new
generation of transactional applications that establish trust, accountability
and transparency at their core, while streamlining business processes and
legal constraints. The blockchain then tracks various assets, the transactions
are grouped into blocks, and there can be any number of transactions per
block. A block commonly consists of the following four pieces of metadata:
ƒƒ The reference to the previous block
ƒƒ The proof of work, also known as a nonce
ƒƒ The time-stamp
ƒƒ The Merkle tree root for the transactions included in this block

Is a blockchain similar to a database?


Blockchain technology is different from databases in some key aspects. In a
relational database, data can be easily modified or deleted. Typically, there
are database administrators who may make changes to any part of the data
or its structure and even to relational databases. A blockchain, however, is
a write-only data structure, where new entries get appended onto the end
of the ledger. There are no administrator permissions within a blockchain
that allow the editing or deleting of data. Also, the relational databases
were originally designed for centralised applications, where a single entity
controls the data. In contrast, blockchains were specifically designed for
decentralised applications.

Types of blockchains
A blockchain can be both permissionless (e.g., bitcoin and Ethereum) or
permissioned, like the different Hyperledger blockchain frameworks. The
choice between permissionless and permissioned blockchains is driven by
the particular use case.

Block 1 Block 2 Block 3


Header Header Header

Hash of Previous Hash of Previous Hash Of Previous


Block Header Block Header Block Header

Market Root Market Root Market Root

Block 1 Block 2 Block 3


Transactions Transactions Transactions

Figure 1: Structure of a block in the chain


6 | Chapter 1: The Beauty of the Blockchain

A permissionless blockchain is also known as a public blockchain,


because anyone can join the network. A permissioned blockchain, or private
blockchain, requires pre-verification of the participants within the network,
who are usually known to each other.

Characteristics of blockchains
Here is a list of some of the well-known properties of blockchains.
ƒƒ Immutability of data
The immutability of the data which sits on the blockchain is perhaps the most
powerful and convincing reason to deploy blockchain-based solutions for a
variety of socio-economic processes that are currently recorded on centralised
servers. This ‘unchanging over time’ feature makes the blockchain useful
for accounting and financial transactions, in identity management and in
asset ownership, management and transfer, just to name a few examples.
Once a transaction is written onto the blockchain, no one can change it or,
at least, it would be extremely difficult to do so.
ƒƒ Transparency
Transparency of data is embedded within the network as a whole. The
blockchain network exists in a state of consensus, one that automatically
checks in with itself. Due to the structure of a block, the data in a blockchain
cannot be corrupted; hence altering any unit of information in it is almost
impossible. Though, in theory, this can be done by using a huge amount of
computing power to override the entire network, this is not possible practically.
ƒƒ Decentralisation
By design, the blockchain is a decentralised technology. Anything that
happens on it is a function of the network, as a whole. A global network of
computers uses blockchain technology to jointly manage the database that
records transactions. The consensus mechanism discussed next ensures
the correctness of data stored on the blockchain.
ƒƒ Security
By storing data across its network, the blockchain eliminates the risks that
come with data being held centrally, and the network lacks centralised points
of vulnerability that are prone to being exploited. The blockchain ensures all
participants in the network use encryption technologies for the security of
the data. Primarily, it uses PKI (public key infrastructure), and it is up to the
participants to select other encryption technologies as per their preference.

What are consensus mechanisms and the types of consensus


algorithms?
Consensus is an agreement among the network peers; it refers to a system
of ensuring that participants agree to a certain state of the system as the
true state. It is a process whereby the peers synchronise the data on the
blockchain. There are a number of consensus mechanisms or algorithms.
Chapter 1: The Beauty of the Blockchain | 7

One is Proof of Work. Others include Proof of Stake, Proof of Elapsed Time
and Simplified Byzantine Fault Tolerance. Bitcoin and Ethereum use Proof
of Work, though Ethereum is moving towards Proof of Stake.

What are smart contracts?


Back in 1996, a man named Nick Szabo coined the term ‘smart contract’. You
can think of it as a computer protocol used to facilitate, verify, or enforce the
negotiation of a legal contract. A smart contract is a phrase used to describe
computer code. Smart contracts are simply computer programs that execute
predefined actions when certain conditions within the system are met. Smart
contracts provide the language of transactions that allows the ledger state
to be modified. They can facilitate the exchange and transfer of anything of
value (e.g., shares, money, content and property).

Open source blockchain frameworks, projects and communities


Looking at the current state of research and some of the implementations of
blockchain technologies, we can certainly say that most enterprise blockchain
initiatives are backed by open source projects. Here’s a list of some of the
popular open source blockchain projects.
ƒƒ Hyperledger is an open source effort created to advance cross-industry
blockchain technologies. Hosted by the Linux Foundation, it is a global
collaboration of members from various industries and organisations.
ƒƒ Quorum is a permissioned implementation of Ethereum, which supports
data privacy. Quorum achieves data privacy by allowing data visibility
on a need-to-know basis, using a voting-based consensus algorithm.
Interestingly, Quorum was created and open sourced by J.P. Morgan.
ƒƒ Chain Core, created by chain.com, was initially designed for financial
services institutions and for things like securities, bonds and currencies.
ƒƒ Corda is a distributed ledger platform designed to record, manage and
automate legal agreements between businesses. It was created by the
R3 Company, which is a consortium of over a hundred global financial
institutions.
8|

Chapter 2

Demystifying Blockchains
A blockchain is a continuously growing list of records, called blocks, which
are linked and secured using cryptography to ensure data security.

Data security is of paramount importance to corporations. Enterprises need


to establish high levels of trust and offer guarantees on the security of the
data being shared with them while interacting with other enterprises. The
major concern of any enterprise about data security is data integrity. What
many in the enterprise domain worry about is, “Is my data accurate?”
Data integrity ensures that the data is accurate, untampered with and
consistent across the life cycle of any transaction. Enterprises share data
like invoices, orders, etc. The integrity of this data is the pillar on which
their businesses are built.

Blockchain
A blockchain is a distributed public ledger of transactions that no person
or company owns or controls. Instead, every user can access the entire
blockchain, and every transaction from any account to any other account, as
it is recorded in a secure and verifiable form using algorithms of cryptography.
In short, a blockchain ensures data integrity.
A blockchain provides data integrity due to its unique and significant
features. Some of these are listed below.
Timeless validation for a transaction: Each transaction in a blockchain
has a signature digest attached to it which depends on all the previous
transactions, without the expiration date. Due to this, each transaction
can be validated at any point in time by anyone without the risk of the data
being altered or tampered with.
Highly scalable and portable: A blockchain is a decentralised ledger
distributed across the globe, and it ensures very high availability and
resilience against disaster.
Tamper-proof: A blockchain uses asymmetric or elliptic curve
cryptography under the hood. Besides, each transaction gets added to the
blockchain only after validation, and each transaction also depends on the
Chapter 2: Demystifying Blockchains | 9

previous transaction. Hence, a blockchain is nearly impossible to tamper


with without anyone noticing.

Demystifying blockchains
A blockchain, in itself, is a distributed ledger and an interconnected chain
of individual blocks of data, where each block can be a transaction, or a
group of transactions.
In order to explain the concepts of the blockchain, let’s look at a code
example in JavaScript. The link to the GitHub repository can be found at
https://github.com/abhiit89/Ang Coins. So do check the GitHub repo and
go through the ‘README’ as it contains the instructions on how to run
the code locally.
Block: A block in a blockchain is a combination of the transaction data
along with the hash of the previous block. For example:

class Block {
constructor(blockId, dateTimeStamp, transactionData, previousTransactionHash) {
this.blockId = blockId;
this.dateTimeStamp = dateTimeStamp;
this.transactionData = transactionData;
this.previousTransactionHash = previousTransactionHash;
this.currentTransactionHash = this.calculateBlockDigest();
}

The definition of the block, inside a blockchain, is presented in the above


example. It consists of the data (which includes blockId, dateTimeStamp,
transactionData, previousTransactionHash, nonce), the hash of the data
(currentTransactionHash) and the hash of the previous transaction data.
Genesis block: A genesis block is the first block to be created at the
beginning of the blockchain. For example:

new Block(0, new Date().getTime().valueOf(), ‘First Block’, ‘0’);

Adding a block to the blockchain


In order to add blocks or transactions to the blockchain, we have to create a
new block with a set of transactions, and add it to the blockchain as explained
in the code example below:

addNewTransactionBlockToTransactionChain(currentBlock) {
currentBlock.previousTransactionHash = this.returnLatestBlock().currentTransactionHash;
currentBlock.currentTransactionHash = currentBlock.calculateBlockDigest();
this.transactionChain.push(currentBlock);
}
10 | Chapter 2: Demystifying Blockchains

In the above code example, we calculate the hash of the previous transaction
and the hash of the current transaction before pushing the new block to the
blockchain. We also validate the new block before adding it to the blockchain
using the method described below.

Validating the blockchain


Each block needs to be validated before it gets added to the blockchain. The
validation we used in our implementation is described below:

isBlockChainValid() {
for (let blockCount = 1; blockCount < this.transactionChain.length; blockCount++) {
const currentBlockInBlockChain = this.transactionChain[blockCount];
const previousBlockInBlockChain = this.transactionChain[blockCount - 1];
if (currentBlockInBlockChain.currentTransactionHash !== currentBlockInBlockChain.
calculateBlockDigest()) {
return false;
}

if (currentBlockInBlockChain.previousTransactionHash !== previousBlockInBlockChain.


currentTransactionHash) {
return false;
}

}
return true;
}

In this implementation, there are a lot of features missing as of now,


like validation of the funds, the rollback feature in case the newly added
block corrupts the blockchain, etc. If anyone is interested in tackling fund
validation, the rollback or any other issue they find, please go to my GitHub
repository, create an issue and the fix for it, and send me a pull request
or just fork the repository and use it whichever way this code suits your
requirements.
A point to be noted here is that in this implementation, there are numerous
ways to tamper with the blockchain. One way is to tamper with the data
alone. The implementation for that is done in the branch https://github.
com/abhiit89/AngCoins/tree/tampering_data.
Another way is to not only change the data but also update the hash.
Even then the current implementation can invalidate it. The code for it
is available in the branch https://github.com/abhiit89/AngCoins/tree/
tampering_data_with_updated_hash.
Chapter 2: Demystifying Blockchains | 11

Proof of work
With the current implementation, it is still possible that someone can spam
the blockchain by changing the data in one block and updating the hash
in all the following blocks in the blockchain. In order to prevent that, the
concept of the ‘proof of work’ suggests a difficulty or condition that each
block that is generated has to meet before getting added to the blockchain.
This difficulty prevents very frequent generation of the block, as the hashing
algorithm used to generate the block is not under the control of the person
creating the block. In this way, it becomes a game of hit and miss to try to
generate the block that meets the required conditions.
For our implementation, we have set the difficult task that each block
generated must have two ‘00’ in the beginning of the hash, in order to be
added to the blockchain. For example, we can modify the function to add
a new block to include the difficult task, given as below:

addNewTransactionBlockToTransactionChain(currentBlock) {
currentBlock.previousTransactionHash = this.returnLatestBlock().currentTransactionHash;
currentBlock.mineNewBlock(this.difficulty);
this.transactionChain.push(currentBlock);
}
This calls the mining function (which validates the difficult conditions):

mineNewBlock(difficulty) {
while(this.currentTransactionHash.substring(0, difficulty) !== Array(difficulty + 1).join(‘0’)) {
this.nonce++;
this.currentTransactionHash = this.calculateBlockDigest();
}
console.log(‘New Block Mined --> ‘ + this.currentTransactionHash);
}

The complete code for this implementation can be seen in the branch
https://github.com/abhiit89/AngCoins/tree/block_chain_mining.

Blockchain providers
Blockchain technology, with its unprecedented way of managing trust and
data and of executing procedures, can transform businesses. Here are some
open source blockchain platforms.
HyperLedger: Hyperledger nurtures and endorses a wide array of
businesses around blockchain technologies, including distributed ledgers,
smart contracts, etc. Hyperledger encourages the re-use of common building
blocks and enables the speedy invention of distributed ledger technology
components.
12 | Chapter 2: Demystifying Blockchains

Project link: https://hyperledger.org/projects


Project GitHub link: https://github.com/hyperledger
Openchain: Openchain is an open source distributed ledger technology.
It is ideal for enterprises, and deals in issuing and managing digital assets
in a robust, secure and scalable way.
Project link: https://www.openchain.org/
Ethereum project: This is a distributed framework that runs smart
contracts—applications that run exactly as programmed in a secured
virtual environment without downtime or the possibility of tampering, as
this platform leverages the custom built blockchain.
Project link: https://www.ethereum.org/
There are some more blockchain projects, links to which can be found
in the References section.
| 13

Chapter 3

Rout Risk Out of Network


Transactions

Ripple, a blockchain based technology startup, is sitting on a venture capital


of US$ 93 million, sourced from an interesting mix of funders ranging from
Google Ventures and Seagate Technology to a horde of banks like Standard
Chartered. Ripple’s network already has 15 global banks, and 10 more are
waiting to board the train. Shanghai Huarui Bank, a privately-owned bank
in China, is working with Ripple to implement a commercial cross-border
payment service, so customers can transfer money internationally in real
time. The bank feels it will help Chinese families to send money to their
children studying abroad.
What is Ripple’s offering that promises such confidence in the network?
What is this technology, which interests not just banks but Web giants and
the tech industry as well? In two words, the answer is blockchain technology.
Bank investment in blockchain technology is expected to reach US$ 400
million by 2019. This is because of the confidence that blockchain technology
has the potential to ensure completely secure and tamper-proof transactions,
in scenarios ranging from smart contracts and real-time international money
transfer to contactless payments. Early blockchain systems had their share
of problems like settlement lag and lack of privacy, but the current generation
of startups is bent upon delivering enterprise-grade blockchain.

Demystifying the blockchain


You do not have to feel bad if you have already Googled for blockchain and
not made head or tail of it. Even finance and tech experts take some time to
understand this concept, and even more time to explain it confidently. As with
most nascent technologies, it is difficult to differentiate the technology from
its applications, and understand it for what it really is, what it is currently
used for and what else it can do.
14 | Chapter 3: Rout Risk Out of Network Transactions

A blockchain is a decentralised, distributed public ledger that records,


validates and secures transactions in a system. As is obvious from the name,
a blockchain is made of several blocks. Each block contains encrypted data
pertaining to a transaction, along with a hash that draws upon the previous
block in the chain.
This way of connecting each cryptographically-hashed block with the
previous one ensures that all data in the chain remains secure and unchanged.
There is no single owner of any transaction—each transaction is authorised
and backed by thousands of computers (called miners)—and so there is no
single point that can be attacked or hacked.

“Blockchain technology continues to redefine not only


how the exchange sector operates, but the global financial
economy as a whole.”
—Bob Greifeld,chief executive officer, NASDAQ

That is what makes blockchain based transactions secure and tamper-


proof. Using blockchain technology, it is possible to carry out peer-to-peer
transactions over the Internet, without requiring middlemen like payment
gateways to authorise transactions.
“The block records some or all of the current transactions, and once it
is completed, the block is time-stamped and hashed into the permanent
database or blockchain.
“The blocks are linked to each other in a linear, chronological order
where each new block contains the hashed details of the previous block.
This creates a chain of transactional information, so that every block that is
added protects information in the previous one,” explains Kumar Abhishek,
founder and CEO of ToneTag, a sound based proximity communication
provider that enables contactless proximity communication, mobile
payments, location based services, customer engagement services and
more. The company recently adopted blockchain technology to make its
transactions more secure.
Do Bitcoin, blockchain and distributed ledger technology (DLT) mean
the same? People tend to use these terms interchangeably, much like they
use Xerox to mean photocopier, but these are not the same.
A distributed ledger refers to a consensus of replicated, shared and
synchronised data that is distributed across multiple locations, often spanning
several institutions and individuals across the globe.
Bitcoin is one of the most well-known and earliest proven applications
of DLT. It is a decentralised digital currency that enables you to make
instant payments to anyone, anywhere in the world, without requiring
any middlemen.
Chapter 3: Rout Risk Out of Network Transactions | 15

It is decentralised, that is, transaction management and money issuance


are carried out collectively by the network. This is where the blockchain
comes in. Devised as a method to keep track of all confirmed Bitcoin
transactions, the blockchain is one type of distributed ledger in which data
is distributed as blocks that form a linear chain with each one connected
to the previous.
As explained in Bitcoin wiki, “Bitcoin uses public-key cryptography,
peer-to-peer networking and proof-of-work to process and verify payments.
Bitcoins are sent (or signed over) from one address to another with each
user potentially having many, many addresses. Each payment transaction is
broadcast to the network and included in the blockchain so that the included
bitcoins cannot be spent twice. After an hour or two, each transaction is
locked in time by the massive amount of processing power that continues to
extend the blockchain. Using these techniques, Bitcoin provides a fast and
extremely reliable payment network that anyone can use.”

Fig. 1: Blockchain technology ensures completely secure and tamper-proof


transactions in various scenarios (Image courtesy: ToneTag)
16 | Chapter 3: Rout Risk Out of Network Transactions

There are applications other than Bitcoin that use blockchain technology.
And that blockchain is not the only form of DLT; there are others like
Ethereum, Ripple, Hyperledger and MultiChain. But, by virtue of being the
earliest and most famous example, Bitcoin, blockchain and DLT are used
synonymously by many, and that is not always right.
In fact, blockchain technology can be used to develop apps more advanced
than just supporting digital currency. This evolution is often known as
Blockchain 2.0.
ToneTag’s blockchain approach. “Blockchain was implemented as a
way to keep record of all Bitcoin transactions. The payment system enables
users to pay each other directly, without having to rely on a third party.
Since Bitcoin is a digital cryptocurrency, it cannot be contained physically.
There had to be an effective way to manage all transactions in the system,
without giving control to any single party. This is where blockchain comes in.
It is a distributed public ledger that records all transactions in a particular
system,” says Abhishek.
ToneTag follows a similar approach to Bitcoin blockchain, but the application
varies. The way in which payment transactions are recorded at present is
inefficient. The current system involves many entities and players, which
leaves greater room for fraud. Every year hundreds of billions of dollars are
lost due to fraudulent transactions. To address these security issues, ToneTag
introduced blockchain technology to contactless payments. Blockchain
technology has the potential to completely redefine the way transactions
take place, as it brings unprecedented advancements in fraud prevention.
“ToneTag payments are tokenised, where a unique identifier replaces
sensitive transaction information and none of the actual customer or
merchant transaction information is revealed or shared, hence making the
entire process highly-secure and fraud-proof,” says Abhishek.
ToneTag enables contactless payments that are traceable, transparent
and secure. Every party involved in the transaction is protected by the
blockchain since it maintains a public record of every transaction that ever
took place in the system. While paying through ToneTag, customers can
identify whether the merchant outlet they are dealing with is exposed to
risks or if it has witnessed fraudulent transactions in the past. Similarly,
merchants can ensure whether a customer is genuine or not. Further, all
transactions are validated to ensure these are authorised.

Miners, the quiet workers


We keep saying that, in a distributed ledger, data is stored in a distributed,
decentralised way, spanning multiple digital locations across the globe. What
makes this possible? The answer is mining.
Mining is the distributed computational review process performed on each
block of data in a blockchain, which allows a consensus to be achieved despite
Chapter 3: Rout Risk Out of Network Transactions | 17

each party not knowing or


trusting the other.
Let us take the example
of Bitcoin to understand
this better. In order to
conduct a transaction, a
Bitcoin user has to sign
it with his private key or
seed. This helps prove
that the transaction has
been initiated by the right
person, and also prevents
third parties from altering
the transaction in any way.
After this, the transaction
is confirmed through a
process of mining and then
included in the blockchain.
According to Bitcoin, “To
be confirmed, transactions
must be packed in a
block that fits very strict
cryptographic rules that
are verified by the network.
These rules prevent
previous blocks from being
modified because doing so
would invalidate all the
following blocks.
“Mining also creates
the equivalent of a
competitive lottery that
prevents any individual
from easily adding new
blocks consecutively in
the block chain. This way,
no individuals can control
what is included in the
blockchain or replace parts
of it to roll back their own
spends.”
Mining makes computer
hardware do mathematical
18 | Chapter 3: Rout Risk Out of Network Transactions

calculations for the Bitcoin network to confirm transactions and increase


security. Any computer across the world can be a miner. As a reward for
sharing their computational power, miners get a fee for each transaction
confirmed by them, along with newly-created bitcoins. The reward depends
on the amount of mining done. There are strict rules and procedures for
this, and mining is not to be thought of as an easy way to make money.
Blockchain mining hardware. The blockchain mining process is mostly
software based. In reality, anybody can become a miner using their personal
computer. However, the speed and reliability demanded by upcoming
mining protocols pose an opportunity for hardware innovation. We now have
industrial-grade mining hardware (servers in data centres) and specialised
application-specific integrated circuits (ASICs) for mining.
Antminer, Avalon6, SP20 Jackson and 21 Bitcoin Chip are some well-
known ASICs for mining. Experts say you have to look at hash rate, efficiency
and price when selecting a mining chip. Hash rate is the number of hashes
per second that the Bitcoin miner can make. Usually, if the hash rate is
more, the price will be higher. So you have to balance it with efficiency,
which measures the electricity usage. This is important because miners
usually consume a lot of power. Remember, we told you it is not an easy
way to make money!
21 Inc. has come up with something more than ASICs. 21 Bitcoin
computer is claimed to be the first computer with native hardware and
software support for Bitcoin protocol. According to the company, it has the
hardware to mine a stream of small amounts of Bitcoins for development
purposes, and the software to make that Bitcoin useful for buying and
selling digital goods. It can be used by developers and individual miners
to create Bitcoin based apps, services and devices.
Embedded blockchain mining is a very nascent idea, which involves
embedding mining chips into different kinds of Internet-connected devices.
Last year, 21 Inc. revealed its plans to develop a chip (called 21 BitShare)
that can be embedded into mobile phones, enabling them to silently mine
in the background.
Another innovation from 2015, by Patric Lanhed and Juanjo Tara, is a
chip that can be implanted in your hands for Bitcoin bio-payment. They have
gone a bit overboard, but it might be a glimpse of what the future holds. You
never have to worry about forgetting your purse or phone at home, when
tapping your hand can complete a payment.
Bit more than Bitcoin
Undoubtedly, Bitcoin, allegedly invented by Satoshi Nakamoto in 2008,
is one of the best-known names in distributed ledger and blockchain
technologies, but it is not the only one. Of late, there has been a lot of interest
in this space, and many alternatives have come up. Here is a quick look at
some of the contenders:
Chapter 3: Rout Risk Out of Network Transactions | 19

Ethereum. Ethereum is a decentralised platform that runs smart


contracts. These are apps that run on a custom-built blockchain, with a
platform-specific cryptographic token called Ether. The blockchain can
move value as well as represent ownership of property. According to the
company, “This enables developers to create markets, store registries of
debts or promises, move funds in accordance with instructions given long
in the past (like a will or a futures contract) and many other things that
have not been invented yet, all without a middle man or counter-party risk.”
Online reviews show that Ethereum transactions are confirmed in
seconds compared to minutes for Bitcoin.
Another key difference is that Ethereum uses ethash, while Bitcoin uses
secure hash algorithm SHA-256.
The two platforms also differ in purpose. While Bitcoin was intended to
be an alternative to regular money, Ethereum is meant as a platform that
facilitates peer-to-peer contracts and applications via its own currency vehicle.
The focus of Ethereum is not to replace regular money but to facilitate and
monetise the working of Ethereum to enable developers to build and run
distributed applications.
Ripple. Ripple aims to be a global settlement network to facilitate instant,
certain, low-cost international payments. According to the company, Ripple’s
distributed network allows foreign exchange to be externally sourced from
a competitive foreign exchange marketplace or an internal foreign exchange
trading desk via Ripple’s FX Market Making Solution.
The backbone of Ripple’s network is Ripple Consensus Ledger (RCL), a
secure distributed ledger that uses the consensus process to settle transactions.
Like other blockchain technologies, it does not require a middleman, and is
very secure. The RCL holds the order book with bid/ask offers from payment
initiators and market makers. Its path-finding algorithm enables it to find
the lowest foreign exchange rate across all order books and currency pairs.
It is basically a DLT, but with a specific purpose, which makes it more
enterprise-ready.
Ripple aims to solve specific problems, which banks are likely to have
with other public ledger based systems, such as delay in confirming
transactions and lack of privacy. Ripple takes just three to five seconds to
confirm a transaction through consensus among validators, as it does not
use a proof-of-work method.
To solve the privacy problem, it advocates the use of Interledger Protocol
(ILP), which can work with any bank or non-traditional payment network,
regardless of its underlying technology.
ILP is an emerging standard that provides all benefits of public and
private blockchains, while also ensuring that transaction data remains
private to only the transacting parties. Ripple feels that ILP is a much better
approach than private, bank-sponsored blockchains, as the latter approach
20 | Chapter 3: Rout Risk Out of Network Transactions

can lead to a further fragmentation of payment networks.


Hyperledger. Hyperledger is a collaborative effort to develop a cross-
industry open standard for distributed ledgers. The current implementation
employs Bitcoin UTXO transaction model, which uses a system of public
and private keys to ensure that transactions remain uncompromised while
travelling to their destination. As of now, Hyperledger does not have any
native currency. They believe that the technology will be useful for syndicated
loans and capital markets infrastructure.
MultiChain. An interesting innovation, MultiChain is a platform that lets
banks and other organisations develop their own blockchain. Customers
can customise various aspects of the blockchain such as whether it is
private or public, target time for blocks, who can connect to the network,
how they interact, maximum block size, metadata that can be included in
transactions and so on.
They also have their own improvised mining technique called mining
diversity. The process enables miners to approve transactions in a random
rotation. The company claims that this structure allows more miners to
participate in the approval of transactions, while ensuring there is no fixed
order of verification that could be corrupted.
India can benefit from blockchain technology
Every other day, there is a press release about a new DLT or platform.
It is clear that it will play a key role in the future of the finance industry.
“For the financial services sector in India or abroad, blockchain offers the
opportunity to overhaul existing banking infrastructure, speed up settlements,
organise assets and streamline stock exchanges, although regulators want to
be assured that it can be done securely. According to Santander, the banking
industry could save about US$ 20 billion every year with the implementation
of blockchain processes,” explains Abhishek.
“According to many evangelists, the possibilities are limitless. Applications
range from storing client identities to handling cross-border payments, clearing
and settling bond or equity trades to smart contracts that are self-executing,
such as a credit derivative that pays out automatically if a company goes
bust, or a bond that regularly pays interest to the holder,” he adds.
The emergence of enterprise-grade DLTs including highly customisable
blockchains and enthusiastic support that banks and tech majors are
extending to such companies make it clear that DLT is the way ahead for
the financial services sector.
| 21

Chapter 4

Tools for Blockchain Developers


Developers need to arm themselves with special tools when working on
blockchain technology. Let us explore some of these tools that are useful
for developers working on the Bitcoin or Ethereum networks.

Blockchain technology envisions a future of making every centralised process,


activity and organisation fully autonomous. It is immutable, encrypted,
decentralised and has the potential to eliminate intermediaries, authorities
and any third-party intervention in all applications. No wonder blockchain
developers are considered as real unicorns in the industry right now as a lot
of companies, especially startups, are looking for their expertise. However,
only a handful of them work on this technology today.
To work with blockchain technology you do not need to build a blockchain
from scratch. You can use the already existing networks like Bitcoin, Ethereum
or Hyperledger. While Bitcoin and Ethereum are both decentralised, open
source and public, Hyperledger is private but open source. Both Bitcoin and
Ethereum are different and you must choose between them based on your
application. Ethereum is suitable for building decentralised applications
(DApps) while Bitcoin is not really a good choice for DApps as it was designed
for peer-to-peer transactions.

Blockchain as a Service
The main goal of Blockchain as a Service (BaaS) is to offer the backend
capabilities needed by blockchain solutions. The BaaS offered by different
companies supports several chains including MultiChain, Eris, Storj and
Augur. One of the advantages of BaaS is that users can leverage the lessons
learned by the service provider to make their system more secure. The key
players offering BaaS are Microsoft, IBM, HP and Oracle.

Platforms for writing smart contracts


One of the most common languages used for writing smart contracts is
Solidity, for which Solc is the compiler. Most of the Ethereum nodes natively
22 | Chapter 4: Tools for Blockchain Developers

include a Solc implementation but the latter is available as a separate


module for offline compiling.
Another programming language used to write smart contracts is Serpent,
for which the Ether scripter helps you to write the script or code. The latest
version of the Serpent compiler is available on GitHub.

Testnet
Testnet is an alternative blockchain, the coins of which do not carry
any value and are easy to obtain. These allow application developers
to test their creations before taking them to production. Testnet offers
developers a sandbox environment to experiment in without having to
use real cryptocurrency or worrying about breaking the main chain. Both
Ethereum and Bitcoin have different criteria for the blockchain Testnet.
To work on the Bitcoin Testnet, you must generate a differently formatted
Testnet Bitcoin address which always begins with ‘m’ or ‘n’. For Ethereum,
the same address can work on both the Testnet and main net; hence, you
need to be careful to not to mix them.
Among the two common ways to obtain Testnet coins easily, the first is
by solving cryptographic puzzles. These Testnet chains have fewer miners
and the level of difficulty is low, which makes it easier to find the solution
for a hash puzzle to obtain a block reward. The other way to get these
Testnet coins is by using faucets. These are the websites that dispense a
small amount of Testnet coins in exchange for completing some task for
their website.

Mist
Most people get confused as there are two terms related to Mist in Ethereum.
The Mist-Ethereum wallet is the one that is most commonly used. The
name, Mist, is also used for the browser. The Mist-Ethereum wallet allows
you to store and send your ether. It is different from the Ethereum wallet,
which is online. Whereas Mist runs from your computer and must be
downloaded to be used.
The Mist browser is a special-purpose browser that offers an overall view
of the Ethereum blockchain and all the tools that are needed to interact
in blockchain components like ether, DAO and smart contracts. However,
it is still at the beta stage.
The Mist browser was introduced to build the third-generation Web
(3.0), which envisages eradicating centralised servers and using Ethereum,
Whisper and Swarm as their replacements.
Chapter 4: Tools for Blockchain Developers | 23

Coinbase API
Coinbase API allows you to build new Bitcoin apps as well as integrate Bitcoin
into already existing applications. The system provides a wide range of
capabilities — from gathering read-only data to building something completely
new. It also offers a system to create Bitcoin wallets and addresses, as well
as to buy, sell, send and receive Bitcoins worldwide. It provides several
client libraries and mobile software development kits (SDK) for developers.
It allows developers to access and integrate the functionality of Coinbase
with other applications.

Tierion
Tierion is used by developers to anchor data to the blockchain to prove the
integrity and provide the timestamp of any data. It offers developer tools
and APIs to add data to a distributed ledger. It also has an open standard
called ChainPoint, which allows the user to record and generate receipts
that contain all the information needed to verify data and avoids the need
to rely on intermediaries.
24 |

Chapter 5

Developing Blockchain Applications


Since the phenomenal rise in the value of the cryptocurrency Bitcoin, which
uses a blockchain for accounting, there has been a tremendous interest
in blockchain technology. A blockchain is a transparent distributed ledger
which is revolutionising the financial services industry by empowering
millions across the globe to authenticate and transact immediately, without
the involvement of expensive intermediaries. This article introduces a few
popular open source platforms that help in the quick and easy development
of blockchain based applications.

Blockchain technology is termed as the ‘Fifth Evolution’ of computing. A


blockchain is regarded as a novel approach to distributed databases. It is a
disseminated database of open records which documents all transactions or
advanced events that have been executed prior to that point in time when
it is shared among participating members. Every transaction in the public
record is confirmed by agreement by a larger number of members within
that framework.
These days, transactions between persons or companies are often
centralised and controlled by a third party organisation. Making a digital
payment or currency transfer requires a bank or credit card provider as the
middleman to complete the transaction. In addition, a transaction attracts a
fee from banks or credit card companies. The same process applies to other
application domains like games, software, etc. The transaction system is
centralised, and all data and information are controlled and managed by a
third party organisation, rather than the two principal participants in the
transaction. Blockchain technology has been developed to solve this issue.
Chapter 5: Developing Blockchain Applications | 25

A blockchain is a data structure that makes it possible to create a digital


ledger of data and share it among a network of independent parties. The
ultimate goal of blockchain technology is to create a decentralised environment
where no third party is in control of the data and the transactions. A
blockchain is a distributed database solution that maintains a growing
list of data records that are confirmed by the nodes participating in it.
The data is recorded in a public ledger, which includes all the information
about every transaction ever completed. This information is shared and
available to all nodes. This, in turn, makes the blockchain system more
transparent and leaves no room for third parties.
Blockchains are secure by design and include sophisticated distributed
computing systems with high Byzantine Fault Tolerance. Blockchain
technology was invented by Satoshi Nakamoto in 2008 to serve as a public
transaction ledger of the cryptocurrency called Bitcoin. The invention of the
blockchain for Bitcoin made it the first digital currency to solve the double-
spending problem without any need for a centralised server or third party
trusted authority.
Till date, Bitcoin is still the most commonly used application using
blockchain technology. Bitcoin is a decentralised digital currency payment
system that consists of a public transaction ledger called a blockchain.
There are many different kinds of blockchains.
ƒƒ Public blockchain: Public blockchains are like Bitcoins, which are large
distributed networks that are run through a native token. They are open
for the public to participate at any level and have open source code that
the community maintains.
ƒƒ Permissioned blockchains: Permissioned blockchains like Ripple control
roles that individuals can play within the network. They are still large and
distributed systems that use a native token. Their code may or may not
be open source.
ƒƒ Private blockchains: Private blockchains tend to be smaller and don’t
use a token. Their membership is closely controlled. These types of
blockchains are favoured by consortiums that have trusted members
and trade in confidential information.
All the above blockchains use cryptography to allow every participant
on any given network to manage the ledger in a secure way, without the
need for any central authority to enforce the rules.

The underlying principles of the blockchain


The following are the five basic principles underlying the technology.
1. Distributed database: Every participant on the blockchain has access
to the entire database and its complete history. No single participant
controls the data or information and every one of them can verify the
records of the transaction partners directly, without any intermediary.
26 | Chapter 5: Developing Blockchain Applications

How a blockchain works


1 2 3
A wants to send The transaction is The block is broadcast to
money to B represented online every party in the network
as a ‘block’

4 5 6
those in the network The block then can be added The money moves
approve the to the chain, which provides from A to B
transation is valid an indelible and transparent
record of transactions

Figure 1: How a blockchain works

2. Peer-to-peer transmission: Communication occurs directly between


peers instead of through a central node. Every node stores and forwards
information to all the other nodes.
3. Transparency with pseudonymity: Every transaction and its associated
value is visible to anyone with access to the system. Every node or user
on a blockchain has a unique 30+ character alphanumeric address that
identifies it. Users can choose to remain anonymous or provide proof
of their identity to others. Transactions take place between blockchain
addresses.
4. Record irreversibility: When the transaction is entered in the database
and the accounts are updated, the records cannot be altered because
they are linked to every transaction record that is previously recorded.
Various types of computational algorithms and proposed approaches
are deployed to ensure that the recording on the database is permanent,
ordered in proper sequence and available to all others on the network.
5. Computational logic: Because of the digital nature of the ledger, blockchain
transactions cannot be tied to computational logic and programmed.
So, users can set up algorithms and rules that automatically trigger
transactions between nodes.
Chapter 5: Developing Blockchain Applications | 27

How a blockchain works


The blockchain is a new concept when compared to traditional financial practices
and can involve a series of complex steps. The following points highlight the
processes in a blockchain. The first few steps are simple to understand, but
the subsequent steps become complicated as transactions mature.
1. Transaction initiation: In order to run any business, it is necessary
to have currency transactions. For example: Party A wants to buy some
goods from Party B, for which the former has to perform some cash/online
transactions with the latter. Now assume that A and B are Bitcoin users.
And A wants to send money to B in exchange for the goods. This is the first
stage of the blockchain process.
2. Identity encryption: In the blockchain domain, both A and B are in the
form of cryptographic keys holding unique public and private keys. The
main objective of the private key is to ensure that only that user who
owns the key can access and edit any specific part of the blockchain in
an exclusive manner, and no editing can be done by any other entity.
As each key is modified within its own domain, it keeps the whole chain
coordinated in an efficient manner.
3. Block creation: When A starts and locks the transaction, a block is
created, which contains encrypted information of the person who intends
to transfer the money to B. It is created by combining a timestamp, all
significant information as well as a digital signature to ensure that the
private key of A is attached to the public key of B to transfer the amount
in the form of cryptocurrency.
4. Noding: After the secure encrypted block is created, it is broadcast as
a message across the blockchain via all nodes attached to the network.
Nodes are computers connected to a single network. Once the block is
communicated to the system, the nodes are primarily responsible for
confirming each entry by solving an arithmetical problem connected to
it to verify and validate the block and receive Bitcoins in return.
5. Verification: Once the transaction is confirmed, the blocks are time
stamped and coupled together with previous verified blocks present in the
blockchain. Once the process is complete, Party B receives the amount
from Party A.

Open source blockchain platforms


Blockchain technology was first used for financial transactions, but nowadays,
its scope is increasing rapidly. Today it is applied in a variety of industries like
e-commerce, data management, energy, online voting, gaming, e-governance
and many more.
A number of commercial and open source platforms provide the framework
for creating applications that support a blockchain. A blockchain product
must fulfil the following primary requirements:
28 | Chapter 5: Developing Blockchain Applications

Hyperledger APIs, SDK, CLI

MEMBERSHIP BLOCKCHAIN TRANSACTIONS CHAINCODE

Membership Blockchain Services Chaincode


Services Services

Registration Consensus Distributed Secure Container


Manager Ledger
Identity
Management
P2P Ledger Secure
Auditability Protocol Storage Registry

Event Stream

Figure 2: Hyperledger services


ƒƒ Create a live and distributed transactional database
ƒƒ Create user identification labels for active parties
ƒƒ Each transaction must be verified on an active ledger for approval
ƒƒ Transactions should stop in case of any non-verification
To develop a smart mobile blockchain app, one needs to use a transaction
and ledger model. For easy and quick blockchain app development, there are
various open source platforms available, some of which are featured here.

Ethereum
Ethereum is an open source, public, blockchain based decentralised platform
running smart contracts — applications that run exactly as programmed without
any possibility of downtime, censorship, fraud or third-party interference.
It was proposed in 2013 by Vitalik Buterin and was crowdfunded online
between July and August 2014.
Ethereum is a distributed public blockchain network and is somewhat
different from Bitcoin in terms of capability and purpose. The Bitcoin
blockchain is used to track ownership of digital currency, while the
Ethereum blockchain mostly focuses on running the programming code
of any decentralised application. In the Ethereum blockchain, Ether is a
crypto type which is the heart of the network. Ether is used by application
developers to pay transaction fees and services on the Ethereum network.
Ethereum is made up of the following components.
ƒƒ Ethereum virtual machine (EVM): This is a 256-bit register stack that’s
completely sandboxed and isolated from the network, file system or other
Chapter 5: Developing Blockchain Applications | 29

processes. Every node runs an EVM and executes the same instructions.
ƒƒ Smart contracts: These are high level programming abstractions compiled
to EVM byte code and deployed to the Ethereum blockchain for execution.
They are programmed using various languages like Solidity, Serpent, LLL
and Mutan.
ƒƒ Applications: Ethereum has almost 50 per cent of the market share and
more than 250 live Dapps, which are used for various applications like
digital signatures, stock market predictions, gaming, social media, etc.
ƒƒ Performance: It makes use of Merkle trees to improve scalability and
optimise transaction hashing.
Official website: https://www.ethereum.org/
Latest version: 0.10.0

Hyperledger
Hyperledger is an open source collaborative effort hosted by the Linux
Foundation and doesn’t support Bitcoin or any other cryptocurrency.
The objective of Hyperledger is to advance cross-industry collaboration
by developing blockchains and distributed ledgers, with a focus on
improving the performance and reliability of these systems as compared
to traditional cryptographic designs – in order to make them capable of
supporting global business transactions by major technological, finance
and supply chain companies.

Infrastructure Services
Notary Notary

BFT
RAFT
Validating
Notary
Services Network Map Permissioning
txns storage TLS certs

AMQP 1.0/TLS

Party A Oracle Party B


Oracle
Party A node Oracle Party B node
CorDrop CorDrop
Node Oracle node Node
Explorer CorDrop Explorer

vault vault

txns txns

Figure 3: The components of Corda


30 | Chapter 5: Developing Blockchain Applications

Bank
Quorum
Network

Bank

Regulator

DApp DApp DApp DApp

Quorum
Private & Quorum Constellation
Public Node
transactions Data
go-ethereum
Transaction
Enclave encryption
Mangager
Off-chain
payload
storage

Figure 4: Quorum network architecture

Figure 2 highlights the Hyperledger reference architecture.


The following are some of the Hyperledger frameworks. Hyperledger
Sawtooth: This is a modular blockchain suite developed by Intel, which
makes use of the consensus algorithm called ‘Proof of Elapsed Time (PoeT)’.
Hyperledger Iroha: This is a project of some Japanese companies to create
an easy-to-implement framework for a blockchain.Hyperledger Fabric: This
has been designed by IBM as a plug-and-play implementation of blockchain
technology for designing high-scale blockchain applications with a high
degree of flexible permissions.
ƒƒ Hyperledger Burrow: This develops a permissible smart contract machine
along the specifications of Ethereum.
Some of the popular tools of Hyperledger are listed below.
• Caliper: This is a benchmarking tool that allows users to measure
the performance of specific blockchain implementations with a set of
predefined use cases.
• Cello: This blockchain module toolkit brings the on-demand ‘as-a-
service’ deployment model to the blockchain ecosystem to reduce the
effort of managing and destroying blockchains.
• Composer: This creates smart contracts and applications to solve complex
business problems.
Chapter 5: Developing Blockchain Applications | 31

• Explorer: This is a user interface to view, deploy and query blocks,


transactions, chain codes as well as other relevant information in
the ledger.
• Quilt: This is a payment protocol developed to transfer value across
distributed ledgers and non-distributed ledgers.
Official website: https://www.hyperledger.org/

Corda
Corda is an open source distributed ledger platform for recording and
processing financial agreements that support smart contracts. The objective
of Corda is to provide a platform with common services to ensure that
any services built on top are compatible with network participants and
innovations happen faster.
Corda is the only platform offering the ‘universal interoperability of
public networks with the privacy of private networks’. As compared to
traditional blockchains, Corda ensures minimal information leaks by
sharing transaction data only with participants that require it. It maintains
confidentiality and provides encryption to client data.
As a smart contract platform and host of distributed apps called Dapps,
it acts as a gateway to a network of fully interoperable Dapps for finance
and commerce. These are called CorDapps.
Listed below are some of the key components of Corda.
ƒƒ Node: Every node hosts Corda services and executes CorDapps using
JVM and communicates using AMQP/1.0 over TLS
• Permissioning service
• Network map service
• Pluggable notary service types
• Oracle services
• CorDapps
• Corda applications
Official website: https://www.corda.net/
Latest version: 3.1

HydraChain
HydraChain is an open source blockchain platform designed by Brainbot
Technologies and the Ethereum Project. It is regarded as an extension to
the Ethereum blockchain platform, and provides support to create private
blockchain networks.
It is fully compatible with API level as well as contract level protocols in
Ethereum, and smart contracts are designed using the Python programming
language. In a HydraChain network, all the blocks are not allowed to enter
the network without proper validation, and any block can only be added
with a proper validator’s signature. Once the block enters the network, it
32 | Chapter 5: Developing Blockchain Applications

becomes persistent with no reverts.


The HydraChain platform provides the following components in a
blockchain.
ƒƒ Transaction cost: This is the cost of executing computational steps
in a transaction. In HydraChain, the cost is calculated on the basis of
requirements.
ƒƒ Gas limits: These are basic units for transaction executed in a blockchain.
Every transaction is sub-divided into ‘opcode’ and every opcode has
specific gas units based on the opcode type.
ƒƒ Genesis allocation: This is related to the hashing and mining capacity
of the blockchain.
ƒƒ Block time: This is the time delay between mining or validation of two
blocks.
Official website: http://www.brainbot.com/projects.html
Latest version: 0.3.0

MultiChain
MultiChain is an open source blockchain platform that enables user
based networks to supposedly perform 1000 financial transactions
per second. It enables enterprises to build and implement blockchain
applications with speed. It is specially designed for customers with
requirements similar to what Bitcoin offers but with special features
for corporate entities. With MultiChain, banks can even build their own
blockchains. It offers users 45 customisable parameters and changeable
protocol-level restrictions.
The following are some of the unique features of MultiChain:
ƒƒ 1000 transactions per second.
ƒƒ Dynamic control over connections, sends and receives transactions,
asset creation, streams and blocks.
ƒƒ Cross-chain applications and users can issue millions of assets on a
blockchain.
ƒƒ Highly developer friendly and fully customisable.
ƒƒ Extends the Bitcoin protocol, formats and APIs including full multi-
signature support.
ƒƒ Ideal for data sharing, encryption archiving and time stamping.
Official website: https://www.multichain.com/
Latest version: 1.0.4

Openchain
Openchain is a distributed ledger based on open source technology and is
specially designed for organisations to issue and manage digital assets in a
highly scalable, secured and robust manner. Openchain doesn’t make use of
the concept of blocks, and transactions are directly chained to one another.
Chapter 5: Developing Blockchain Applications | 33

Transactions get linked to the chain at the same time that they are submitted
to the network.
This is how it works:
ƒƒ There is a single authority for validating transactions for every Openchain
instance.
ƒƒ Rather than have one single central ledger, every organisation has
complete control over its respective instance and every instance connects
with each other.
ƒƒ Different transactions are validated by different authorities, depending
on the exchange of assets.
ƒƒ Every issuer of an asset has full control over the transactions.
There are three modules of the Openchain blockchain.
• Storage engines: These are the core components, and their primary
task is to store transaction chains and records. Modules include
Openchain.Sqlite, Openchain.SqlServer, Openchain.MongoDB, etc
• Validation engines
• Anchoring media
Official website:
https://www.openchain.org/
Latest version: 0.7

Elements
Elements, being an open source collaborative project, was designed to
bring advanced technological improvements to Bitcoin technology. It is a
blockchain based digital currency that aims to revolutionise the loyalty
rewards industry. It offers a unique platform to multiple merchants to
leverage the underlying cryptocurrency technology to boost sales, visibility
and customer satisfaction.
It operates on the Proof-of-Work (POW) mining algorithm with the X11-
changed hashing algorithm as its POW. It provides a universal loyalty currency
that can be adapted by various merchants and used by customers as per
their requirements.
Components of the Elements blockchain are:
ƒƒ Asset issuance
ƒƒ Confidential transactions
ƒƒ Segregated witnesses
ƒƒ Relative time clock
ƒƒ SCHNORR signatures
ƒƒ New opcodes
ƒƒ Signature covers value
ƒƒ Deterministic pegs
ƒƒ Signed blocks
ƒƒ Bitmask Sighash, which is under development
34 | Chapter 5: Developing Blockchain Applications

Official website: https://elementsproject.org/


Latest version: 0.14.1

Quorum
Quorum is an open source extension to Ethereum created by J.P. Morgan.
It supports transaction and contract privacy. It was designed especially for
applications requiring a high speed and throughput in terms of processing
private transactions and a permissioned group of known participants.
It has also been designed to overcome many of the key challenges of the
financial industry. Being an extension to Ethereum, it basically modifies some
part of the Ethereum core and is able to integrate all updates of Ethereum
without any hiccups.
Quorum supports:
ƒƒ Privacy at the transaction level and maintains a wide transparency
network; it is highly customised as per the requirements of the business.
ƒƒ Institutional transaction volumes.
The following libraries have been designed by developers especially for
Quorum:
ƒƒ Quorum Blockchain Explorer – This supports viewing of private
transactions.
ƒƒ Quorum-Genesis – This is a simple CL utility for Quorum to help populate
the genesis file with voters and makers.
ƒƒ Quorum Maker – This is a utility to create Quorum nodes.
ƒƒ QuorumNetworkManager – This makes creating and managing Quorum
networks easy.
ƒƒ ERC20 REST service – This is a Quorum-supported RESTful service for
creating and managing ERC-20 tokens.
ƒƒ Nethereum Quorum – This is a .NET Quorum adapter.
ƒƒ web3j-quorum – This is an extension to the web3j Java library providing
support for the Quorum API.
Official website: https://www.jpmorgan.com/global/Quorum
Latest version: 2.0.2
| 35

Chapter 6

Blockchain and Data Security


Bitcoin and other blockchain technologies have received a lot of media
attention over the past year. These technologies, aimed at disrupting
traditional financial setups, have the potential to change the way we look
at money. But how secure are these new technologies?

At a time when data privacy is becoming increasingly important, you need


to be sure that your personal information is being handled correctly.
There have been a number of high-profile hacks into cryptocurrency trading
sites, leading to the loss of millions of dollars. Is this a reflection of the tech
at the heart of the systems? In this article, we’ll examine what blockchain
and cryptocurrencies are, and whether they are secure.

Blockchain and cryptocurrency explained


These two words are often misused or used interchangeably. Although the
detailed workings of each can be somewhat difficult to grasp, the concepts
themselves aren’t. I’ve defined each term below.
ƒƒ Blockchain: This is a system that was initially developed as an accounting
tool for the digital currency, Bitcoin. Simply put, it’s a public ledger of all of
the transactions carried out using Bitcoin, or other digital currencies. You’ll
often hear the word ‘decentralised’ associated with blockchain. Although
there are many meanings to this term, in this case it means that no one
body controls it, and that there is no central point in the infrastructure.
The blockchain grows as more transactions are added (in chronological
order). It uses a distributed ledger, which means that it is shared and
synced across a broad network.
ƒƒ Cryptocurrency: Often, the terms ‘cryptocurrency’ and ‘Bitcoin’ are used
interchangeably. This is incorrect. Bitcoin is a type of cryptocurrency.
Though admittedly, it was the first of its kind. A cryptocurrency is a
digital currency that uses cryptography as a means of security. This
means that the information associated with the currency is encrypted.
These currencies are not issued by a central government and are used
to facilitate the transfer of funds between two parties.
It’s clear that these two terms are closely linked but refer to very different
things. So, how secure are they?
36 | Chapter 6: Blockchain and Data Security

Is the technology secure?


One of the most useful aspects of blockchain technology is that the transaction
data recorded to it cannot be manipulated. Because the data is decentralised
and on a distributed ledger, the system relies on the data being correct across
each user’s version. This makes it extremely difficult for cyber criminals
to target it. Some experts believe that the technology could be used to act
as a cyber security shield. There are many opportunities for blockchain to
be implemented, and a wide variety of companies are exploring options for
increased data privacy and online anonymity.
Cryptocurrencies based on these systems can be considered secure in
many ways. Because both a public and private key is required to access
them, and since the technology is hard to hack, the digital currencies
themselves cannot be altered. However, there have been many cases of
digital coins being stolen from exchanges and digital wallets. It’s common
for people to get scammed into sending their coins to fraudulent addresses.
This makes it incredibly difficult to recover them. Other examples have seen
websites being hacked and the coins they store being routed to a different
wallet. The risk of this kind of digital crime is greatly reduced if you use
a hardware wallet. This is a physical device in which you can safely store
your digital coins.
Ultimately, both technologies are incredibly secure. However, thefts
of cryptocurrencies are common, particularly when users aren’t careful.
It’s not the digital currencies themselves that get hacked, but rather, the
exchanges and wallets in which they are kept.

Blockchain and cryptocurrency security


The financial sector has been shaken up of late, all thanks to these innovative
systems. However, their unregulated and decentralised nature has led
many to question the security of blockchain and cryptocurrencies. This
fear seems to be unfounded, particularly when the fundamentals of the
technologies are examined. The very nature of the blockchain means that
it’s incredibly difficult to tamper with. It relies on many different instances
of the same information to be consolidated and checked. The implications
and applications of this are great, and we’ll likely see much broader adoption
of the blockchain in the near future.
Cryptocurrencies have been at the centre of a media storm. There have
been stories of instant riches, as well as significant losses. However, the
stories of stolen or lost funds are not an indication of a security flaw in the
technology. Instead, it shows that both users and websites that store the
digital assets need to be constantly vigilant. There are a number of ways to
secure cryptocurrencies, but being aware of the dangers is essential.
| 37

Chapter 7

Discover Ethereum
Dive into the world of blockchains, and use Ethereum to host a private
network and deploy a smart contract.

Blockchain, as you might already know, is a tamper-resistant, append-only,


distributed ledger. It is expected to be the next disruptive technology, although
some argue that it is more of a foundational technology than something
disruptive. Bitcoin was the first large scale adoption of a blockchain based
platform, but the blockchain technology is capable of supporting much more
than just cryptocurrencies. Ethereum provides an open source blockchain
based distributed computing platform on which we can deploy apps to do
much more than just financial transactions or money exchange. I’ve chosen
Ethereum because it is very popular, and currently ranks second behind
bitcoin, in terms of market capitalisation. Besides, it is open source, provides
a Turing complete virtual machine – the Ethereum Virtual Machine (EVM)
— to deploy the applications, and has an active community to support it.
In this article, we will discuss how to set up a private network that will
host the Ethereum platform, including the blockchain. We will also learn
to deploy a very basic application and interact with it. First, let us discuss
some key terms that will help us understand the later sections.
Smart contract: This is a piece of code that is deployed in a distributed
manner across the nodes hosting the network. It administers laws and rules,
determines penalties and enforces them across the network. It contains
states that are stored on the blockchain.
Consensus: This is the process by which all the different nodes agree about
a state change. It ensures that even if malicious parties behave arbitrarily,
the honest parties would still be able to reach an agreement.
Transactions: Any change of state is proposed as a transaction. The
transactions (individually or collectively) are consented upon and then
written into the blockchain.
38 | Chapter 7: Discover Ethereum

Queries: Reading states from a current blockchain is known as a query.


It does not require consensus, and any node can perform a query by just
reading the latest states on the blockchain.
Mining (in Proof of Work systems): A hard cryptographic puzzle needs
to be solved before a node can take multiple transactions and form a block.
This process is called mining and the nodes which perform this are called
miners. Because this is a tough job, to incentivise miners, a mining reward
is given to the winner who successfully writes on the blockchain.
Genesis: Every blockchain starts with a genesis block containing the basic
rules of that chain. It mainly contains the system parameters.

Prerequisites for installation


We first need a few tools to help us through the installation and deployment.
Let’s assume you have Ubuntu 16.04 running on your system, although
the tools and methods are quite generic and can be easily ported to other
distributions or operating systems too.
Installing Git and Go: There are a few official implementations of the
Ethereum protocol. We will build the Golang implementation from source and
to check out the latest build, we will need Git. Also, the Go version present
in the Ubuntu repositories is old and hence we will use the gophers PPA for
the latest version.

$ sudo add-apt-repository ppa:gophers/archive


$ sudo apt-get update
$ sudo apt-get install golang-1.10-go git

Setting up the environment variables: We need to set up some environment


variables for Go to function correctly. So let us first create a folder which
we will use as our workspace, and set up a GOPATH to that folder. Next, we
will update our PATH variable so that the system recognises our compiled
binaries and also the previously installed Golang.

$ cd ~
$ mkdir workspace
$ echo “export GOPATH=$HOME/workspace” >> ~/.bashrc
$ echo “export PATH=$PATH:$HOME/workspace/bin:/usr/local/go/bin:/usr/lib/go-1.10/bin” >> ~/.bashrc
$ source ~/.bashrc

Installing and running Ethereum


Let us first check out the latest version of geth (go-ethereum) with Git, and
then build it from the source.

$ cd ~/workspace
Chapter 7: Discover Ethereum | 39

$ git clone https://github.com/ethereum/go-ethereum.git


$ cd go-ethereum/
$ make geth

Upon successful completion of the last command, it will display a path


to the geth binary. We don’t want to write the entire path again and again,
so let’s add that to the PATH variable:

$ echo “export PATH=$PATH:$HOME/workspace/go-ethereum/build/bin” >> ~/.bashrc


$ source ~/.bashrc

Next, we need to create a genesis.json file that will contain the blockchain
parameters. It will be used to initialise the nodes. All the nodes need to have
the same genesis.json file. Here is a sample of a genesis.json file that we will
use. It is saved in our workspace directory.

$ cd ~/workspace/
$ cat genesis.json
{
“config”: {
“chainId”: 1907,
“homesteadBlock”: 0,
“eip155Block”: 0,
“eip158Block”: 0,
“ByzantiumBlock”: 0
},
“difficulty”: “10”,
“gasLimit”: “900000000000”,
“alloc”: {}
}

Now, open a new terminal (say Terminal 1) and run our first Ethereum
node on it. To enable that, first create a work folder for the node and a
new account. Make sure you don’t forget the passphrase because that can
be fatal on the main Ethereum network. In our case, because we are just
creating our own private network, this is not such a serious concern. Then
we supply a network ID:

cd ~/workspace/
$ mkdir node1
$ geth account new --datadir node1
$ geth init genesis.json --datadir node1
$ geth console --datadir node1 --networkid 1729
40 | Chapter 7: Discover Ethereum

We should now be inside the Geth console. You can play around before
proceeding but for our purpose, let us head on to creating a second node.
To do that, look at the enode details of our current node. On the Geth
console, execute the following commands:

> admin.nodeInfo
{
enode: “enode://c2b8714eca73d7a5a4264fa60641a8791ff8d33e47
dbb51f8b590594eb48e2aba9f360f340f358700e41e9d8415d7ca f70c67d12a66096053989c3824f7f64c3@
[::]:30303”,
………

We just need the enode details and have to replace the [::] with the
localhost IP 127.0.0.1.
Let’s fire up a new terminal, say Terminal 2, to host the second node.
We proceed like, before and then supply the previous network ID, bootnode
details and a port number for the node to bind to. We will also enable RPC
from a particular domain, which we will use later to connect to this node.

$ cd ~/workspace/
$ mkdir node2
$ geth account new --datadir node2
$ geth init genesis.json --datadir node2
$ geth console --datadir node2 --networkid 1729 --port 30304
--bootnodes “enode://c2b8714eca73d7a5a4264fa60641a8791ff8d33e47
dbb51f8b590594eb48e2aba9f360f340f358700e41e9d8415d7c af70c67d12a66096053989c3824f7f64c3@
[127.0.0.1]:30303” --rpc --rpccorsdomain “http://remix.ethereum.org”

If everything goes well, you will have two nodes connected to each other,
hosting the same blockchain. To confirm, you can use ‘admin.peers’ inside
the Geth consoles.
Until now, we just hosted the blockchain. We did not perform any
transaction, mine blocks or transfer ether. In fact, all our accounts are
empty. Let us now check our account balance and start mining on one of
the nodes, say Terminal 1.

> eth.getBalance(eth.accounts[0])

0
> miner.start(1)

We see that our account balance is zero. Starting the mining process
may take some time. If you want a break, now is the time, because
Chapter 7: Discover Ethereum | 41

generating the DAG may take a considerable amount of time. Once the
mining starts, you can recheck the account balance to see it increasing.
This is because you are getting the mining reward. You can see logs on
the console such as ‘mined potential block’ and ‘commit new mining
work’ that tell you that a new block has been mined. The other node
will also sync the newly created blocks.
To transfer ether from one account to another, we have to unlock the
account and transfer funds. For example:

> personal.unlockAccount(eth.accounts[0], “pass”, 24*7*360)


true

> eth.sendTransaction({from:eth.accounts[0],
to:”0xba993910008b3940626c83135fa2412b4a91b3b1”, value: web3.toWei(6, “ether”)})

In the first command, the passphrase needs to be supplied in place


of ‘pass’. The last argument is the time duration for unlocking, which is
optional. But we don’t want this to bother us again and again.
In the second command, the ‘to’ field should contain the address of
the account you want to send to. You can execute ‘eth.accounts[0]’ on
Terminal 2 and supply the string here. Once done and once a new block
is mined, you can see the change of funds reflected in your account
balances. If it says insufficient funds, wait for some new blocks to be
mined or decrease the amount. We have sent six ethers in the example
shown.

Writing your first solidity contract


Now that we have set up the network to host the blockchain, let us deploy
a smart contract and interact with it.
Fire up the browser and head to http://remix.ethereum.org/. We
will use the online compiler to compile our code and with it, connect
to our localhost and deploy on the private network. Close the default
code (Ballot.sol) that is open on Remix, delete the sol file from under the
browser dropdown on the left and create a new file named Basic.sol on
the browser. Then write the following piece of code inside the contract.

pragma solidity ^0.4.19;

contract Basic {
//declaring an unsigned interger. Let’s make it private
uint private variable;
42 | Chapter 7: Discover Ethereum

//this function returns the value of the stored variable


function get() constant public returns (uint retVal) {
return variable;
}

//this functions sets the value of the stored variable to the passed argument value
function set (uint x) public {
variable = x;
}

Now, compile to see if it successfully compiles without errors. Next,


go to the ‘Run’ tab and select ‘Web3 Provider’ from the ‘Environment’
drop down menu. Choose the default endpoint, if asked.
On clicking ‘Create’ , the contract will be deployed. But on the browser
console, you’ll probably see an authentication error. This is because to
deploy, your account needs to be unlocked. Head over to the Terminal 2
Geth console and unlock the account as you did while transferring funds.
Now, once done, try creating the contract from your browser again. (If
you see an error message saying ‘Insufficient funds’, try sending more
ethers from your node1 account to your node2 account.) Once deployed
and mined, you will see the address and function names on your browser,
as seen on the lower right of Figure 1.
Use the ‘get’ button to fetch the current value of the variable. Use
‘set’ to put some value into the variable which you can check by using
‘get’ again. You will notice that ‘get’ gives the value instantaneously,
whereas ‘set’ takes time. Also, on using ‘set’, a new transaction is seen
on the Geth console on Terminal2. This is because ‘get’ is a query
which just returns the current state recorded on the blockchain,
whereas ‘set’ attempts to change the state. Any state changes must
go through consensus, and hence we need to wait till the transaction
is mined before we can see the changes across the nodes.

The final steps


This article was meant to initiate you into the world of Ethereum. There
are a lot of things which you can try, and make complex blockchain based
projects. I would encourage those interested to try out the following.
ƒƒ Exploring the Geth console and expanding the private network to multiple
nodes: You can try to make a node malicious or shut down abruptly,
and see if and how it impacts the transactions.
ƒƒ Writing more elaborate smart contracts: You can send and receive funds
Chapter 7: Discover Ethereum | 43

Figure 1: Using Remix to deploy a contract and interact

to and from smart contracts. Try some of the projects at https://www.


ethereum.org/.
ƒƒ Using the online compiler was one of the ways to deploy and interact. You
can manually compile and deploy using ABI (https://github.com/ethereum/
go-ethereum/wiki/Contract-Tutorial) or use a framework like Truffle
(http://truffleframework.com/).
ƒƒ Geth is one of the flavours implemented in Go. You can use other language
implementations like C++ and Python, look into the code and contribute.
They are all open source (https://github.com/ethereum). You can even
use GUI clients like Mist (https://github.com/ethereum/mist).
ƒƒ Use the testnet and main Ethereum network to test and deploy contracts:
Warning: The main network involves real money. So be sure about what
you are doing. Writing secure contracts is a tough job (https://medium.
com/new-alchemy/a-short-history-of-smart-contract-hacks-on-ethereum-
1a30020b5fd)!
ƒƒ Take a look at other smart contract based projects and learn from them
(https://www.stateofthedapps.com/dapps/tab/most-viewed).
Ethereum has a very active community. In case you face issues, a quick
Web search should fetch most answers. If not, try their Gitter, Reddit and
Stack Exchange platforms. I hope this article helped demystify some of the
blockchain buzzwords and gave readers a feel of what blockchain is about.
It is still a developing technology, and you can contribute both in terms of
theory and implementation.
44 |

Chapter 8

Hyperledger: An Overview
Hyperledger is a project that was conceived by The Linux Foundation. It
focuses on developing blockchain frameworks and modules to support
global enterprise solutions. It is an open source collaborative effort to
foster cross-industry blockchain technologies.

Those familiar with the fundamentals of blockchain technologies will


know how open source is currently driving the innovation in blockchain
frameworks. However, there are a number of challenges to the widespread
use of permissioned distributed ledger technologies (DLT). Key among them
are problems associated with the lack of standards, the regulatory challenges
and the lack of knowledge about DLT. These challenges are inherent to
any new technological infrastructure that replaces an older infrastructure.

Challenges in adopting blockchain technologies


Those adopting blockchain technologies are likely to face challenges in the
following areas.

ƒƒ Standards
Since we are still witnessing the early days of blockchain technology, there
is currently no consensus on standards in the developer and business
communities, as yet. Standards are the key in ensuring interoperability and
avoiding risks associated with a fragmented ecosystem. They are critical not
just for the distributed ledger itself, but also for supporting services, like
identity, privacy and data governance, as well as for the management of keys,
the protocols, key-loss and theft. As a result, the International Organization
for Standardisation for Blockchain and Distributed Ledger Technologies was
established in 2016 and has defined areas for future work on standardisation.
More details are available at https://www.iso.org/committee/6266604.html.
Chapter 8: Hyperledger: An Overview | 45

ƒƒ Regulation
The lack of regulation around transactions on the blockchain creates an
environment of uncertainty for all participants. Highly regulated industries
like financial services are treading carefully in the DLT space. There are no
regulatory guidelines governing smart contracts, causing much anxiety among
various players like lawyers, regulators, programmers and businesses. The
lack of regulatory guidelines, along with a lack of industry standards, prevents
the rapid adoption of DLT.

ƒƒ Lack of knowhow
The lack of knowhow (as well as know-whom and know-where) around DLT
and the shortage of experts in the area is a major challenge when adopting
distributed ledger technologies. While there has been an exponential increase
in the interest around blockchain technology, there is a huge shortage of
talent in the business and the technical spaces.

Introducing Project Hyperledger


Hosted by The Linux Foundation, Project Hyperledger provides an alternative
to the cryptocurrency-based blockchain model and focuses on developing
blockchain frameworks and modules to support global enterprise solutions.
The focus of Hyperledger is to provide a transparent and collaborative approach
to blockchain development. Hyperledger is an open source effort created to
advance cross-industry blockchain technologies. The community incubates and
promotes a range of business blockchain technologies, including distributed
ledger frameworks, smart contract engines, client libraries, graphical interfaces,
utility libraries and sample applications. It is a global collaboration of members
from various industries and organisations.
Hyperledger boasts a host of enterprise-ready solutions. It is about
communities of software developers building blockchain frameworks and
platforms. Hyperledger can be thought of as an open system for marketplaces,
including decentralised data-sharing networks and digital communities.

Introducing Hyperledger frameworks


Hyperledger business blockchain frameworks are used to build enterprise
blockchains for a consortium of organisations. The Hyperledger frameworks
include:
ƒƒ An append-only distributed ledger
ƒƒ A consensus algorithm for agreeing to changes in the ledger
ƒƒ Privacy of transactions through permissioned access
ƒƒ Smart contracts to process transaction requests
Hyperledger is an umbrella of open source projects, which are identified
as either frameworks that facilitate the creation of blockchain networks or
modules that facilitate the supporting functionality for exploring, visualising
or deploying the frameworks.
46 | Chapter 8: Hyperledger: An Overview

Hyperledger Fabric was the first proposal for a codebase, combining


previous work done by Digital Asset Holdings, Blockstream’s libconsensus
and IBM’s OpenBlockchain. It provides a modular architecture, which
allows components such as consensus and membership services to be
plug-and-play. Hyperledger Fabric supports permissioned deployments.
Hyperledger Sawtooth, which has been contributed by Intel, is a
blockchain framework that uses a modular platform for building, deploying
and running distributed ledgers. Solutions built with it can use various
consensus algorithms. Based on the size of the network, it uses the Proof
of Elapsed Time (PoET) consensus algorithm, eliminating high energy
consumption. It is designed for versatility, with support for both permissioned
and permissionless blockchain deployments.
Hyperledger Iroha is a blockchain framework contributed by
Soramitsu, Hitachi, NTT Data and Colu. It is designed to be simple and
easy to incorporate into infrastructure projects requiring distributed ledger
technology. Its emphasis is on mobile application development with client
libraries for Android and iOS, providing a development environment for
C++ developers to contribute to Hyperledger.
Hyperledger Indy is a distributed ledger that has been custom-built
for decentralised identity, with a goal to develop a set of decentralised
identity specs and artefacts that are independent of any particular ledger
and enable interoperability across any DLT that supports them.
Hyperledger Burrow is a permissioned smart contract machine that
provides a modular blockchain client with a permissioned smart contract
interpreter built, in part, to the specification of the Ethereum Virtual
Machine (EVM). Currently under incubation, it is the only available
Apache-licensed EVM implementation.

Introducing Hyperledger modules


Hyperledger modules are auxiliary software used for things like deploying
and maintaining blockchains, and examining the data on the ledgers as
well as the tools for designing, prototyping and extending blockchain
networks.
Hyperledger Cello provides a toolkit that fulfils Blockchain-as-a-Service,
eliminating the effort required in creating, managing and terminating
blockchains. It allows blockchain deployment to the cloud.
Hyperledger Explorer is a tool for visualising blockchain operations. It is
the first ever blockchain explorer for permissioned ledgers, allowing anyone
to explore the distributed ledger projects being created by Hyperledger’s
members from the inside, without compromising their privacy.
Hyperledger Composer provides an easy-to-use set of components that
developers can quickly learn to implement blockchain business networks.
Chapter 8: Hyperledger: An Overview | 47

Contributing to Hyperledger
Hyperledger has a really unique community. There are more than 130
organisations that comprise the Hyperledger member community.
Hyperledger has taken a leadership role in developing cross-industry
standards and provides a neutral space for software collaboration. The
code repositories for frameworks and modules are hosted on GitHub at
https://github.com/hyperledger.
There are a number of ways in which you can get involved with the
Hyperledger community (http://hyperledger.org/community) – you can
participate on the mailing lists (http://lists.hyperledger.org/), and start
or join a meetup or join the discussion on Rocket.Chat (https://chat.
hyperledger.org/).
48 |

Chapter 9

Hyperledger Fabric
With the runaway success of Bitcoin, the interest in distributed ledgers
and blockchains has perked up. Hyperledger Fabric is a collaborative open
source project that has been created to advance cross-industry blockchain
technologies. This article introduces the reader to it.

Hyperledger Fabric was the first proposal to The Linux Foundation’s


Hyperledger Project, contributed in part by IBM. This framework is modular,
scalable and secure. It has been specifically designed for industries such as
manufacturing, agriculture, healthcare and the capital markets. Hyperledger
Fabric is revolutionary in its ability to allow entities to conduct confidential
transactions without passing through a central authority. It is unique,
because it allows for modular consensus and membership service.
There are four different types of roles within a Hyperledger Fabric network:
ƒƒ Clients are applications that act on behalf of a person to propose
transactions on the network.
ƒƒ Peers maintain the state of the network and a copy of the ledger. There are
two different types of peers — endorsing and committing peers. However,
there is an overlap between endorsing and committing peers, in that the
former are a special kind of committing peers. All peers commit blocks
to the distributed ledger.
ƒƒ Endorsers simulate and endorse transactions.
ƒƒ Committers verify endorsements and validate transaction results, prior
to committing transactions to the blockchain.
The ordering service accepts endorsed transactions, orders them into a
block, and delivers the blocks to the committing peers.

Key components of Hyperledger Fabric


Transaction endorsement
A transaction endorsement is a signed response to the results of the simulated
transaction. The method of transaction endorsements depends on the
endorsement policy, which is specified when the chaincode is deployed. An
example of an endorsement policy would be something like, “The majority of
the endorsing peers must endorse the transaction.” Since an endorsement
policy is specified for a specific chaincode, different channels can have
different endorsement policies.
Chapter 9: Hyperledger Fabric | 49

Ordering
Transactions within a time frame are sorted into a block and are committed
in sequential order. In a blockchain network, transactions have to be written
to the shared ledger in a consistent order. The order of transactions has to be
established to ensure that the updates to the world state are valid when they
are committed to the network. Unlike the Bitcoin blockchain, where ordering
occurs by the solving of a cryptographic puzzle or by mining, Hyperledger
Fabric allows the organisations running the network to choose the ordering
mechanism that best suits that network. This modularity and flexibility makes
Hyperledger Fabric incredibly advantageous for enterprise applications.
Hyperledger Fabric provides three ordering mechanisms — SOLO, Kafka
and Simplified Byzantine Fault Tolerance (SBFT), though the last mechanism
has not yet been implemented in Fabric v1.0.
SOLO is the ordering mechanism most typically used by developers
experimenting with Hyperledger Fabric networks. It involves a single ordering
node.
Kafka is the Hyperledger Fabric ordering mechanism that is recommended
for production use. It uses Apache Kafka, an open source stream-processing
platform that provides a unified, high-throughput, low-latency platform for
handling real-time data feeds. In this case, the data consists of endorsed
transactions and RW sets. The Kafka mechanism provides a crash fault-
tolerant solution to ordering.
Simplified Byzantine Fault Tolerance or SBFT is an ordering mechanism
that is both crash fault-tolerant and Byzantine fault-tolerant. This means
that it can reach agreement even in the presence of malicious or faulty nodes.
The Hyperledger Fabric community has not yet implemented this mechanism,
but it is on its roadmap.
These three ordering mechanisms provide alternate methodologies for
agreeing on the order of transactions.

Identity verification
In addition to the multitude of endorsement, validity and versioning checks
that take place, there are also ongoing identity verifications happening during
each step of the transaction flow. Access control lists are implemented on
the hierarchical layers of the network (from the ordering service down to
channels) and payloads are repeatedly signed, verified and authenticated as a
transaction proposal passes through the different architectural components.

Channels
Channels allow organisations to use the same network, while maintaining
separation between multiple blockchains. Only the members of the
channel on which the transaction was performed can see the specifics of
the transaction. In other words, channels partition the network in order to
50 | Chapter 9: Hyperledger Fabric

allow transaction visibility for stakeholders only. This mechanism works by


delegating transactions to different ledgers. Only the members of the channel
are involved in consensus, while other members of the network do not see
the transactions on the channel.
Figure 1 shows three distinct channels — blue, orange, and grey. Each
channel has its own application, ledger and peers. The peers could belong to
multiple networks or channels. Those that do participate in multiple channels
simulate and commit transactions to different ledgers. The ordering service
is the same across any network or channel.

Application Peer1 Peer3


SDK
Ordering
Service
Application Peer2 Peer4
SDK

Figure 1: Key channels

A few things that must be kept in mind are:


ƒƒ The network setup allows for the creation of channels.
ƒƒ The same chaincode logic can be applied to multiple channels.
ƒƒ A given user can participate in multiple channels.

State database
The current state data represents the latest values for all assets in the ledger.
Since the current state represents all the committed transactions on the
channel, it is sometimes referred to as the world state. Chaincode invocations
execute transactions against the current state data. To make these chaincode
interactions extremely efficient, the latest key/value pairs for each asset are
stored in a state database, which is simply an indexed view into the chain’s
committed transactions. It can therefore be regenerated from the chain at
any time. The state database will automatically be recovered (or generated, if
needed) upon peer startup, before new transactions are accepted. The default
state database, LevelDB, can be replaced with CouchDB.
LevelDB is the default key/value state database for Hyperledger Fabric
and simply stores key/value pairs. CouchDB is an alternative to LevelDB.
Unlike LevelDB, CouchDB stores JSON objects. The latter is unique in that
it supports keyed, composite, key range, and full data-rich queries.
Hyperledger Fabric’s LevelDB and CouchDB are very similar in their
structure and functions. Both support core chaincode operations, such as
getting and setting key assets, and querying based on these keys. With both,
keys can be queried by range and composite keys can be modelled to enable
equivalence queries against multiple parameters. But, as a JSON document
Chapter 9: Hyperledger Fabric | 51

store, CouchDB additionally enables rich query against the chaincode data,
when chaincode values (e.g., assets) are modelled as JSON data.

Smart contracts
As a reminder, smart contracts are computer programs that contain logic to
execute transactions and modify the state of the assets stored within the ledger.
Hyperledger Fabric’s smart contracts are called chaincode and are written
in Go. The chaincode serves as the business logic for a Hyperledger Fabric
network, in that it directs how you manipulate assets within the network.

LovelDB

World State Chaincode


APIs

CouchDB

Figure 2: State database

Membership service provider (MSP)


The membership service provider, or MSP, is a component that defines the
rules in which identities are validated, authenticated and allowed access to
a network. The MSP manages user IDs and authenticates clients who want
to join the network. This includes providing credentials for these clients to
propose transactions. The MSP makes use of a certificate authority, which
is a pluggable interface that verifies and revokes user certificates upon
confirmed identity. The default interface used for the MSP is the Fabric-CA
API; however, organisations can implement an external certificate authority
of their choice. This is another feature of Hyperledger Fabric that is modular.
Hyperledger Fabric supports many credential architectures, which allow
for many types of external certificate authority interfaces to be used. As a
result, a single Hyperledger Fabric network can be controlled by multiple
MSPs, where each organisation brings its favourite.
What the MSP does: To start, users are authenticated using a certificate
authority, which identifies the application, peer, endorser and orderer
identities, and verifies these credentials. A signature is generated through
the use of a signing algorithm and a signature verification algorithm.
Specifically, generating a signature starts with a signing algorithm, which
52 | Chapter 9: Hyperledger Fabric

uses the credentials of the entities associated with their respective identities,
and outputs an endorsement. A signature is then generated, which is a byte
array that is bound to a specific identity.
Next, the signature verification algorithm takes the identity, endorsement
and signature as inputs and outputs ‘Accept’ if the signature byte array
corresponds with a valid signature for the inputted endorsement, or
outputs ‘Reject’ if it does not. If the output is ‘Accept’, the user can view the
transactions in the network and perform transactions with other actors in
the network. If the output is ‘Reject’, it implies that the user has not been
properly authenticated and is not able to submit transactions to the network,
or view any previous transactions.

Fabric-Certificate Authority (Fabric-CA)


In general, certificate authorities manage enrolment certificates for a
permissioned blockchain. Fabric-CA is the default certificate authority for
Hyperledger Fabric and handles the registration of user identities. The Fabric-
CA is in charge of issuing and revoking enrolment certificates (E-Certs). The
current implementation of Fabric-CA only issues E-Certs, which supply
long term identity certificates. E-Certs issued by the enrolment certificate
authority (E-CA) assign peers their identity, and give them permission to join
the network and submit transactions.

MSP
Fabric-CA
Fabric-CA
API

External-CA
API
External-CA

Figure 3: Membership service provider (MSP)

Getting involved with the Hyperledger Fabric project


Hyperledger Fabric is an open source project, where ideas and code can
be publicly discussed, created and reviewed. There are many ways to join
the Hyperledger Fabric community. You can join the weekly meeting on
Fabric Documentation or other Hyperledger Fabric-related get-togethers.
The Hyperledger Community Meetings Calendar is a great resource to learn
about the timings for these meetings. You can also join the Hyperledger
Fabric mailing lists for technical discussions and announcements. Gerrit is
Chapter 9: Hyperledger Fabric | 53

used for submitting PRs and managing code reviews and check-ins. You can
join the live conversations on Rocket.Chat (which is an alternative to Slack),
using your Linux Foundation ID.

What’s next?
In subsequent articles, we will look at Hyperledger Fabric with respect to
transaction flow, installation and chaincode development.
54 |

Chapter 10

Transaction Flow in Hyperledger Fabric


This is a continuation of the article that introduced Hyperledger Fabric,
published in the previous issue of OSFY. It explores the internal workings of
Hyperledger Fabric and takes a look at transaction flow.

In a distributed ledger system, consensus is the process of reaching an


agreement on the next set of transactions to be added to the ledger. In
Hyperledger Fabric, consensus involves three distinct steps:
ƒƒ Transaction endorsement
ƒƒ Ordering
ƒƒ Validation and commitment
These three steps ensure the policies of a network are upheld. We will
look at how these steps are implemented by exploring the transaction flow.

Transaction flow (Step 1)


Within a Hyperledger Fabric network, transactions start out with client applications
sending transaction proposals or, in other words, proposing a transaction to
endorsing peers.
Client applications are commonly referred to as applications or clients, and
allow people to communicate with the blockchain network. Application developers
can leverage the Hyperledger Fabric network through the application’s SDK.

Figure 1: Step 1 of the transaction flow


Chapter 10: Transaction Flow in Hyperledger Fabric | 55

Transaction flow (Step 2)


Each endorsing peer simulates the proposed transaction, without updating
the ledger. The endorsing peers will capture the sets of read and written data,
called RW sets. These RW sets capture what was read from the current world
state while simulating the transaction, as well as what would have been written
to the world state, had the transaction been executed. These RW sets are then
signed by the endorsing peer, and returned to the client application to be used
in future steps of the transaction flow.
This is the second step of the transaction flow, when endorsers simulate
transactions, generate RW sets, and return the signed RW sets back to the
client application. Endorsing peers must hold smart contracts in order to
simulate the transaction proposals.

Figure 2: Step 2 of the transaction flow

Transaction flow (Step 3)


The application then submits the endorsed transaction and the RW sets to
the ordering service. Ordering happens across the network, in parallel with
endorsed transactions and RW sets submitted by other applications.

Figure 3: Step 3 of the transaction flow


56 | Chapter 10: Transaction Flow in Hyperledger Fabric

Transaction flow (Step 4)


The ordering service takes the endorsed transactions and RW sets, orders
this information into a block, and delivers the block to all committing peers.
This is Step 4 of the transaction flow, where the orderer sends the ordered
transactions in a block to all committing peers.

Figure 4: Step 4 of the transaction flow

The ordering service, which is made up of a cluster of orderers, does not


process transactions, smart contracts, or maintain the shared ledger. It only
accepts the endorsed transactions and specifies the order in which those
transactions will be committed to the ledger. The Fabric v1.0 architecture
has been designed such that the specific implementation of ‘ordering’ (Solo,
Kafka and BFT) becomes a pluggable component. The default ordering service
for Hyperledger Fabric is Kafka. Therefore, the ordering service is a modular
component of Hyperledger Fabric.

Transaction flow (Step 5)


The committing peer validates the transaction by checking to make sure that
the RW sets still match the current world state—specifically, that the read
data that existed when the endorsers simulated the transaction is identical to
the current world state. When the committing peer validates the transaction,
the transaction is written to the ledger, and the world state is updated with
the write data from the RW set.
This is the fifth step of the transaction flow, where committing peers
validate each transaction in the block. If the transaction fails, that is, if the
committing peer finds that the RW set does not match the current world state,
the transaction ordered into a block will still be included in that block, but it
will be marked as invalid, and the world state will not be updated. Committing
peers are responsible for adding blocks of transactions to the shared ledger
and updating the world state. They may hold smart contracts, but it is not a
requirement.
Chapter 10: Transaction Flow in Hyperledger Fabric | 57

Figure 5: Step 5 of the transaction flow

Transaction flow (Step 6)


Lastly, the committing peers asynchronously notify the client application
of the success or failure of the transaction. Applications will be notified by
each committing peer.

Figure 6: Step 6 of the transaction flow

Chaincode
In Hyperledger Fabric, chaincode is the ‘smart contract’ that runs on the peers
and creates transactions. More broadly, it enables users to create transactions
in the Hyperledger Fabric network’s shared ledger and update the world state
of the assets.
Chaincode is programmable code, written in Go, and instantiated on a
channel. Developers use chaincode to develop business contracts, asset
definitions, and collectively-managed decentralised applications. The chaincode
manages the ledger state through transactions invoked by applications. Assets
are created and updated by a specific chaincode, and cannot be accessed
by another chaincode.
Applications interact with the blockchain ledger through the chaincode.
Therefore, the chaincode needs to be installed on every peer that will endorse
a transaction and is instantiated on the channel.
There are two ways to develop smart contracts with Hyperledger Fabric:
ƒƒ Code individual contracts into standalone instances of chaincode.
ƒƒ A more efficient way is to use chaincode to create decentralised applications
that manage the life cycle of one or multiple types of business contracts, and
58 | Chapter 10: Transaction Flow in Hyperledger Fabric

let the end users instantiate instances of contracts within these applications.

Overview of a chaincode program


When creating a chaincode, there are two methods that you will need to
implement:
ƒƒ Init: This is called when a chaincode receives an instantiate or upgrade
transaction. This is where you will initialise any application state.
ƒƒ Invoke: This is called when the invoke transaction is received to process
any transaction proposals.
As a developer, you must create both an Init and an Invoke method within
your chaincode. The chaincode must be installed using the peer chaincode
install command, and instantiated using the peer chaincode instantiate
command before the chaincode can be invoked. Then, transactions can be
created using the peer chaincode invoke or peer chaincode query commands.

Chaincode key APIs


Important interfaces that you can use when writing your chaincode are
defined by Hyperledger Fabric —ChaincodeStub and ChaincodeStubInterface.
The former provides functions that allow you to interact with the underlying
ledger to query, update and delete assets. The key APIs for chaincode include:

func (stub *ChaincodeStub) GetState(key string) ([]byte, error)

The above command returns the value of the specified key from the
ledger. Note that GetState doesn’t read data from the write set, which has
not been committed to the ledger. In other words, GetState doesn’t consider
data modified by PutState that has not been committed. If the key does not
exist in the state database, (nil, nil) is returned.

func (stub *ChaincodeStub) PutState(key string, value []byte) error

The above command puts the specified key and value into the transaction’s
write set as a data-write proposal. PutState doesn’t affect the ledger until the
transaction is validated and successfully committed.

func (stub *ChaincodeStub) DelState(key string) error

The above command records the specified key to be deleted in the write
set of the transaction proposal. The key and its value will be deleted from
the ledger when the transaction is validated and successfully committed.
With this tutorial, we complete the learning part related to Hyperledger
Fabric. In my next article, we will walk through using Fabric for a specific
use case.
| 59

Chapter 11

Hyperledger Sawtooth Framework


With the runaway success of Bitcoin, the interest in distributed ledgers
and blockchains has perked up. Hyperledger Fabric is a collaborative open
source project that has been created to advance cross-industry blockchain
technologies. This article introduces the reader to it.

Hyperledger Sawtooth is a blockchain framework that uses a modular platform


for building, deploying and running distributed ledgers. Such distributed
ledger solutions can use various consensus algorithms, depending on the
size of the network. Initially contributed by Intel, Hyperledger Sawtooth uses
the Proof of Elapsed Time (PoET) consensus algorithm, which provides the
scalability of the Bitcoin blockchain without the high energy consumption.
PoET allows for a highly scalable network of validator nodes. Hyperledger
Sawtooth is designed for versatility, with support for both permissioned and
permissionless deployments.
Sawtooth is the only Hyperledger project that provides the distributed
state agreement, which means that you can trust every node in the system to
understand information in the same way. It is the only framework that provides
the ability to create adapters for any kind of transaction logic which means, for
instance, that you can now run Ethereum Virtual Machine code, like Solidity,
compile it and then run that on a Sawtooth based network.

The functional elements of Hyperledger Sawtooth


Transaction validators validate transactions. In Hyperledger Sawtooth,
validators apply blocks that cause a change in the state. More specifically,
validators validate transaction blocks and ensure that transactions result
in state changes that are consistent across all participants in the network.
Transaction families are smart contracts in Hyperledger Sawtooth.
They define the operations that can be applied to transactions. This allows
for flexibility in the level of versatility and risk that exists on a network.
Transaction families are often called ‘safer’ smart contracts, because they
specify a predefined set of acceptable smart contract templates, as opposed
to programming smart contracts from scratch. Hyperledger Sawtooth’s
transaction families can be written in many languages, including JavaScript,
60 | Chapter 11: Hyperledger Sawtooth Framework

Java, C++, Python and Go, which allows flexibility for businesses to
bring their own transaction families. Transaction families consist of both
transaction processors (the server-side logic) and clients (for use from Web
or mobile applications).
Hyperledger Sawtooth organisations run a node that interacts with
the Hyperledger Sawtooth network. Each node runs at least three things:
ƒƒ The main validator process
ƒƒ The REST service listening for requests
ƒƒ One or more transaction processors
Each organisation that enters the Hyperledger Sawtooth network runs
at least one node and receives transactions submitted by fellow nodes.
A transaction processor is the server-side business logic of transaction
families, which acts upon network assets. Hyperledger Sawtooth supports
pluggable transaction processors that are customisable based on the specific
application. Each node within the Hyperledger Sawtooth network runs a
transaction processor, which processes incoming transactions submitted
by authorised clients.
Transaction batches are clusters of transactions that are either all
committed to state or are all not committed to state. As a result, transaction
batches are often described as an atomic unit of change, since a group of
transactions is treated as one and is committed to the state, as one. Every
single transaction in Hyperledger Sawtooth is submitted within a batch.
Batches can contain as little as a single transaction.
In Hyperledger Sawtooth, the journal maintains and extends the
blockchain for the validator. It is responsible for validating candidate
blocks, evaluating valid blocks to determine if they are the correct chain
head and for generating new blocks to extend the chain. Transaction
batches arrive at the journal, where they are evaluated, validated and
added to the blockchain. Additionally, the journal resolves forks, which
occur due to disagreements over who commits a block. Once blocks
are completed, they are delivered to the ChainController for validation
and fork resolution.
The network layer is responsible for communicating between validators in
a Hyperledger Sawtooth network, including performing initial connectivity,
peer discovery and message handling.
The global state contains the current state of the ledger and a chain of
transaction invocations. The state for all transaction families is represented
on each validator.
The process of block validation on each validator ensures that the same
transactions result in the same state transitions and that the resulting
data is the same for all participants in the network. The state is split into
namespaces, which allow flexibility for transaction family authors to define,
share and reuse global state data between transaction processors.
Chapter 11: Hyperledger Sawtooth Framework | 61

The consensus interface in Sawtooth


Consensus in Hyperledger Sawtooth is modular, which means that
the consensus algorithm can be easily modified. Hyperledger Sawtooth
provides an abstract interface that supports both PBFT and Nakamoto-
style algorithms. To implement a new consensus algorithm in Hyperledger
Sawtooth, you must implement the distinct interface for the following.

Journal

Transaction verification
and Consensus

Completer

Chain Controller Block Publisher

Block Verifier Fork Resolver Block Publisher

Transaction
Processing
Platform

Figure 1: The consensus interface in Sawtooth

ƒƒ Block publisher: This creates new candidate blocks to extend the chain.
ƒƒ Block verifier: This verifies that candidate blocks are published in accordance
with consensus rules.
ƒƒ Fork resolver: This chooses which fork to use as the chain head for
consensus algorithms that result in a fork.
These interfaces are used by the journal component. The journal verifies
that all the dependencies for the transaction batches are satisfied. When
verified, completed batches are checked for validity and fork resolution and
then, they are published within a block.

Introducing Proof of Elapsed Time (PoET)


The consensus algorithm commonly used in a Hyperledger Sawtooth network
is the Proof of Elapsed Time, or PoET, which impartially determines who will
commit a transaction to state using a lottery function that elects a leader
from many different distributed nodes.
62 | Chapter 11: Hyperledger Sawtooth Framework

Hyperledger Sawtooth’s PoET algorithm differs from the Proof of Work


(PoW) algorithm implemented by the Bitcoin blockchain in that PoW relies on
vast amounts of power, while PoET is able to ensure trust and randomness
in electing a leader, without the high power consumption. PoET allows for
increased scalability and participation, as every node in the network has an
equal opportunity to create the next block on the chain.

How Proof of Elapsed Time (PoET) works


To start with, each validator within the network requests a wait time from
an enclave or a trusted function. This is where the ‘elapsed time’ comes into
play. The validator with the shortest waiting period for a specific block is
appointed the leader and creates the block to be committed to the ledger. As
a result, a truly random leader is elected and the amount of power or type of
hardware you have will not give you an advantage. Using simple functions,
the network can verify that the winning validator did indeed ‘win’, by proving
that it had the shortest time to wait before assuming the leadership position.
Proof of Elapsed Time is revolutionary in its ability to achieve distributed
consensus using a lottery function. This not only allows for easy verification
and fairness within the network, but also for incredible scalability. Without
the heavy costs of participating in consensus, any block can participate
in the network. One of Hyperledger Sawtooth’s main advantages is that
it allows the size of the network to scale, i.e., with PoET it can nearly
support limitless nodes in the network.

Use cases
Hyperledger Sawtooth is a blockchain framework with potential in IoT,
manufacturing, finance and enterprises. It supports diverse requirements,
including both permissioned and permissionless deployments and a pluggable
consensus algorithm. This framework also provides a revolutionary consensus
algorithm, Proof of Elapsed Time (PoET), that allows for versatility and
scalability suited for a variety of solutions which can be broadly classified
with different infrastructural requirements, such as:
ƒƒ Permissioned and permissionless infrastructure
ƒƒ Modular blockchain architecture
ƒƒ Scalability, which is good for larger blockchain networks due to higher
throughput
ƒƒ Many languages for transaction logic
Hyperledger Sawtooth is an open source project, where ideas and code
can be publicly discussed, created and reviewed. All code is available on
GitHub and there are a number of ways that you can get involved with the
Hyperledger community, participate on the mailing lists, start or join a
meetup or join the discussion on Rocket.Chat, as the following references
indicate.
| 63

Chapter 12

Hyperledger Iroha
This article is for open source enthusiasts with an interest in blockchain
technology, and continues with the series on blockchain frameworks in
Project Hyperledger. So let’s look at Hyperledger Iroha, see what makes
it unique and learn how to get started with this framework.

Hyperledger Iroha is a blockchain framework, and one of the Hyperledger


projects hosted by The Linux Foundation. Initially contributed by Soramitsu,
Hitachi, NTT Dat and Colu, it is designed to be simple and easy to incorporate
into infrastructure projects requiring distributed ledger technology. Hyperledger
Iroha features a simple, modern construction, has a domain-driven C++
design, with an emphasis on mobile application development, and it comes
with the YAC consensus algorithm. This framework is a blockchain platform
implementation, designed to be easily incorporated into other distributed ledger
technologies. Hyperledger Iroha is designed to compile a library of reusable
modular components that enhance existing distributed ledger frameworks.

The goals of Hyperledger Iroha


The team behind Hyperledger Iroha set out to achieve the following three goals:
1. Provide an environment for C++ developers to contribute to Hyperledger.
2. Provide infrastructure for mobile and Web application support.
3. Provide a framework to introduce APIs and a new consensus algorithm
that can potentially be incorporated into other frameworks in the future.

The architecture
The core architecture of Hyperledger Iroha was inspired by Hyperledger
Fabric. The creators of Hyperledger Iroha have emphasised the importance
of this framework in fulfilling the need for user-friendly interfaces. In doing
so, they’ve created a framework with many defining features, and have
achieved their stated goals of a simple construction, a modern C++ design
with an emphasis on mobile application development, and a new chain-
based Byzantine fault-tolerant consensus algorithm called Sumeragi. The
most defining characteristic of Hyperledger Iroha is its ability to be freely

Figure 6: Transaction flow: S


64 | Chapter 12: Hyperledger Iroha

interoperable with other Hyperledger projects. The open source libraries for
iOS, Android and JavaScript allow developers to conveniently create functions
for performing common operations.
Figure 1 shows a layered architectural view of the different components
that make up Hyperledger Iroha. The four layers are: API, Peer Interaction,
Chain Business Logic and Storage.
Here is a brief description of the components of Hyperledger Iroha.
Model classes are system entities.
Torii (gate) provides the input and output interfaces for clients. It is a
single gRPC server that is used by clients to interact with peers through the
network. The client’s RPC call is non-blocking, making Torii an asynchronous

API level Torii Model

Peer interaction level Network Consensus

Chain business logic level Simulator Validator Synchoronizer

Storage level Ametsuchi

Figure 1: Hyperledger Iroha architecture

Stateless
Validation

Transaction
Client Peer

Torii

Figure 2: Transaction flow: Step 1

Transaction
Validated

Client Peer Ordering Service

Torii Ordering Gate

Figure 3: Transaction flow: Step 2

Transactions
Ordering Service
are ordered

Proposals

Peer Peer Peer Peer

Figure 4: Transaction flow: Step 3


Chapter 12: Hyperledger Iroha | 65

server. Both commands (transactions) and queries (read access) are performed
through this interface.
Network encompasses interaction with the network of peers.
Consensus is in charge of peers agreeing on chain content in the network.
The consensus mechanism used by Iroha is YAC (Yet Another Consensus),
which is a practical Byzantine fault-tolerant algorithm based on voting for
block hash.
Simulator generates a temporary snapshot of storage to validate transactions
by executing them against this snapshot and forming a verified proposal,
which consists only of valid transactions.
Validator classes check the business rules and validity (correct format)
of transactions or queries.
There are two distinct types of validation that occur in Hyperledger Iroha:
ƒƒ Stateless validation is a quicker form of validation, and it performs schema
and signature checks of the transaction.
ƒƒ Stateful validation is slower and checks the permissions and the current
world state view (which is the latest and most actual state of the chain)
to see if desired business rules and policies are possible — for example,
to check if an account has enough funds to transfer.
Synchroniser helps to synchronise new peers in the system or temporarily
disconnect peers.
Ametsuchi is the ledger block storage which consists of a block index,
block store, and a world state view component.

Key participants in the network


There are three main participants in a Hyperledger Iroha network.
Clients are able to:
a. Query data that they have access/permission to;
b. Perform a state-changing action or ‘transaction’, which consists of atomic
operations, called ‘commands’.

Peer Consensus Voting


Gate Leader
Peer
Simulator
Peer
Sending signed
proposed blocks
Peer
Proposed Block
Proposal’s Proposed Block
Peer
transactions Transaction Transaction
are verified Transaction Transaction
Transaction
Transaction

Figure 6: Transaction flow: Step 5


Figure 5: Transaction flow: Step 4
66 | Chapter 12: Hyperledger Iroha

Peers maintain the current state and their own copy of the shared ledger. A
peer is a single entity in the network, and has an address, identity and trust.
The ordering service orders transactions into a known order. There are a
few options for the algorithm used by the ordering service.

Transaction flow
Step 1: A client creates and sends a transaction to the Torii gate, which routes
the transaction to a peer that is responsible for performing stateless validation.
Step 2: After the peer performs stateless validation, the transaction is
first sent to the ordering gate, which is responsible for choosing the right
strategy for connection to the ordering service.
Step 3: The ordering service puts transactions into order and forwards
them to peers in the consensus network in the form of proposals. A proposal
is an unsigned block shared by the ordering service that contains a batch
of ordered transactions. Proposals are only forwarded when the ordering
service has accumulated enough transactions, or a certain amount of time
has elapsed since the last proposal. This prevents the ordering service from
sending empty proposals.
Step 4: Each peer verifies the proposal’s contents (stateful validation) in the
simulator, and creates a block that consists only of verified transactions. This
block is then sent to the consensus gate, which performs YAC consensus logic.
Step 5: An ordered list of peers is determined, and a leader is elected
based on the YAC consensus logic. Each peer casts a vote by signing and
sending its proposed block to the leader.
Step 6: If the leader receives enough signed proposed blocks (i.e., more than
two-thirds of the peers), then it starts to send a commit message, indicating
that this block should be applied to the chain of each peer participating in
the consensus. Once the commit message has been sent, the proposed block
becomes the next block in the chain of every peer, via the synchroniser.

The YA Consensus algorithm


Hyperledger Iroha currently implements the YAC consensus algorithm,
which is based on voting for block hash. The YAC performs two functions:
ordering and consensus.
‘Ordering’ is responsible for ordering all transactions, packaging them
into proposals, and sending them to peers in the network. The ordering
service is an endpoint for setting an order of transactions and their broadcast
(in a form of proposal). Ordering is not responsible for performing stateful
validation of transactions.
‘Consensus’ involves taking blocks after they have been validated,
collaborating with other blocks to decide on a commit, and propagating
commits between peers. ‘Consensus’ is responsible for an agreement on
blocks based on the same proposal.
Chapter 12: Hyperledger Iroha | 67

‘Validation’ is an important part of the transaction flow; however, it is


separate from the consensus process.

Note: Currently, the ordering service is a single point of failure that


does the ordering and, therefore, Hyperledger Iroha is neither crash
fault-tolerant, nor Byzantine fault-tolerant.

Hyperledger Iroha’s mobile libraries


A major goal for the creators of Hyperledger Iroha is to develop a distributed
ledger system that can be easily used by applications. In order to accomplish
this, Hyperledger Iroha offers open source software libraries for iOS, Android,
and JavaScript. These libraries allow for simple compatibility with not only
Hyperledger Iroha, but also, potentially, with other networks through flexible
API functions. These libraries are all open source, and available on GitHub.

An overview of the community


Hyperledger Iroha is an open source project for which ideas and code can be
publicly discussed, created and reviewed. There are many ways to get involved
with the Hyperledger Iroha community, one of which is through GitHub.
68 |

Chapter 13

Blockchain In The Energy Sector


As everyone jumps onto the blockchain bandwagon to
implement it in sectors like finance and land records, its use in
the energy distribution sector seems to hold a lot of promise.
This article explores its potential

After Bitcoin demonstrated the potential of blockchain, people from many


industries sat up. Though the financial services sector was an early adopter,
it did not use this technology merely for cryptocurrency purposes, but
rather for reasons of security and authentication. A publicly distributed
chain of blocks, each block representing data or a transaction, was virtually
tamper-proof. Soon, other verticals, like the energy sector, began exploring
the potential of blockchain.

The Brooklyn Grid


One of the early proofs of concept (PoCs) of how blockchain could work in the
utilities space is the Brooklyn Grid that was set up in 2015. This began in a
single neighbourhood in New York. Some residents set up solar panels that
fed the grid—these are whom we call prosumers. Others were just consumers.
This part of the operations involved Siemens (multinational in the electricity
space, which took care of digital grids and components) and LO3 Energy (firm
that develops blockchain-based solutions that have changed how energy is
generated, stored, bought and sold, at a local level).
At the first stage, with neighbours on the grid connected to each other,
the system worked as follows:
1. A home solar energy generator’s units of power were tokenised as it got
fed into the common grid.
2. Tokens could be bought directly by others in the grid, who were just
electricity consumers, bypassing the need to deal with a centralised
authority or utility.
3. Transactions were stored in a public Ethereum blockchain.
In his talk about blockchain usage in the energy sector, at India Electronics
Week (IEW) in February this year, Prashant K. Singh, senior consultant,
Blockchain Centre of Excellence, Wipro, described how things work. This
peer-to-peer trading in electricity tokens was enabled by an app that offered
Chapter 13: Blockchain In The Energy Sector | 69

two views: one of the users’ own consumption, billing and trading history,
as well as that of the neighbours. This allowed residents to compare their
own energy usage with that of other residents and maybe change behaviour
to ensure optimised consumption. It also let them know which homes had
tokens available for peer-to-peer trading.
In 2016, this pilot project got upgraded further by the installation of smart
meters by blockchain midware provider ConsenSys, and the incorporation of
many aspects of the Internet of Things (IoT). The software on these meters enable
smart transactions, whereby energy usage is tracked automatically, bills get
paid on their own—from credit or reserve tokens—and even energy usage alerts
are generated. For instance, with open trading in electricity tokens, just like
with other commodities, token rates also fluctuate. So, a smart energy agent
can even instruct the microwave oven, a known high-energy guzzler, to avoid
working during peak price hours!

Evolution of blockchain in the energy sector


At this year’s IEW held at Bengaluru, Singh spoke about both opportunities and
challenges when applying blockchain technology to the energy sector. He talked
of how in the early days, around 2015, companies exploring the potential of
blockchain tended to look for solutions within single organisations. But it soon
emerged that the utility space needed groups or consortiums to work together
as partners, on a common platform.
Using the oil sector as an example, Singh turned the spotlight on oil traders.
From these traders’ points of view, positioned in the middle of the extraction-
to-market chain, there are innumerable transactions, involving asking oil
producers for quotations, and placing orders directly with sellers and carriers
like tanker fleet owners, etc. All these transactions need support from banks
and regulatory authorities.
Further, these middlemen or traders then transact with buyers, who can be
traders themselves, or governments and firms in the Big Oil league. These set
of transactions require regulatory approvals, as oil is shipped across national
and international boundaries, being subjected to tax and duties. These also
require finance, which is usually in the form of credit.
With diverse firms operating on different systems, these transactions take
an unnecessarily long time, leading to lost man hours, delayed deliveries
and money lost during a slower business cycle.
Now, consortiums comprising every entity in the ecosystem—oil producers,
traders, banks and buyers—are being formed. All members will work on a
common platform, on which records of every successful transaction and contract
are tokenised in a chain of blocks, on view for all to see. This transparency
enables bankers to finance an operation with greater confidence, buyers to
check the due diligence on a large supply and oil commodity traders to get
more transparent.
70 | Chapter 13: Blockchain In The Energy Sector

This is the model that the electricity utility sector is looking at—in
particular, the renewable energy segment.

Limited in scope?
The renewable energy market in the US is currently estimated to be US$ 7
billion. This suggests that blockchain-based trading has a vast scope here.
Yet, scaled-out models are few, at the moment. Blockchain + IoT in the utility
space appears to still be a work-in-progress.
In March 2016, Massachusetts Institute of Technology (MIT) Enterprise
Forum of Cambridge, Massachusetts, played host to an interesting presentation.
Ewald Hesse, chief executive officer, Grid Singularity—Austria-based startup
in the blockchain space—was on stage. He presented a unique case study of
blockchain usage.
In Soweto, a poor outer suburb of Johannesburg, South Africa, most homes
are off-grid. Lorien Gamaroff, chief executive officer, Bankymoon—South
African blockchain firm—decided to step in and somewhat adopt a local
school. Bankymoon set up a smart meter at the school that is programmed to
accept digital currency. This meter is also linked to a platform where donors
can donate Bitcoin. As long as the cryptocurrency has not all been spent, the
local utility supplies the school with electricity. When the currency runs out,
the school goes off-grid.
Across the world, at Boston, Hesse shared his video call with Gamaroff with
the audience at MIT Enterprise Forum. On the large screen on an MIT stage,
the distant Soweto school was seen to be in darkness. And, when someone from
Boston donated one Bitcoin on Bankymoon’s platform, the school lit up to the
sound of applause from the children in Soweto.
This pilot shows one way that blockchain can be used by the donor community.
This would involve no middlemen, nor high overheads of organisations like
Oxfam, United Nations and Red Cross, where administration costs are known
to eat up about 30 per cent of donations, and often even more.

The way forward


As Singh mentioned in his IEW talk, the way forward lies in forming large
consortiums, with many partners from different levels of a sector’s ecosystem,
working on a common platform. Grid Singularity has tied up with the well-
respected US-based NGO, Rocky Mountain Institute, to form Energy Web
Foundation. This has many partners and users, like Shell, ShareCharge,
Wipro and a host of other big utilities and blockchain solution providers.
If this platform gets more accepted and signs on partners from across the
globe, the interesting PoCs and pilots being demonstrated in isolated pockets
around the world could probably scale out efficiently, truly demonstrating
how blockchain could save millions of dollars in cutting out middlemen.
Chapter 13: Blockchain In The Energy Sector | 71

In the Indian context, energy distribution is entirely in the hands of the


government and, hence, locked up in bureaucratic red tape. Apart from that,
distribution infrastructure is dated. In response to an audience-member’s
question about India’s readiness for blockchain application, Singh said, “In
India, we are still dealing with electricity theft.” Sadly, the country is struggling
with that, as well as electricity loss due to inefficient systems.
Further, getting all the country’s states onto a common platform itself
would pose quite a challenge. And then, upgrading its vast distribution
network to the level of smartness required to enable blockchain usage lies
many years in the future.
If at all opportunities exist for blockchain application in the Indian energy
space, it could be in renewable energy alone, and possibly in vast gated technology
parks or housing estates, where smartness has already been built into the
infrastructure. Some examples are smart access control, smart surveillance
and IoT usage to ensure efficient energy usage. With such infrastructure as a
base, it would be possible to replicate the Brooklyn Grid experiment in India.
72 |

Chapter 14

Geospatial Applications of Blockchain


Blockchain can be regarded as the world’s leading software platform for
digital assets. It is a continually growing list of records, called blocks,
which are linked and secured by using cryptography. A blockchain
inherently resists the modification of data.

In the early stages of the Internet’s evolution, computers required a specialised


language like humans, in order to communicate. For instance, carpenters
use certain terms that are well understood amongst them, just as doctors
do or even sailors. Each group uses a shared language that is designed to
enhance precision and clarity within its profession.
Computers use protocols to interact with one another. These protocols
include HTTP, which is used to access the Internet through a Web browser;
SMTP, which helps deliver emails to the right recipients; and SNMP, which
is used for building a computer network.
These protocols are invisible to us and we only see the applications that
take advantage of them. For instance, we use Internet Explorer or the Firefox
browser to access websites, while Outlook provides access to our email.
SNMP is virtually invisible to most of us unless we’ve worked on a computer
network that’s bigger than the basic router setup most of us use at home.

Enter blockchain
After the release of the bitcoin in 2009, blockchain slowly became an
Internet protocol that transmitted value from node to node. One can think
of blockchain as a way that allows different computers to talk to one another
using the language of cryptography. It is a peer-to-peer network; thus the
information exchanged does not require centralised servers. Since there is
no central server that ‘runs’ a blockchain, it is incredibly difficult to use the
current denial-of-service attacks on it, which work on centralised applications.
A blockchain is a digital, decentralised, peer-to-peer, immutable, public,
shared ledger/registry. Each transaction has a string of characters called a
hash. Each hash includes a date/time stamp, a unique ID, a code linking
it to the previous hash and a private key identifying ownership, albeit
Chapter 14: Geospatial Applications of Blockchain | 73

anonymously. Each transaction is another link in a chain that can be


traced backwards to the previous link, all the way back to the origin of
the entire chain, which is called the Genesis Block.
Unlike other databases or registries, a blockchain doesn’t reside on a
single computer and is not controlled by any person or any group of people.
It resides on an open network of computers (also called nodes) where all
nodes are equal – no super node manages the other nodes. Anyone can
download the software and become a fully qualified node in the network,
and all nodes carry a full copy of the blockchain registry. Data can only be
entered or transferred with encrypted signatures using private encryption
keys that only the owner of each particular data entry possesses. Nodes on
a network record each transaction, and these transactions are mirrored
on every other node throughout the network.
The transactions can be accessed and downloaded from any node on
the network. This makes a blockchain an open and distributed ledger.
When a node is out of sync with other nodes on the network, it is rejected
until it is reset to match the other nodes. That makes it impossible to alter
any records, making a blockchain immutable.
For these reasons, integrity is built into the blockchain. Anonymity is
provided by a private key that ties it to a digital wallet, which can only
be accessed by the owner. The digital wallet connects to the owner, but
not to the blockchain itself. As a result, a blockchain identifies the ‘what,
when and who’ about each transaction, but does not provide information
on where the transaction occurred. At this point in time, blockchains lack
the geospatial capability.

Public vs private blockchain


Public blockchain: The most visible implementation of a public blockchain is
the bitcoin network. Here, a potential member has to open a wallet to which
the system assigns a private key. The member can now transact with others
on the network, paying by bitcoins for goods, services, data, documents,
etc. The public blockchain has two drawbacks. The first is the validation
process, which can take time as there are many users. The second is the
block size which cannot be too big; hence, only the transaction details can
be carried and not the object of the transaction—for example, documents.
Private blockchain: On the other hand, private blockchains can be
created and run by institutions like government departments, industries
and companies, and maybe even NGOs. Private blockchains avoid these
problems by restricting the number of users. Membership to a private
blockchain is by invitation. Though others may be able to view the
transactions, they cannot participate in them. The rules governing the
private blockchain can be changed easily by the administrators and
backtracking of transactions may be allowed by them. The validators
74 | Chapter 14: Geospatial Applications of Blockchain

(miners in public blockchains) are trusted by the institution. Transaction


costs are lower than in public blockchains, and malfunctioning nodes can
be quickly spotted and repaired.

Blockchain and GIS applications


The unprecedented growth of blockchains has taken these beyond cryptocurrencies,
and people appreciate the public ledger, peer-to-peer networks and no-trust-
required transactions like never before. Integration of such a technology is
slowly gaining momentum in GIS. Open data initiatives across the globe have
resulted in successful spatial data infrastructures. However, the repositories for
the data are developed and maintained by central organisations. This means
there is a chance of bias as well as ‘control’ in data management.

Genesis Second Current/Last


First Block Block
Block Block

Block 0 Block 1 Block 2 Block n

HEADER HEADER HEADER HEADER

TIMESSTAMP Block0 Hash Block1 Hash Blockn-1 Hash


TIMESTAMP1 TIMESTAMP2 TIMESTAMPn
N ONCE
N ONCEn
N ONCE1 N ONCE2

Transactions Transactions Transactions Transactions

Older Newer

Figure 1: A simplified bitcoin blockchain

In geospatial terms, two domains that attract blockchain implementation are


land transactions and data repositories. In the case of land records, there is no
established trust between the participants and there is a need for openness.
While geospatial technologies have had a huge impact on the digitisation of
spatial land records, the transaction data related to these records tends to lose
synchronism as it is maintained in different databases. Typically, the 7/12 land
records lie with the Revenue Department of the state, while the registration
records are with the Department of Stamps and Registration, and spatial data
are maintained by the Land Records Department. Blockchain provides the
capability to create a decentralised system that stores geodata with no central
control, and yet everyone has access to the data and its history.
There are software products available in the market that allow the
publishing of spatial data to the public, spatial data exchange within an
organisation and the transfer of private spatial data between different
organisations using blockchain technology. Two good examples are Atlaschain
and FOAM.
Chapter 14: Geospatial Applications of Blockchain | 75

Use cases
Here are some other geospatial applications:
ƒƒ Public data: Street maps, terrain models, aerial footage or sea maps can
be made publicly available without a central hub that can restrict access
to the data; contributors to the map can be rewarded with tokens, and a
public record can be kept of changes and contributions.
ƒƒ IoT-autonomous devices and apps: These include devices that negotiate
with and pay each other, such as drones that negotiate use of air space,
self-driving cars that negotiate lane space or pay for road usage, mobile/
wearable devices that pay for public transportation, and apps similar to
Uber and Airbnb that connect clients and providers without a middleman.
ƒƒ Elections: In a free republic, the integrity of elections must be protected
and made fully transparent. Geotagged blockchain election ballots offer
an immutable record of the election. A little geospatial analysis can easily
detect locations where multiple votes indicate possible voter fraud. Add
the requirement to have a private key associated with each voter, and
voter fraud can be eliminated entirely.
76 |

Chapter 15

Blockchain and Cloud Storage


Blockchain has revolutionised the Internet. This new and ingenious technology
allows blocks of data to be distributed across ledgers, without any central
administering authority, but with the essential requirement that the data be
validated by participants. This makes the data open and secure. Blockchain
technology can be used to great advantage in cloud storage solutions.

Blockchain technology is one of the greatest inventions of today. You would


have heard about digital currency, cryptocurrency or Bitcoin. These are possible
because of blockchain technology. In this article, we will first understand
what blockchain technology is and how it works, and then we will look at
how we can correlate cloud computing with blockchain technology.
The blockchain was invented in 2008 by a person or group of persons
called Satoshi Nakamoto. Till date, no one knows who Satoshi Nakamoto
is, and whether he is a person or whether the name represents a group of
people. Blockchain has evolved into something very powerful since then.
Blockchain technology is built using peer-to-peer networking. Anyone can
join the network and there is no central authority to manage it. It is operated
by people, called miners, who lend their computing power to the network
in order to solve complex algorithms. Machines run by miners perform the
necessary functions to solve the algorithms, and for that they are rewarded
with a fee (for lending their computing power). In the case of Bitcoin, that
complex algorithm is SHA-256.
In a blockchain, each block stores the data of the transaction, its hash
code and the previous block’s hash code. So whenever a new block is
created, it is validated by a majority of the peers or miners on that network.
If anyone tries to change the data in one block, the entire blockchain will

“The blockchain is an incorruptible digital ledger of economic


transactions that can be programmed to record not just financial
transactions but virtually everything of value.”
—Don and Alex Tapscott, authors of ‘The Blockchain Revolution’
Chapter 15: Blockchain and Cloud Storage | 77

be invalidated; so it’s nearly impossible for an individual to change all other


attached blocks—and that’s how a blockchain remains secure and managed.
Also, all the data is encrypted for security purposes. Bitcoin works on the
same technology. It is a virtual currency that is mined using the blockchain
technique and today, the value of one Bitcoin is `458,609. So, as you can
imagine, it’s virtually like gold.
This blockchain technology is not just used for cryptocurrencies but can
be used in many other sectors also. Potential use cases are video or audio
streaming, cloud storage and much more. Today, a lot of research is going
on to study how to tap the power of this technology and apply it across
various verticals.

Figure 1: Cloud storage

Cloud storage
Google Drive, Dropbox, Gmail, etc, are the basic examples of cloud storage.
Cloud storage allows users to store their data online and hence access it
anywhere and at any time — that’s the biggest advantage. Nowadays, we store
all data in the digital format, having moved beyond the stage of managing
bundles of physical files. Government agencies are also leveraging the
advantages of cloud storage and availing the benefits of public and private
clouds to store, manage and manipulate data. All the data stored in the
cloud is encrypted and cloud services are available under a range of SLAs,
covering data integrity and privacy. Many companies have shifted their
entire data centre onto the cloud and enjoy advantages like elasticity, load
balancing, redundancy, availability and integrity. This market is expanding
at an exponential rate, currently, with the majority of cloud storage being
provided by large companies like Google, Microsoft and Amazon. You may
78 | Chapter 15: Blockchain and Cloud Storage

have observed that even mobile companies like Samsung and Apple now
have their own cloud storage offerings, such as Samsung Cloud and iCloud,
for end users.

Blockchain in cloud storage


Blockchain cloud storage solutions take the user’s data and break it up into
small chunks. They then add an additional layer of security and distribute
it throughout the network. This is possible using blockchain features like
the hashing function, public/private key encryption and transaction ledgers.
Each chunk of data is stored in a decentralised location. If intruders try to
hack into it, they first get encrypted data, and then get only a chunk of the
data and not the whole file–this secures documents in blockchain based
cloud storage.
Another benefit is that the owner is hidden since the node does not
store the owner’s data. The miner only gets a chunk of data; hence, all the
sensitive information is protected and secured. Data redundancy and load
balancing mechanisms are applied for high availability and quick access.
Whenever a user tries to fetch data, all chunks of the data are first validated
and if any alteration is found on a data chunk, then the miner who altered
the data chunk is removed from the network, and that altered part is taken
from another redundant copy. Thus, all users get original and identical
copies of the data.
Many new companies have jumped into this new blockchain cloud storage
market and the entire business is taking on a new shape. Blockchain is the
newest and possibly the cheapest way to get cloud storage because many
small entities participate in cloud storage by providing their computing power
and space to store data. Hence, cloud storage costs are lowered and all the
entities that participate can also get paid.
Companies like Sia, Amazon and Storj are creating systems for paying
a small amount to such participants for providing the extra storage from
their computers. So, in the near future, we can see many more cloud storage
providers moving to this technology. In the coming articles, we will talk
about blockchain based cloud applications and how to create your own
cryptocurrency.
| 79

Chapter 16

Applying Blockchain in Gaming Industry


The techies in the gaming industry have always been the early adopters of
technology and right now, they are excited about blockchains – now believed
to be the world’s leading software platform for digital assets.

After being successfully applied in almost every field, like finance, agriculture
and in geospatial areas, blockchain – the decentralised technology developed
by an elusive Satoshi Nakamoto, is now making an entry into the gaming
space as well. In fact, some believe that the gaming industry will be the first
to see the next generation using blockchain technology.

The journey of the gaming industry


Since ancient times, games have been a part of human culture. Back then,
games were limited to the real world. With the advances in technology, the
era of video games began, followed by games on PCs and mobile phones.
These games were first limited to just one player or multiple players
who were physically present with each other. But all this changed as game
developers launched massively multi-player online (MMO) games, which
involved competing with a large number of remote players on the same server.
Now, these game developers are shifting their focus to blockchain technology.

A look at today’s gaming industry


The gaming industry has tremendous appeal for developers as well as the
players and investors. However, the industry still has several pain points for
both developers and players. Let’s get introduced to some of these so that
we know how blockchain can resolve them.
The fear of losing precious digital assets: Players spend so much
time and sometimes money to acquire their precious assets in the game
but there is always a fear that they may lose these any day. This could
occur because of several reasons such as the game creator going out of
business or some central authority banning them from playing the game.
This happens all the time as players do not own these digital assets, which
reside on a centralised server.
80 | Chapter 16: Applying Blockchain in Gaming Industry

The digital assets of one game have no value in another: Let’s suppose
a player has spent a lot of time and money to obtain a sword, in one particular
game. When he completes the game or just wants to move on to another
one, he cannot use that sword in the new game as it never really belonged to
him, even though he has spent time and money on acquiring it. He can no
longer use this sword or even exchange it for something else in another game.
Separate servers for different regions: In the massively multi-player
online role-playing games (MMORPG), separate servers are needed for different
regions. In fact, many sub-servers are also required to form the whole system.
So, even if there are only a few players, but they are from different regions, a
large number of servers will be in use. Besides, if one server crashes, players
from an entire large area will lose connectivity.
Micro-transactions are a myth: The ‘free-to-play’ games are entirely
based on the strategy to offer early users low-cost items and then upgrade
them, step by step, by luring them into spending what seems like almost
negligible amounts of money, but which finally adds up to a large sum.
For example, a game company may offer a sword for US$ 15 and then
upgrade it to the next level at the rate of US$ 0.25. Game developers can
add hundreds of upgraded features in this way, and players do not think
too much about buying something worth US$ 0.25 at one time. Hence,
many players buy the sword and keep updating it, at different stages of
the game, without actually knowing how much they end up spending on
it. But traditional payment methods do not allow these micro-transactions.
Even payment channels like Paypal charge US$ 0.25 + 2.5 per cent of the
transaction amount. Thereby, true micro-transactions are a myth in the
gaming industry right now.
Developers lose money in customer support: The credit card companies,
especially in western countries, are pretty good at protecting their customers’
rights. If you have any issues regarding a purchase on your card, you are free
to raise a dispute and ask for your money back. In such cases, there is very
little a game developer can do, since the credit card company rarely listens
to them. Moreover, game developers must pay US$ 25 for every disputed
transaction. Because of this, the gaming industry loses millions of dollars
in customer support.

Blockchain to the rescue


Blockchain technology has the potential to end all these problems in the
gaming world. The games based on blockchain technology will offer solutions
for game developers as well as the players. There are infinite possibilities that
a blockchain has to offer but, for starters, there are several benefits that no
one can ignore. Here are some of them.
True ownership of virtual assets: In blockchain games, the virtual
assets of the player will belong to the player and the creators cannot take
Chapter 16: Applying Blockchain in Gaming Industry | 81

them away. These virtual assets may be stored in the form of tokens in the
player’s digital wallet. These tokens can be fungible (replaceable by another
identical item) or even non-fungible. With blockchain games, the players
will not have to worry about losing their digital assets even if they get
banned from the game, if the company shuts down or they quit the game.
Inter-game compatibility: As the characters, items or ‘karma’ of the
games are stored on your blockchain, it will allow you to see your existing
characters or items even on a completely unrelated game. It could open an
era for a new type of game in which characters from separate game genres
could play together in one game. In case you are building your own game,
instead of building new characters, you can use assets of an existing game
or invite players from the large game communities to instantly jump into
your game with the characters they already have. This is one of the coolest
features blockchain technology has to offer in the gaming industry.
Uniformity in the virtual assets of different games: The design
of blockchain games is fundamentally different from that of traditional
games. It does not allow the in-game currency to get generated infinitely.
Currently, in some games, while gold coins can be generated by just killing
some monster, in others, they might be a scarce resource. Blockchain will
end this infinite generation of coins in some games.
No Need for sub-servers: The blockchain technology in the MMORPG
will end the need to have different servers or even sub-servers for a different
region. Hence there will be no blackout in a particular region due to the
failure of local servers.
Cheap and secured trading of virtual assets: Blockchain will allow
users to convert their virtual assets into a token, making these free for
buying, selling and trading, at the will of the owner. The record of the
transaction will be on the blockchain itself, eliminating the threat of
fraudulent activities. The game characters, items, etc, can be managed
through smart contracts as has been done in Cryptokitties – a blockchain
game that has created much hype in the blockchain industry. Blockchain
technology even has the potential to offer micro-transactions involving the
cryptocurrency

Cases of early blockchain based gaming


Realising the potential of blockchain technology in the next generation of
online games, some developers have already started using it. Successful
projects range from blockchain game development platforms to innovative
payment gateways to buy games. While some of these blockchain based
games are already in the market, some others are in their beta phase and
some have raised funding through the process of Initial Coin Offering
(ICO). Every project has different aims but all of them together hold much
promise to build the future of gaming.
82 | Chapter 16: Applying Blockchain in Gaming Industry

Blockchain games in the market


There are several blockchain based games available in the market. Many
of them are built on top of the Ethereum blockchain, with Cryptokitties
being the most well known. This game uses ERC 721 tokens which are non-
fungible, indivisible and unique. It uses smart contracts for ownership and
for the distribution of virtual cats. This is considered as the first non-financial
application of blockchain technology.
Other blockchain games that are available in the market are Ethermons,
Cryptopets, Cryptopuppies, Etherarmy, etc. Ethereum is not the only
blockchain to attract game developers. A blockchain game called Spell of
Genesis is built on the Bitcoin blockchain.

Payment systems for games


There are several blockchain based platforms which have been built that
offer users the option to sell, buy and promote online games. Some of these
are GameCredits, Enjincoin and Refereum. Some gaming corporations like
Valve are even allowing users to buy games using Bitcoins.

Platforms for building blockchain based games


Platforms for building blockchain based games promise to offer all the new
features that we just discussed. They aim to simplify the ownership, sharing
and trading of virtual assets. Such platforms like BitGuild and Chimaera are
expected to get launched this year. There are several other platforms like
Decentraland and Voxels which are offering a virtual space for blockchain
based 3D graphics and games.
From the tokenisation of virtual goods to improving betting and payments,
every area of gaming is undergoing experimentation using blockchain
technology. While this technology has a lot to offer, there is an issue of speed,
especially when we talk about MMORPG. At present, there is a blockchain
based MMORPG, but it is still in its beta version.
| 83

Chapter 17

IoT Based Management of


Shared Resources
In this article, the authors discuss use cases for which blockchains and
IoT devices can be used, instead of intermediaries, for Trustless parties to
transact with each other. The authors also discuss the architecture and the
open source technologies that were used in their solution.

Governments, communities or companies often need to track, control and


manage assets and resources that they have a shared interest in. For example,
in the logistics industry, a perishable item might get transported from a
sender to a receiver. While in transit, the perishable item may have to be
kept under a certain temperature or pressure. The item may get transported
through multiple modes such as ship, train, truck, etc, and multiple transport
operators might be involved before it reaches its destination. Payments have
to be released to these parties if and only if they transported the item as per
the contract.
Often, there is no trust between the sender, receiver and the various
parties involved. This means that the parameters required to preserve a
perishable item have to be tracked and controlled. And there needs to be a
verifiable record of this tracking/controlling throughout the transportation
period. There is also a need for a trusted way to settle payments between the
various parties once the shipment has been delivered as per the contract.
Another use case is in the energy sector, where smart grids are used for
the distribution and consumption of electric power. There is a need for power
generators and distributors to track the supply and distribution of power,
and keep records of it, to eventually reconcile and settle accounts between
the producers and distributors of power. A third use case could be to manage
water resources stored in dams and shared between countries/states.
The list of such use cases is endless. Often these parties do not trust
each other and end up appointing an intermediary third-party trusted by
all of them to manage, control or track the resources, on their behalf. The
84 | Chapter 17: IoT Based Management of Shared Resources

intermediaries, however, may charge exorbitant fees for their services or


may become ineffective due to political/commercial reasons. Blockchain
and IoT technologies together provide a solution which can do away with
the intermediaries and autonomously track, control and manage resources
in a trusted way.

Blockchain
The blockchain is a peer-to-peer network. It is based on a shared ledger (the
blockchain database) and a protocol to keep the shared ledger updated. It is
the technology underlying Bitcoin, the famous crypto-currency. Bitcoin was
created by an unknown person nicknamed Satoshi Nakamoto. For people to
accept and adopt Bitcoin as a crypto-currency, they had to be able to trust it.
But, there is no government backing this crypto-currency. So, the trust has
to be provided by the Bitcoin network itself.
The technology that provides such trust for Bitcoin is the blockchain. It
is a shared ledger which is available on each full node of the network. In a
Blockchain, each block is analogous to a ledger page and the blockchain
is analogous to a ledger book. When a Bitcoin transaction happens on the
network, the miner nodes verify the validity of the transaction, arrive at a
consensus and update their copy of the ledger. The transactions verified
and entered in the blockchain are immutable. Since blockchain is a peer-to-
peer network, it does not have a central server. It has only peer level client
applications, which join the blockchain network as nodes.

Blockchain Network with Smart Contracts


Blockchain Network Node 1 Blockchain Network Node 2

Block 1 Block 2 Block M Block 1 Block 2 Block M

Peer-To-Peer Network

Blockchain
Shared Ledger Smart
Contract
Consensus Protocol

Block 1 Block 2 Block M Block 1 Block 2 Block M

Blockchain Network Node N-1 Blockchain Network Node Node N

Figure 1: Blockchain with smart contract

A blockchain provides some key benefits, which can be leveraged to provide


solutions for use cases such as the ones discussed earlier in this article. Since
it is a shared ledger on a peer-to-peer network, it does not have any central
server which can be shut down unilaterally by any one party or authority.
The records, transactions and smart contracts updated in the blockchain are
immutable. They cannot be modified. The shared ledger is updated based on
Chapter 17: IoT Based Management of Shared Resources | 85

a consensus protocol and hence it prevents users or those transacting with


Bitcoins from making fraudulent entries in the blockchain. This provides the
trust needed when parties unknown to each other have to transact without
an intermediary. Here, the blockchain network provides the trust.
There are a few open source platforms such as Ethereum, Hyperledger
and Stellar, using which we can create a blockchain network as a public
network, whereby any one can join the network. Alternatively, it can also be
a private network behind the firewall of an organisation so that only those
within the organisation can join it; or as a permissioned blockchain, where
only those who are permitted to join the blockchain can do so.

MQTT Publish Subscribe Broker

Sensor-Data Topic

Control-Data Topic

IoT Gateway

Microcontroller + Embedded
Transducer

Microcontroller + Embedded
Transducer
Networking Module Networking Module

Sensor 1 Sensor 1

Sensor 2 Sensor 2

Sensor 3 Sensor 3
Thing n Thing n

Figure 2: IoT thing server architecture

Smart contracts
The features of Blockchain, such as decentralisation, immutability,
verification, consensus and not being able to shut it down, provide a trustable
network which can replace any intermediary. Soon, many people realised
that the blockchain has the potential to be used for applications beyond
crypto-currency such as Bitcoin. It can be used as a platform to execute
or enforce contracts between unknown and hence untrusted parties in the
form of smart contracts. But this needed a Turing Complete blockchain
platform so that complex business logic could be written as code. The
Bitcoin blockchain is not Turing Complete by design to avoid hacks. Hence,
smart contracts cannot be written on the Bitcoin blockchain. This limitation
gave rise to other blockchain platforms which can be used to write smart
contracts, such as Ethereum, Hyperledger, etc.
86 | Chapter 17: IoT Based Management of Shared Resources

Smart contracts are posted on the blockchain network in the same way we
send crypto-currency. The posted contracts are added to the shared ledger
(blockchain database). Smart contracts implement complex business logic
as code. Each smart contract will have an address to which messages can
be posted. A smart contract executes upon getting the messages posted to
its address.
A client application connected to the blockchain network can receive
messages from real-world assets such as IoT devices and post them to the
smart contract. On getting the message, the smart contract executes and
sends the result back to the client application in the form of an asynchronous
event. This event can be used to control/manage the real-world assets.
In a way, smart contracts are analogous to the standing instructions given
to banks to perform tasks such as transferring money to another account
on specific dates, paying utility bills, etc. But, smart contracts implement
more complex business logic and leverage the properties of the blockchain
such as decentralisation, immutability and trust.

IoT
IoT (Internet of Things) is a network of things in the physical world. These
things may be devices which have sensors within them or attached to them. In
the context of IoT, a ‘thing’ is a server which is capable of getting sensor data
from the device and sending it to the backend applications. A ‘thing’ server
can be anything – a car, a refrigerator, a machine, a surveillance camera, a

Solution Architecture
Hive MQTT Broker IoT Device
(Publish/Subscriber)

Topic/Sensor Data MQTT


Sensors
Topic/Control data MQTT Light
Temp Humidity
Intensity
T
QT
M M Device Under Control
T M Q
QT Q TT
M TT

Blockchain – Node1
Blockchain – Node2
Node JS + MQTT
library Node JS + MQTT
library
Admin/Controller Role

Web Socket Blockchain


Observer Role

Web 3 Web 3 Web Socket


Shared Ledger &
Smart Contracts
Web - based
on all Nodes
Admin Web - based
Dashboard Dashboard

Figure 3: IoT-blockchain PoC architecture


Chapter 17: IoT Based Management of Shared Resources | 87

fan, a light, etc. IoT uses a local gateway server to connect the various thing
servers in a building, car, etc, to the backend application. Thing servers use
various communication technologies such as RFID, NFC, Wi-Fi, Bluetooth,
and ZigBee to send data to the gateway server. Thing servers can also have
wide area connectivity such as GSM, GPRS, 3G and LTE. On top of this
communication infrastructure, IoT uses the MQTT protocol to connect the
thing servers with the backend applications.

MQTT messaging protocol


The IoT thing servers may generate various types of data. Different backend
applications might be interested in different types of data. The data exchange
between the thing servers and the backend applications should happen
asynchronously. There should not be any dependency on both of them to
be alive at the same time to send and receive data.
To address this kind of a need, a publish/subscribe broker can be used in
the architecture. HiveMQ is an open source publish/subscribe broker which
uses the MQTT protocol to talk to the IoT thing servers on the one hand and
to the backend applications on the other. The MQTT protocol works on the
basis of topics. IoT thing servers can register topics with the HiveMQ broker.
They will publish sensor data as messages on those topics. The backend
servers will subscribe to those messages.
Once an IoT thing server publishes a message on a specific topic, the
HiveMQ broker sends that message to all the backend servers which
have subscribed to that topic. Similarly, if the backend servers want to
send any control information to the IoT thing servers, they can register
the control topics with the HiveMQ broker and the IoT thing servers can
subscribe to those topics. This will establish a two-way communication
between the IoT things and the backend servers using the MQTT protocol
and the HiveMQ broker.

PoC
We did a Proof of Concept (PoC) implementation using IoT, blockchain and
MQTT to control a transducer. The building blocks of the PoC, and the open
source technologies with which they were implemented, are explained below:
ƒƒ A cloud based HiveMQ server was used as the MQTT publish/subscribe
broker. On this broker, the IoT thing server registers a topic on which
it publishes the sensor data and the blockchain node registers a topic
on which it publishes the control data. In addition, the IoT thing server
subscribes to receive the control data while the blockchain node subscribes
to receive the sensor data. The HiveMQ broker delivers the published
messages to subscribers.
ƒƒ ESP8266-12 was used as the IoT thing server. This had a temperature,
humidity and light sensor. It registered the sensor data topic with the
88 | Chapter 17: IoT Based Management of Shared Resources

cloud based HiveMQ MQTT broker and published the sensor data on this
topic. It subscribed to the control messages from the blockchain node.
ƒƒ A Node.js Web application, which subscribes to the sensor data topic
on the HiveMQ broker for getting the sensor data, was used. It registers
the topic on which it publishes the control messages on the HiveMQ
broker. Subsequently, it publishes the control messages received from
the blockchain. This Web application was connected to an Ethereum
blockchain using the web3 JavaScript library. It registers the smart
contract on the blockchain. It also posts the sensor data to the smart
contract and watches for the asynchronous control messages from the
smart contract. The control messages received from the smart contract
are published through the HiveMQ broker.
ƒƒ The smart contract was written using the Solidity language and compiled
using a Solc compiler. The compiled smart contract is posted to the
Ethereum blockchain using the web3 JavaScript
library from the blockchain node.

Logistics use case


Let us again look at the logistics use case mentioned at the beginning of this
article and see how the solution can be implemented. The perishable items
are packed in a container in which a thing server with the temperature/
pressure sensors is fitted. The sensor data is published through the MQTT
broker.
The various transport operators together could form a consortium and
start a blockchain network. In this case, the blockchain is a permissioned
one, where the consortium controls who can join its blockchain. Only
members of the consortium may be allowed to join the blockchain network.
Alternatively, the public Ethereum blockchain network can be used and
the smart contract can be deployed on it.
The transport operator may run a Web application on his node with an
easy-to-use user interface to create the smart contract on the blockchain.
The sender gets into a contract with the transport operator. The terms
and conditions of the transportation and payment are coded as a smart
contract and deployed on the blockchain. The payment may be locked up
in an escrow account.
The sensor data from the shipped container is received by the blockchain
nodes and posted to the smart contract, which verifies the recorded
temperature/pressure parameters as per the codified terms of the contract.
Upon successful delivery of the item, the smart contract will trigger the
payment from the escrow account. The payment will be completed in near
real-time.
In future, micro payments between machines and M2M (machine-
to-machine) communication without human intervention will find wide
Chapter 17: IoT Based Management of Shared Resources | 89

application. Today’s centralised client-server world is being augmented with


decentralised, peer-to-peer, disintermediated digital solutions. Blockchains
with smart contracts and IoT are the evolving technologies which will drive
such an exciting world.

Acknowledgements
The authors would like to acknowledge and thank Sriram Rajagopalan and
Sarav Daman of Wipro Limited for their critical review of the article and
contribution during the implementation of the PoC.
90 |

About the Authors

Swapnil Kulkarni
The author is an open source enthusiast with experience in blockchain, cloud
native solutions, containers and enterprise software product architectures. He
is a technology hobbyist and writes at cloudnativetech.wordpress.com.

Abhinav Nath Gupta


The author is a software development engineer at Cleo Software India Pvt Ltd,
Bengaluru. He is interested in cryptography, data security, cryptocurrency
and cloud computing. He can be reached at [email protected].

Janani Gopalakrishnan Vikram


She is a technically-qualified freelance writer, editor and handson mom based
in Chennai.

Pragati Aggarwal
The author is a technology journalist at OSFY.

Dr Anand Nayyar
The author works at Duy Tan University in Vietnam. He loves to work and
research on open source technologies, sensor communications, network secu-
rity, the Internet of Things, etc. He can be reached at anandnayyar@duytan.
edu.vn. YouTube channel: Gyaan with Anand Nayyar at www.youtube.com/
anandnayyar.

Shakshi Talwar
The author is passionate about helping people in all aspects of Internet mar-
keting. She enjoys holidays, travelling and generating business ideas.
| 91

Prabal Banerjee
The author is currently a PhD student at the Cryptology and Security Research
Unit, Indian Statistical Institute. His current interests are exchanging or audit-
ing data on blockchains, and studying their privacy and security issues. He can
be reached at http://www.cmi.ac.in/~prabal/.

Maulik Parekh
The author works at Cisco as a consulting engineer and has an M. Tech in
cloud computing from VIT University, Chennai. He constantly strives to learn,
grow and innovate. He can be reached at [email protected]. Website:
https://www.linkedin.com/in/maulikparekh2.

Miren Karamta
The author is a project scientist and IT systems manager at the Bhaskaracha-
rya Institute for Space Applications and Geo-informatics (BISAG), Gandhinagar,
Gujarat. You can reach him via email at [email protected]. LinkedIn:
https://in.linkedin.com/in/miren-karamta-2b929122.

Venkatachalam Subramanian
Venkatachalam Subramanian is a principal consultant in talent transformation,
Wipro Limited, Bengaluru. He has 20 years of experience in the IT industry.

Sumanta Basu
Sumanta Basu is a senior architect in the communications vertical, Wipro Lim-
ited, Bengaluru. He has more than 12 years of experience in the IT industry.

You might also like