BlockChain_ project
BlockChain_ project
| 1
B LOC KC HAIN
FOR DEVELOPERS
| 3
Table of Contents
4 The Beauty of the Blockchain.....................................Swapnil Kulkarni
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 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.
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.
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.
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.
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.
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
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();
}
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.
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;
}
}
return true;
}
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
Chapter 3
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.
Chapter 4
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.
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
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
Event Stream
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
vault vault
txns txns
Bank
Quorum
Network
Bank
Regulator
Quorum
Private & Quorum Constellation
Public Node
transactions Data
go-ethereum
Transaction
Enclave encryption
Mangager
Off-chain
payload
storage
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
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
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
Chapter 7
Discover Ethereum
Dive into the world of blockchains, and use Ethereum to host a private
network and deploy a smart contract.
$ 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
$ cd ~/workspace
Chapter 7: Discover Ethereum | 39
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:
> eth.sendTransaction({from:eth.accounts[0],
to:”0xba993910008b3940626c83135fa2412b4a91b3b1”, value: web3.toWei(6, “ether”)})
contract Basic {
//declaring an unsigned interger. Let’s make it private
uint private variable;
42 | Chapter 7: Discover Ethereum
//this functions sets the value of the stored variable to the passed argument value
function set (uint x) public {
variable = x;
}
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.
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.
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.
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
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
CouchDB
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.
MSP
Fabric-CA
Fabric-CA
API
External-CA
API
External-CA
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
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.
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.
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.
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
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
Journal
Transaction verification
and Consensus
Completer
Transaction
Processing
Platform
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.
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.
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
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
Stateless
Validation
Transaction
Client Peer
Torii
Transaction
Validated
Transactions
Ordering Service
are ordered
Proposals
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.
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.
Chapter 13
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!
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.
Chapter 14
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
Older Newer
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
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.
Chapter 16
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 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.
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
Chapter 17
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.
Peer-To-Peer Network
Blockchain
Shared Ledger Smart
Contract
Consensus Protocol
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
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)
Blockchain – Node1
Blockchain – Node2
Node JS + MQTT
library Node JS + MQTT
library
Admin/Controller Role
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.
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.
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 |
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.
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.