You are on page 1of 181

CHAPTER 1

INTRODUCTION TO BLOCKCHAIN

S Tuart Haber and W. Scott Stornetta, first described the


blockchain concept in 1991. They intended to offer a
computationally feasible approach for time-stamping digital
documents to prevent them from being modified or tampered
with. They created a system that could store time-stamped
documents using a cryptographically secure chain of blocks.

Hal Finney, a computer scientist, and cryptographic activist


proposed the Reusable Proof of Work (RPoW) system as a
prototype for digital payment in 2004. It was a pivotal moment in
the history of cryptocurrency. The RPoW system created an RSA-
signed token to interchangeable Hash based cash POW that could
be transferred from person to person. The double-spending
problem was overcome by RPoW by registering the ownership of
tokens on a trusted server. The addition of this server can ensure
the system’s accuracy and integrity in real-time.

Satoshi Nakamoto materialized the principle of distributed


blockchains in 2008. He improved the architecture by adding
blocks to the initial chain without requiring the blocks to be signed
by trustworthy parties. A secure history of data transfers also

1
Introduction to Blockchain Technology

called transactions is stored among multiple nodes. Participant


timestamps and verifies each transaction via a peer-to-peer
network. This is managed without the need for a central authority.
Blockchains have become the backbone of cryptocurrencies
because of these advancements. Today, the design acts as the
public record for all cryptocurrency transactions. In the next
section, we discuss centralized and decentralized concepts to
explain blockchain technology.

Centralization VS Decentralization Concepts

A centralized system, as the name implies, has a single point of


control over all administrative tasks. Figure 1.1 shows an example
of a centralized system. Several clients are connected to a
centralized server. Such systems are simple to design, manage,
establish trust, and govern, yet they have several intrinsic flaws,
including the following:

1. A centralized system has a single point of failure, so are


less stable. Notice Figure 1.1, if the server is down, all
clients get disconnected from the server.

2. Centralized systems are more vulnerable to attack and


hence less secured.

3. All authorities are provided to the server. This


centralization of power can make the server do unethical
operations.

4. Limited numbers of clients can be connected to a server for


providing better performances. Therefore, scalability of
such systems is difficult most of the time.

2
Introduction to Blockchain Technology

Figure 1.1: A centralized system

A decentralized system, as the name implies, has no centralized


control, and each node has equal authority. It is difficult to build,
manage, govern, or impose trust in such systems. They do not,
however, suffer from the drawbacks of traditional centralized
systems. The following are some of the benefits of decentralized
systems: Figure 1.2 depicts an example of a decentralized system.

1. They are more stable and fault resistant since they do not
have a single point of failure. If a client becomes
detached from the server, it doesn’t have any effect on
other clients of the server.

2. Each client manages their own transaction copy, and they


are responsible for their own security. So, there is no
single point to attack, the system is more secure.

3
Introduction to Blockchain Technology

3. Symmetrical system with equal authority for everybody,


limits the scope of unethical behavior and is typically
democratic in nature.

Figure 1.2: A decentralized system

Definition of Blockchain

A blockchain is a distributed database that allows direct


transactions among two parties without the need for a central
authority. This simple yet powerful concept has far-reaching
implications for a wide range of institutions, including banks,
governments, and marketplaces, to mention a few. Blockchain
technology has the potential to disrupt any business or
organization that depends on a centralized database as a
competitive advantage.

4
Introduction to Blockchain Technology

Figure 1.3: The chain of block in blockchain technology

It is important to note that a distributed system can also be


decentralized just as blockchain. However, unlike other distributed
systems, the task is not divided and delegated to nodes in
blockchain because there is no master to do so. The interested
nodes (or the ones chosen at random) perform the entire task,
rather than the contributing nodes working on a piece of it. The
following diagram (Figure 1.3) depicts a typical decentralized and
distributed system, which is effectively a peer-to-peer system.

Figure 1.3: A blockchain distributed peer to peer network

5
Introduction to Blockchain Technology

How blockchain dependent cryptocurrencies work?

Assume that there are three candidates: Alice, Bob, and Charlie
who are doing some monetary transactions among each other on a
blockchain network. Let us go through the transactions step by
step to understand blockchain’s open and decentralized features.

Step 01: Assume Alice had $50 in her possession, which is the
starting point for all transactions, and that every node is aware of
it, as depicted in Figure 1.4-1.6.

Charlie Alice

Genesis block
Genesis block Alice has 50$
Alice has 50$

Genesis block
Genesis block
Alice has 50$ Alice has 50$

Shelly Bob

Figure 1.4: Alice has 50$ and all participants have this information

Step 02: Alice completes a transaction by paying Bob $20.


Examine how each node updates the blockchain, as depicted in
Figure 1.5.

6
Introduction to Blockchain Technology

Charlie Alice

Genesis block
Alice has 50$
Genesis block Alice →Bob: 20$

Alice pays $20 to Bob.


Alice has 50$

Alice →Bob: 20$

Genesis block Genesis block

Alice has 50$ Alice has 50$


Shelly Alice →Bob: 20$
Alice →Bob: 20$ Bob

Figure 1.5: Alice pays $20 to Bob and every participant has this
information including the previous records.

Step 03: As seen in Figure 1-6, Bob makes another transaction by


sending $10 to Charlie, and the blockchain is updated.

Charlie
Alice

Genesis block
Genesis block Alice has 50$
Alice pays $20 to Bob.

Alice has 50$ Alice →Bob: 20$

Alice →Bob: 20$ Bob →Charlie: 10$


Bob →Charlie: 10$

Genesis block Genesis block

Alice has 50$ Alice has 50$

Alice →Bob: 20$ Alice →Bob: 20$


Bob
Shelly
Bob →Charlie: 10$ Bob →Charlie: 10$

Figure 1.6: Bob pays $10 to Alice

7
Introduction to Blockchain Technology

Keep in mind that the transaction data stored in the blocks is


unchangeable. All transactions are final and cannot be reversed.
Any modification would generate a new transaction that would be
validated by all participating nodes. Every node has its own
blockchain copy.

You may have a lot of questions, such as "What if Alice sends the
same amount to Dave to double-spend the same amount, or what
if she's making a payment without adequate cash in her account?"
"How is the security ensured?" and so on. In the following
chapters, we will go through those specifics.

Exercise

1. Determine if the statement is true or false. If false, provide


the true answer.

a. Blockchain concept was first known in 1992.

b. Bitcoin was built by Satoshi Nakamoto in 2008.

c. Blockchain’s network differs from the conventional


decentralized network.

d. Blockchian suffers from double spending attacks.

e. Centralized system is vulnerable to a single point


of failure.

2. “Blockchain technology is the basis of cryptocurrency”,


Justify the statement.

3. What are the challenges of a centralized system that a


decentralized system can overcome?

8
Introduction to Blockchain Technology

4. How does decentralization differ from conventional


distributed systems?

5. Suppose there are four participants named A, B, C, and D in


a blockchain peer to peer network. First transaction: A has
$50, A sends $10 to B. Second transaction: B pays $15 to C.
Third Transaction: D pays $5 to A. Demonstrate how these
transactions will be recorded on the blockchain network.

9
Introduction to Blockchain Technology

CHAPTER 2
BLOCKCHAIN FUNDAMENTALS

The modern concept of cryptocurrencies started with a white


paper published in 2008 by Satoshi Nakamoto, an unknown person
or organization. The white paper, titled "Bitcoin: A Peer-to-Peer
Electronic Cash System," lay the groundwork for what is now
known as Blockchain. Satoshi detailed how to create a peer-to-
peer electronic cash system in the initial Bitcoin white paper,
which allows internet payments to be transmitted directly from
one party to another without passing through a centralized
organization. This technique addresses a significant issue in
digital money known as double-spending. In chapter 1, we
described the brief history of blockchain technology. This chapter
will cover the double spending attack and layer wise description of
blockchain technology.

Double-Spending

Assume Alice wishes to pay Bob $1. If Alice and Bob pay with
actual currency, Alice will lose the $1 when the transaction is
completed. The dilemma becomes more difficult if Alice and Bob
use digital money. Digital money is in the form of a digital file that
can be easily copied. If Alice sends Bob a $1 digital file over email,
for example, Bob has no way of knowing if Alice has deleted her
copy of the file. If Alice still has the $1 digital file, she has the
option of sending it to Carol. Double spending is the term for this
issue.

10
Introduction to Blockchain Technology

Carol

Alice

Bob

Figure 2.1: If Alice sends money in digital format to Bob. Bob


cannot know for sure if Alice has deleted her copy of the file and
she can choose to send the same file to Carol.

One solution to the double-spending problem is to place a trusted


third party (such as a bank) between Alice, Bob, and the rest of the
network participants. This third party oversees maintaining a
centralized ledger that records and validates all network
transactions. The disadvantage of this technique is that it
necessitates faith in a centralized third party for it to work.

11
Introduction to Blockchain Technology

Figure 2.2: A Bitcoin blockchain example

Bitcoin: A Decentralized Solution for the Double-


Spending Problem

Satoshi proposed a public ledger, i.e. Bitcoin's blockchain, to keep


track of all transactions in the network to solve the double-
spending problem. The Bitcoin blockchain contains the following
features:

▪ Distributed: Rather than being maintained on a central


server, the ledger is replicated among several machines. A
full copy of the blockchain can be downloaded to any
computer with an internet connection.
▪ Cryptographic: Cryptography is employed to ensure that
the sender has the bitcoin she is attempting to transmit, as
well as to determine how transactions are added to the
blockchain.

12
Introduction to Blockchain Technology

▪ Immutable: Only appends to the blockchain can be


modified. To put it another way, transactions can only be
added to the blockchain, not erased, or modified.

Proof of Work (PoW) is a term used to describe the act of


demonstrating that something has been done. Miners are a
specific type of network participant that compete to solve a
cryptographic challenge that allows them to add a block of
transactions to Bitcoin's blockchain. Proof of Work is a procedure
that ensures the security of the system (more on this later).
Sending bitcoin money goes as follows:

▪ Step1: Create a bitcoin wallet as the first step (a one-time


effort). To send or receive bitcoins, one must first construct
a bitcoin wallet. A bitcoin wallet contains two types of
data: a private key and a public key. The private key is a
secret number that enables the owner to send bitcoin to
another user or spend bitcoins on services that accept
bitcoin as payment. To receive bitcoins, you'll need to
know your public key. A bitcoin address is also known as a
public key (not entirely true, but for simplicity we will
assume that the public key and the bitcoin address are the
same). It's worth noting that the wallet doesn't hold the
bitcoins. It's worth noting that the wallet doesn't hold the
bitcoins. The Bitcoin blockchain stores information on
bitcoin balances.
▪ Step 2: To make a bitcoin transaction, follow the steps
below. If Alice wishes to send 1 BTC to Bob, she must first
connect to her bitcoin wallet using her private key and
initiate a transaction with the quantity of bitcoins she
wants to send and the address she wants them sent to (in
this case, Bob's public address).

13
Introduction to Blockchain Technology

▪ Step 3: Publish the transaction on the Bitcoin network.


Alice must broadcast the bitcoin transaction to the whole
Bitcoin network after she has created it.
▪ Step 4: Confirm that the transaction is complete. A miner
listening to the Bitcoin network authenticates the
transaction with Alice's public key, confirms that Alice has
enough bitcoins in her wallet (in this case at least 1 BTC),
and adds a new record to Bitcoin's Blockchain with the
transaction details.
▪ Step 5: All miners should be notified of the blockchain
modification. Once the transaction has been validated, the
miner should broadcast the blockchain change to all other
miners to ensure that their copies of the blockchain are all
up to date.

Blockchain Technology

Singhla et al described blockchain technology as an amalgamation


of cryptography, game theory and computer science. Ismail et al.
defined blockchain technology as a combination of distributed
ledger, consensus protocols, and cryptography. Ismail formulated
the blockchain as in equation,

Blockchain = (DL + CP + C), where DL= Distributed Ledger, CL=


Consensus Protocols, C= Cryptography.

14
Introduction to Blockchain Technology

Cryptography

Consensus
mechanism Distributed ledger

Figure 2.3: Theories of blockchain technology

Cryptography in Blockchain Technology

The goal of this section is to go deeper into the technical building


blocks that power the blockchain. We will cover public key
cryptography, hashing functions, mining, and security of the
blockchain. Two kinds of cryptographic techniques named
symmetric and asymmetric cryptography are described in the next
section. Below is an example how cryptography works to secure
user’s information over the internet.

15
Introduction to Blockchain Technology

Figure 2.5: An example of how cryptography works to secure


information

Symmetric Key Cryptography

In the previous section we looked at how Alice can encrypt a


message and send the ciphertext to Bob. Bob can then decrypt the
ciphertext to get the original message. If the same key is used for
both encryption and decryption, it is called symmetric key
cryptography. This means that both Alice and Bob have to agree
on a key (k) called “shared secret” before they exchange the
ciphertext.

Figure 2.6: Example of symmetric encryption to secure user’s


information

Public Key Cryptography (Asymmetric Key


Cryptography)

Public-key cryptography, or asymmetrical cryptography, is any


cryptographic system that uses pairs of keys: public keys which
may be disseminated widely, and private keys which are known
only to the owner. This accomplishes two functions:
authentication, where the public key verifies a holder of the paired
private key sent the message, and encryption, where only the
paired private key holder can decrypt the message encrypted with

16
Introduction to Blockchain Technology

the public key. RSA and Elliptic Curve Digital Signature (ECDSA)
are the most popular public-key cryptography algorithms.

In the case of Bitcoin, ECDSA algorithm is used to generate Bitcoin


wallets. Bitcoin uses a variety of keys and addresses, but for the
sake of simplicity, we will assume in this blog post that each
Bitcoin wallet has one pair of private/public keys and that a
Bitcoin address is the wallet's public key. I recommend this article,
if you're interested in the complete technical details of Bitcoin
wallets.

To send or receive BTCs, a user starts by generating a wallet which


contains a pair of private and public keys. If Alice wants to send
Bob some BTCs, she creates a transaction in which she enters both
her and Bob's public keys, and the amount of BTCs she wants to
send. She then signs the transaction using her private key. A
computer on the blockchain uses Alice's public key to verify that
the transaction is authentic and adds the transaction to a block
that will be later added to the blockchain.

17
Introduction to Blockchain Technology

Figure 2.7: Properties of public/private key and hash


operation

Asymmetric cryptography for confidentiality

Figure 2.8 shows how public and private key can be used to
perverse the confidentiality of two parties communicating over
insure channel.

18
Introduction to Blockchain Technology

Figure 2.8: Uses of public/private key to ensure confidentiality of


data

Asymmetric cryptography for authentication

The act of verifying an assertion, such as a computer system user's


identity, is known as authentication. Authentication is the process
of verifying a person's or thing's identity, as opposed to
identification, which is the act of indicating that person's or
thing's identity.

19
Introduction to Blockchain Technology

Figure 2.9: Usages of public/private key for user’s authentication.

Hashing, and Merkle Tree

One of the oldest hash functions or compression functions is the


MD4 hash function. It belongs to the message digest (MD) family.
Other members of the MD family are MD5 and MD6, and there are
many other variants of MD4 such as RIPEMD. The MD family of
algorithms produce a 128-bit message digest by consuming 512-bit

20
Introduction to Blockchain Technology

blocks. They were widely used as checksums to verify data


integrity. Many file servers or software repositories used to
provide a precomputed MD5 checksum, which the users could
check against the file they downloaded. However, there were a lot
of vulnerabilities found in the MD family and it was deprecated.
Another such hash function family is the Secure Hash Algorithm
(SHA) family. There are basically four algorithms in this family,
such as SHA-0, SHA-1, SHA-2, and SHA-3. The first algorithm
proposed in this family was named SHA, but newer versions were
coming with security fixes and updates, so a retronym was applied
to it and it was made SHA0. It was found to have a serious yet
undisclosed security flaw and was discontinued. Later, SHA-1 was
proposed as a replacement to SHA-0. SHA-1 had an extra
computational step that addressed the problem in SHA-0. Both
SHA-0 and SHA-1 were 160-bit hash functions that consumed 512-
bit block sizes. SHA-1 was designed by the National Security
Agency (NSA) to use it in the digital signature algorithm (DSA).

Figure 2.10: The process of hashing in cryptography

SHA-2
It belongs to the SHA family of hash functions, but itself is a
family of hash functions. It has many SHA variants such as SHA-
224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-
512/256. SHA-256 and SHA-512 are the primitive hash functions
and the other variants are derived from them.

21
Introduction to Blockchain Technology

SHA-256 and SHA-512

As mentioned already, SHA-256 belongs to the SHA-2 family of


hash functions, and this is the one used in Bitcoins! As the name
suggests, it produces a 256-bit hash value, hence the name. So, it
can provide 2^128-bit security as per the birthday paradox.

RIPEMD

RACE Integrity Primitives Evaluation Message Digest (RIPEMD)


hash function is a variant of the MD4 hash function with almost
the same design considerations. Since it is used in Bitcoins, we will
have a brief discussion on it. The original RIPEMD was of 128 bits,
later RIPEMD-160 was developed. There exist 128-, 256-, and 320-
bit versions of this algorithm, called RIPEMD-128, RIPEMD-256,
and RIPEMD-320, respectively, but we will limit our discussion to
the most popular and widely used RIPEMD-160.

Message Word Message Digest


Block Size
Algorithm Size Size Size
(bits)
(bits) (bits) (bits)
SHA-1 < 264 512 32 160
SHA-224 < 264 512 32 224
SHA-256 < 264 512 32 256
SHA-384 < 2128 1024 64 384
SHA-512 < 2128 1024 64 512
SHA-
< 2128 1024 64 224
512/224
SHA-
< 2128 1024 64 256
512/256

22
Introduction to Blockchain Technology

Applications of Hash Functions

The cryptographic hash functions have many different usages in


different situations. Following are a few examples use cases:

● Hash functions are used in verifying the integrity and


authenticity of information.
● Hash functions can also be used to index data in hash
tables. This can speed up the process of searching. Instead
of the whole data, if we search based on the hashes
(assuming the much shorter hash value compared with the
whole data), then it should obviously be faster.
● They can be used to securely authenticate the users
without storing the passwords locally. Imagine a situation
where you do not want to store passwords on the server,
obviously because if an adversary hacks on to the server,
they cannot get the password from their stored hashes.
Every time a user tries to log in, hash of the password is
calculated and matched against the stored hash. Secured,
isn’t it?
● Since hash functions are one-way functions, they can be
used to implement PRNG.
● Bitcoin uses hash functions as a proof of work (PoW)
algorithm. We will get into the details of it when we hit the
Bitcoin chapter.
● Bitcoin also uses hash functions to generate addresses to
improve security and privacy.
● The two most important applications are digital signatures
and in MACs such as hash-based message authentication
codes (HMACs).

MAC and HMAC HMAC is a type of MAC (message authentication


code). As the name suggests, a MAC’s purpose is to provide
message authentication using Symmetric Key and message
integrity using hash functions. So, the sender sends the MAC
along with the message for the receiver to verify and trust it. The
receiver already has the key K (as symmetric key cryptography is

23
Introduction to Blockchain Technology

being used, so both sender and receiver have agreed on it already);


they just use it to compute the MAC of the message and check it
against the MAC that was sent along with the message.
In its simplest form, MAC = H(key || message). HMAC is actually a
technique to turn the hash functions into MACs. In HMAC, the
hash functions can be applied multiple times along with the key
and its derived keys. HMACs are widely used in RFID-based
systems, TLS, etc. In SSL/TLS (HTTPS is TTP within SSL/TLS),
HMAC is used to allow client and server to verify and ensure that
the exchanged data has not been altered during transmission. Let
us look at a few of the important MAC strategies that are widely
used:

● MAC-then-Encrypt: This technique requires the


computation of MAC on the cleartext, appending it to the
data, and then encrypting all of that together. This scheme
does not provide integrity of the ciphertext. At the
receiving end, the message decryption has to happen first
to be able to check the integrity of the message. It ensures
the integrity of the plaintext, however. TLS uses this
scheme of MAC to ensure that the client-server
communication session is secured.
● Encrypt-and-MAC: This technique requires the
encryption and MAC computation of the message or the
cleartext, and then appending the MAC at the end of the
encrypted message or ciphertext. Notice that MAC is
computed on the cleartext, so integrity of the cleartext can
be assured but not of the ciphertext, which leaves scope for
some attacks. Unlike the previous scheme, integrity of the
cleartext can be verified. SSH (Secure Shell) uses this MAC
scheme.
● Encrypt-then-MAC: This technique requires that the
cleartext needs to be encrypted first, and then compute the
MAC on the ciphertext. This MAC of the ciphertext is then
appended to the ciphertext itself. This scheme ensures
integrity of the ciphertext, so it is possible to first check
the integrity and if valid then decrypt it. It easily filters out
the invalid ciphertexts, which makes it efficient in many

24
Introduction to Blockchain Technology

cases. Also, since MAC is in ciphertext, in no way does it


reveal information about the plaintext. It is usually the
most ideal of all schemes and has wider implementations.
It is used in IPsec.

Merkle Tree

Merkle trees are hash-based data structures used to validate large


amounts of data in an efficient manner. This data structure is used
to solve the previously time-consuming and computationally
expensive problem of keeping data consistent across multiple
computers. Prominent uses of a Merkle tree - and its variations-
are in peer-to-peer networks such as Bitcoin, Ethereum, Git, and
Tor.

Merkle Tree Diagram

This diagram illustrates a fully balanced Merkle tree. As you can


guess from the illustration, the Merkle hash root maintains the
integrity of the data. If any of the nodes are changed, or the order
of the data items is changed, the Merkle hash root will be
completely different.

25
Introduction to Blockchain Technology

Figure 2.11: Example of Merkle Tree

We had to add an empty light-weight node to keep it balanced.


Therefore, when we append a new leaf, we can just replace that
empty node and recalculate the hash root.

Merkle Audit Proof

Audit proof lets you verify that a specific data record is included in
the database. Usually, the server maintaining the database
provides the client with a proof that the record exists in that
database. If a Merkle audit proof fails to produce a root hash that
matches the Merkle root hash (which is obtained from a trusted
authority), it means that the data record is not in the database.

The diagram below illustrates how you should construct an audit


proof:

Figure 2.12: Example of audit proving using Merkle Tree

In this example, we need to provide proof that the record D exists


in the database. Since we already know the hash value of D (we can
easily compute it), we will need H-3 to compute D-2. Now, when
we can compute D-2, we will need to get D-1 in order to obtain the
hash value of T-1, and so on... You've got the gist, right? We only
need to grab the sibling node and climb up the tree until we've
reached the root. This implements everything described above.

26
Introduction to Blockchain Technology

Merkle Consistency Proof

A Merkle consistency proof lets you verify that any two versions of
a database are consistent: that is, the later version includes
everything in the earlier version, in the same order, and all new
entries come after the entries in the older version.

Description of blockchain technology

Many research articles partitioned Blockchain technologies into


different layers. The section describes layers of a Blockchain
network along with the investigation of Blockchain’s core
properties related to immutability, security, and integrity. The
layered structure of the BC depicted in Figure 3 is discussed below.

Figure 2.13: The layers of blockchain

Data Layer

27
Introduction to Blockchain Technology

This layer consists of transactions, Blocks, Hash function, Merkle


tree, and the digital signature. Important components of this layer
are discussed below:

Data Block: Blockchain is fundamentally a chain of Blocks, a


linear structure that starts with a so-called genesis Block and
continues with each new confirmed Block connected to that chain.
Each Block comprises several transactions and has a field
containing the hashtag of its immediately preceding Block, which
creates links between them.

Figure 2.14: The structure of block in blockchain

Consequently, all confirmed Blocks in the chain can be traced back


through cryptographic hash code; any modification or alteration
to the data of any Blocks is not possible. A typical data Block is
divided into two parts: transaction records and a header.
Transaction records are organized in a Merkle tree as depicted in
Figure 4. A Merkle tree refers to a binary tree structure that
summarizes and allows content to be checked efficiently and
securely within a large data set. If the transactions are not packed
into Merkle trees, each of the network nodes would need to keep a

28
Introduction to Blockchain Technology

complete copy of each transaction which has ever taken place on


the Blockchain [9].

Figure 2.15: The uses of Merkle tree in blockchain

A Merkle tree summarizes all transactions within a Block by


generating a digital fingerprint of the entire collection of
transactions, enabling a user to check whether a transaction is
included in a Block or not. If a single transaction is modified or
altered, the Merkle tree root is also modified. One field in the
Block’s header contains the Merkle tree root that is generated
while making the Block. Merkle trees are generated by hashing
node pairs repeatedly until just one hash is left, and this hash is
called the root hash, or the root of the Merkle tree. Each leaf node
holds a hash of transaction data, and each non-leaf node contains
a hash of its previous hashes. A transaction is made when a user
carries out activities on the Blockchain. For instance, a transaction
with associated metadata and signed with a user’s private key to
ensure trust, is created if the user exchanges money or makes a
contract. In general, the Block header includes: 1) a hash of the
previous Block for authentication, 2) a Merkle tree root for packing

29
Introduction to Blockchain Technology

a group of transactions 3) a Nonce that produces a hash value


below the target level by means of a consensus mechanism and 4)
a Timestamp referring to the time when the Block has been
created. In the Proof of Work BC, the nonce field in the Block
header is continuously incremented by Miner nodes until the
target hash code is generated.

Figure 2.17: The chain of blocks in the blockchain

The Block is shared among the participants on the peer-to-peer


network, and each participant links the Block to the existing chain
of Blocks only if the Block is approved by the consensus
mechanism described in the later section. Thus, a decentralized
ledger is formed on the Blockchain and each node stores one copy
of that ledger. This eliminates the need for the central control
point, resulting in a high level of equity among the participants of
the Blockchain. In addition, each Block in the distributed ledger
always has a distinctive cryptographic signature associated with a
timestamp which makes the ledger auditable and unchangeable.

Digital Signature

30
Introduction to Blockchain Technology

A digital signature (DS) refers to a cryptographic approach to


authenticate digital content and guarantees its integrity. DS
utilizes a public key cryptography (PKI) system. Public key
cryptography (PKI) consists of a public and private key that are
paired together but asymmetric (not identical). The public key in
the pair is usually shared with the authorized entities and the
owner of this key pair does not disclose the private key. Either of
the keys can be applied to encrypt a message; the opposite key
that is not employed to encrypt the message from the pairs is
utilized to decrypt the message. Figure 2.18 (a) demonstrates that
a message is encrypted with a public key, a private key is utilized
to decrypt the message. Alternatively, Figure 2.18 (b) shows that
the ciphertext of the message is generated using private key and
plaintext is produced using the public key.

31
Introduction to Blockchain Technology

Figure 2.18: Properties of public/private key

The public key of a user is known as his or her address like a bank
account in BC technologies such as Bitcoin or Ethereum. Anyone
can send digital currencies to a user’s address (Public Key) and
only the user can access the currencies using his private key of the
corresponding PKI. Figure 2.19 explains signing a message using
the private key and verifying the message with the public key in
the Bitcoin BC.

▪ Signing a message with a sender’s private key: To


generate a digital signature of a message, the sender’s
signing algorithm produces a one-way hash of the message.
A cryptographic hash function depicted in Figure 6 is a

32
Introduction to Blockchain Technology

mathematical algorithm that takes an arbitrary amount of


data input to map the content to a bit array of a fixed size
called hash value or just a "hash". The hash algorithm is a
one-way function which is practically infeasible to invert.
The hash also known as digest of the message is encrypted
with the sender’s private key. The digest along with other
information such as the hashing algorithm is appended
with the original message as a DS of the transmitted data.

▪ Verifying the message with the sender’s public key:


The receiver’s signature algorithm verifies the electronic
signature associated with the original content in two steps:
1) generating the hash or digest of the message 2)
decrypting the appended digital signature using the
sender’s public key. If both digests are identical, the data
has not been changed. Otherwise, either the message or
signature has been altered or the digest has not been
decrypted with the private key of the corresponding public
key.

33
Introduction to Blockchain Technology

Figure 2.19: The process of making and verifying digital signature


in blockchain

The consensus layers

When a node exchanges data on the Blockchain network, no


centralized organization is empowered to monitor the transaction
or prevent attackers from modifying or altering it. To eliminate
fraud-related actions such as double-spending acks, the Block's
trustworthiness must be evaluated, and the data flow must be
managed to guarantee that information flows smoothly[63].
Validation procedures known as consensus algorithms are used to
meet these objectives. A consensus algorithm is a means of
obtaining an agreement between several insecure nodes on a
particular data block in the Blockchain setting. Several consensus
mechanisms from the literature are detailed below and shown in
Figure 2.20, which depicts five consensus mechanism

34
Introduction to Blockchain Technology

categorizations.: Proof of Work (PoW), Proof of Stake (PoS),


Byzantine Fault Tolerance(BFT), Proof of Authority (PoA) and
Proof of Elapsed Time (PoET). Here, Proof of Work consensus
mechanism is described below. We will cover other consensus
mechanisms in a later chapter.

Figure 2.20: Common consensus mechanism in blockchain

Proof of Work:

PoW refers to a cryptographic puzzle. Bitcoins uses a


cryptographic hash function called SHA-256. SHA-256 is applied
to a combination of the block's data (bitcoin transactions) and a
number called nonce. By changing the block data or the nonce, we
get completely different hashes. For a block to be considered valid
or "mined", the hash value of the block and the nonce needs to
meet a certain condition. For example, the four leading digits of
the hash needs to be equal to "0000". We can increase the mining
complexity by making the condition more complex, for example
we can increase the number of 0s that the hash value needs to
start with.

The cryptographic puzzle that miners need to solve is to find a


nonce value that makes the hash value satisfy the mining
35
Introduction to Blockchain Technology

condition. You can use the app below to simulate block mining.
When you type in the "Data" text box or change the nonce value,
you can notice the change in the hash value. When you click the
"Mine" button, the app starts with a nonce equal to zero, computes
the hash value and checks if the leading four digits of the hash
value is equal to "0000". If the leading four digits are not equal to
"0000", it increments the nonce by one and repeats the whole
process until it finds a nonce value that satisfies the condition. If
the block is considered mined, the background color turns green.

Figure 2.21: The procedure of Proof of Work in Bitcoin blockchain

36
Introduction to Blockchain Technology

From Blocks to Blockchain

As discussed in the previous section, transactions are grouped in


blocks and blocks are appended to the blockchain. To create a
chain of blocks, each new block uses the previous block’s hash as
part of its data. To create a new block, a miner selects a set of
transactions, adds the previous block’s hash, and mines the block
in a similar fashion described above.

Any changes to the data in any block will affect all the hash values
of the blocks that come after it and they will become invalid. This
gives the blockchain its immutability characteristic.

You can use the app below to simulate a blockchain with 3 blocks.
When you type in the "Data" text box or change the nonce value,
you can notice the change in the hash value and the "Prev" value
(previous hash) of the next block. You can simulate the mining
process by clicking on the “Mine” button of each individual block.
After mining the 3 blocks, try changing the data in block 1 or 2,
and you will notice that all the blocks that come after becoming
invalid. Both mining simulators above were adapted from Anders
Brown Worth's excellent Blockchain Demo.

Adding Blocks to the Blockchain

37
Introduction to Blockchain Technology

All the miners in the Bitcoin network compete to find a valid block
that will be added to the blockchain and get the reward from the
network. Finding a nonce that validates a block is rare, but because
of the number of miners, the probability of a miner in the network
validating a block is extremely high. The first miner to submit a
valid block gets his block added to the blockchain and receives the
reward in bitcoins. But what happens if two miners or more submit
their blocks at the same time?

Resolving Conflicts

If 2 miners solve a block at almost the same time, then we will


have 2 different blockchains in the network, and we need to wait
for the next block to resolve the conflict. Some miners will decide
to mine on top of blockchain 1 and others on top of blockchain 2.
The first miner to find a new block resolves the conflict. If the new
block was mined on top of blockchain 1, then blockchain 2
becomes invalid, the reward of the previous block goes to the
miner from blockchain 1 and the transactions that were part of
blockchain 2 and weren’t added to the blockchain go back to the
transactions pool and get added to the next blocks. In short, if
there is a conflict on the blockchain, then the longest chain wins.

The network layers

The network layer, also known as the P2P network, establishes


communication between nodes. The P2P network ensures that all

38
Introduction to Blockchain Technology

nodes can discover and connect each other to propagate Blocks


throughout the network and synchronize the valid, current state of
the Blockchain. A P2P network is a network of computers where
computers (nodes) are distributed, and the workload of the
network is shared across multiple nodes to achieve the end target
nodes on the Blockchain for processing transactions and Blocks.
Two kinds of nodes are maintained in the BC peer to peer network:
the full node and the light node. Full nodes ensure that
transactions and Blocks are checked and validated using rules
prescribed in the consensus mechanism, which is also called
mining. Full nodes are accountable for holding trust in the
network, whereas light nodes can make transactions and send
those to the full node. Light nodes can only store the header of the
Blockchain (keys) while the full nodes store the complete
distributed ledger.

Sharding: Sharding that partitions a peer-to-peer network is


introduced to improve Blockchain’s performance. Sharding is a
splitting strategy that distributes computing and storage
workloads across a P2P network such that unlike conventional BC,
each node is not responsible for managing the entire network’s
transactions load, but instead handles information related to its
partition or shard. Figure 9 presents an example of BC sharding. In
this technique, several Blockchains called a chain of a shard are
managed by network nodes instead of maintaining a single
Blockchain for all transactions. Each shard consists of its own
nodes or validators that apply a PoW or staking or voting
consensus mechanism. Readers are suggested to go through to
have comprehensive knowledge on BC sharding.

39
Introduction to Blockchain Technology

Figure 2.22: An example of a sharding network

The infrastructure layers

We describe the infrastructure layer of Blockchain technology for


two enterprise BCs: Ethereum and Hyper- ledger Fabric (HF). A
user’s computer can participate in Ethereum Blockchain by
running a client software such as Geth, Parity. Ethereum
maintains two kinds of nodes: light node, and full node. The light
node runs the client software stores the cache, and the state of the
Ethereum. Further, the light node engages in verifying the
execution of transactions while the full nodes download the entire
ledger in their local storage, participate in full consensus
enforcement, verify signature, transactions, and Block formats,
and check double spending. The Ethereum nodes execute the
Ethereum Virtual Machine (EVM) which is like Java Virtual
Machines (JVMs) running byte code. EVM acting as sandboxes
offers an execution environment for a smart contract. EVM is a

40
Introduction to Blockchain Technology

Turing complete software; a stack-based virtual machine that


handles the internal state and computation for smart contract.

Figure 2.23: The Ethereum blockchain

The Hyperledger Fabric BC is comprised of three types of nodes: 1)


endorsers, 2) orderers, and 3) peer nodes. The peer nodes host
ledgers and chain code that is also known as smart contracts. The
uses’ applications and administrators using Fabric Software
Development Kit (SDK) APIs can always communicate with peer
nodes to access the chain code or distributed ledger. The
Hyperledger Fabric manages multiple channels that refer to
different private sub- networks consisting of several
peers(member). Each channel maintains its separate ledger which
is stored in each peer on the channel. A specific set of applications
and peers can communicate to HF via channels. The transactions
flow in the Hyperledger Fabric in the following three phases.

▪ Endorsing phase: First, the endorsing peers receive update


transactions from an application. These nodes endorse a

41
Introduction to Blockchain Technology

transaction without committing it in the ledger. They send


the endorsement of the transaction to the orderer nodes.
▪ Ordering phase: The orderer nodes collect endorsed
transactions for various applications from the endorsing
nodes. These nodes order the transactions into Block.
▪ Distribution phase: Finally, the Block is distributed to all
the peer nodes on the BC business network. These peers
will validate the transaction and will commit the
transaction to their local copy of the ledger upon successful
validation.

Figure 2.24: The Hyperledger blockchain

The application layers

The BC application layer includes smart contracts, chaincode, and


dApps. This layer comprises two sub-layers: 1) presentation layer
and 2) execution layer. The presentation layer includes scripts,
APIs, and user interface. These tools are used to connect the
application layer with the Blockchain network. The execution layer

42
Introduction to Blockchain Technology

includes smart contracts, chaincode and underlying rules. The


presentation layer sends instructions to the execution layer, which
runs transac- tions. For example, instructions are sent to
chaincode in Hyperledger Fabric and smart contract in Ethereum
Virtual Machine. The components of the application layer are
listed below.

▪ Smart Contract: Smart contract written in Solidity


language runs on the Ethereum runtime engine. The
compiler produces bytecode of a smart contract that runs
faster on the EVM. Code executed on an EVM is isolated
from the network or file system. A smart contract refers to
a set of business logic presented in various functions that
are executed when a transaction against those functions is
issued. The bytecode of a smart contract is assigned a
unique address after deploying it on the EVM. A
transaction associated with a smart contract can result in a
state change in the decentralized ledger.
▪ Chaincode: In Hyperledger Fabric, several related smart
contracts are packaged together into chaincode that is
deployed in the BC business network. For example, an
insurance application needs to implement their business
l.ogic in the form of multiple smart contracts named as
claims, liability, processing, and so on, which together
constitute a chaincode. The chaincode governs packaging
and deployment of smart contracts in the Hyperledger
Fabric. Further, chaincode defines the schema of ledger’s
data, initiates it, performs updates to ledgers based on
consensus, and responds to queries for ledger data.
Unlike EVM, in Hyperledger Fabric, chaincode written in
standard languages such as Java, Node.js and Go is
deployed on peer nodes owned by different organizations.
The chaincode runs on a secure Docker container. The
client applications can access to the chaincode via REST
43
Introduction to Blockchain Technology

APIs or SDK. Chaincodes are initiated for a particular


channel where an administrator determines the
endorsement policy for a chaincode running on the
channel.
▪ dApps: dApp refers to a distributed web application that
runs on top of a distributed Blockchain technologies such
as Ethereum, Bitcoin, and Hyperledger Fabric. dApp can
interact with Blockchain using smart contract or
chaincode. Unlike a conventional app, dApp is no longer
controlled by a single entity or an organization once it is
deployed on the BC network.

Exercise:

1. What is a double spending attack? How does blockchain


solve the double spending problem?
2. How does asymmetric key ensure confidentiality and
authentication in blockchain technology? Explain with
necessary figures.
3. What are the different layers of blockchain technology?
Briefly describe all of them.
4. What is a Merkle Tree? Why is the Merkle tree needed in
blockchain technology?
5. What is sharding? Why is sharding used in blockchain?
6. Explain Proof of Work with proper flow diagram.
7. If two miners mine a block at the same time, how does
blockchain resolve this conflict?
8. Define the following terms: a) smart contract b) chaincode
c) dApp
9. Explain the transaction flow of Hyperledger Fabric.
10. Describe the role of digital signature in blockchain and
explain the mechanism to generate and verify digital
signature.

44
Introduction to Blockchain Technology

11. Write the importance of cryptographic Hash in blockchain


technology with its application.

45
Introduction to Blockchain Technology

CHAPTER 3
BLOCKCHAIN IMPLEMENTATION

Installing Flask

For our conceptual blockchain, we will run it as a REST API, so


that we can interact with it through REST calls. For this, we will
use the Flask microframework. To install Flask, type the following
commands in Terminal:

$ pip install flask

$ pip install requests

The preceding command installs the Flask microframework.

Flask is a web framework, it’s a Python module that lets you


develop web applications easily. A Web Application Framework or
simply a Web Framework represents a collection of libraries and
modules that enable web application developers to write
applications without worrying about low-level details such as
protocol, thread management, and so on.

A minimal Flask application looks something like this:

from flask import Flask


app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>
So, what did that code do?

46
Introduction to Blockchain Technology

1. First we imported the Flask class. An instance of this class


will be our WSGI application.
2. Next we create an instance of this class. The first argument
is the name of the application’s module or package.
__name__ is a convenient shortcut for this that is
appropriate for most cases. This is needed so that Flask
knows where to look for resources such as templates and
static files.
3. We then use the route() decorator to tell Flask what URL
should trigger our function.In the above example, ‘/’ URL is
bound with the hello_world() function. Hence, when the
home page of a web server is opened in the browser, the
output of this function will be rendered.

app.route(rule, options)

a. The rule parameter represents URL binding with the


function.
b. The options is a list of parameters to be forwarded
to the underlying Rule object.
4. Finally the run() method of Flask class runs the application
on the local development server.
5. The function returns the message we want to display in the
user’s browser. The default content type is HTML, so HTML
in the string will be rendered by the browser.

Save it as hello.py or something similar. Make sure to not call


your application flask.py because this would conflict with Flask
itself.

To run the application, use the flask command or python -m flask.


Before you can do that, you need to tell your terminal the
application to work with by exporting the FLASK_APP
environment variable:

47
Introduction to Blockchain Technology

For CMD, to run hello.py

set FLASK_APP=hello
flask run
* Running on http://127.0.0.1:5000/
To run on python shell

app.run(host, port, debug, options)

All parameters are optional

Sr.No. Parameters & Description

Host- Hostname to listen on. Defaults to 127.0.0.1 (localhost).


1
Set to ‘0.0.0.0’ to have server available externally
2 Port-Defaults to 5000

Debug-Defaults to false. If set to true, provides a debug


3
information

4 Options -To be forwarded to underlying Werkzeug server.

The above given Python script is executed from Python


shell.

Python Hello.py

A message in Python shell informs you that

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Open the above URL (localhost:5000) in the browser. ‘Hello


World’ message will be displayed on it.

Complete Blockchain Code

48
Introduction to Blockchain Technology

[The complete code can be retrieved from Lee WM.


(2019), Implementing Your Own Blockchain Using
Python. In: Beginning Ethereum Smart Contracts
Programming.]

Importing the Various Modules and Libraries

To get started, let’s create a text file named blockchain.py. At the


top of this file, let’s import all the necessary libraries and modules:

import sys
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
import requests
from urllib.parse import urlparse

Declaring the Class in Python

To represent the blockchain, let’s declare a class named


blockchain, with the following

two initial methods:

class Blockchain(object):

difficulty_target = "0000"

def hash_block(self, block):

block_encoded = json.dumps(block,
sort_keys=True).encode()

49
Introduction to Blockchain Technology

return
hashlib.sha256(block_encoded).hexdigest()

def __init__(self):

# stores all the blocks in the entire blockchain

self.chain = []

# temporarily stores the transactions for the current


block

self.current_transactions = []

# create the genesis block with a specific fixed hash of previous


block genesis block

#starts with index 0

genesis_hash = self.hash_block("genesis_block")

self.append_block( hash_of_previous_block =
genesis_hash, nonce = self.proof_of_work(0,
genesis_hash, []) )

The preceding creates a class named blockchain with two


methods:

● The hash_block() method encodes a block into array of


bytes and then hashes it; you need to ensure that the
dictionary is sorted, or you’ll have inconsistent hashes later
on
● The __init__() function is the constructor for the class. Here,
you store the entire blockchain as a list. Because every
blockchain has a genesis block, you need to initialize the
genesis block with the hash of the previous block, and in

50
Introduction to Blockchain Technology

this example, we simply used a fixed string called


“genesis_block” to obtain its hash. Once the hash of the
previous block is found, we need to find the nonce for the
block using the method named proof_of_work() (which we
will define in the next section).

The proof_of_work() method (detailed next) will return a nonce


that will result in a hash that matches the difficulty target when
the content of the current block is hashed. For simplicity, we are
fixing the difficulty_target to a hash result that starts with four
zeros (“0000”).

Finding the Nonce

We now define the proof_of_work() method to find the nonce for


the block:

# use PoW to find the nonce for the current block

Def proof_of_work(self, index,


hash_of_previous_block, transactions):

# try with nonce = 0

nonce = 0

# try hashing the nonce together with the hash of


the previous block until it is valid

while self.valid_proof(index,
hash_of_previous_block, transactions, nonce) is
False:

nonce += 1

51
Introduction to Blockchain Technology

return nonce

The proof_of_work() function first starts with zero for the nonce
and check if the nonce together with the content of the block
produces a hash that matches the difficulty target. If not, it
increments the nonce by one and then try again until it finds the
correct nonce.

The next method, valid_proof(), hashes the content of a block and


check to see if the block’s hash meets the difficulty target:

def valid_proof(self, index, hash_of_previous_block, transactions,


nonce):

# create a string containing the hash of the previous

# block and the block content, including the nonce

content =
f'{index}{hash_of_previous_block}{transactions}{nonce}'.encode()

# hash using sha256

content_hash = hashlib.sha256(content).hexdigest()

# check if the hash meets the difficulty target

return content_hash[:len(self.difficulty_target)] ==

self.difficulty_target

Appending the Block to the Blockchain

Once the nonce for a block has been found, you can now write the
method to append the block to the existing blockchain. This is the
function of the append_block() method :

# creates a new block and adds it to the blockchain

52
Introduction to Blockchain Technology

def append_block(self, nonce, hash_of_previous_block):

block = {

'index': len(self.chain),

'timestamp': time(),

'transactions': self.current_transactions,

‘nonce': nonce,

'hash_of_previous_block': hash_of_previous_block

# reset the current list of transactions

self.current_transactions = []

# add the new block to the blockchain

self.chain.append(block)

return block

When the block is added to the blockchain, the current timestamp


is also added to the block.

Adding Transactions

The next method we will add to the Blockchain class is


the add_transaction() method :

def add_transaction(self, sender, recipient, amount):

self.current_transactions.append({

'amount': amount,

53
Introduction to Blockchain Technology

'recipient': recipient,

'sender': sender,

})

return self.last_block['index'] + 1

This method adds a new transaction to the current list of


transactions. It then gets the index of the last block in the
blockchain and adds one to it. This new index will be the block
that the current transaction will be added to.

To obtain the last block in the blockchain, define a property


called last_block in the Blockchain class:

@property

def last_block(self):

# returns the last block in the blockchain

return self.chain[-1]

Exposing the Blockchain Class as a REST API

Our Blockchain class is now complete, and so let’s now expose it as


a REST API using Flask. Append the following statements to the
end of the blockchain.py file:

app = Flask(__name__)

54
Introduction to Blockchain Technology

# generate a globally unique address for this node

node_identifier = str(uuid4()).replace('-', ")

# instantiate the Blockchain

blockchain = Blockchain()

Obtaining the Full Blockchain

For the REST API, we want to create a route for users to obtain the
current blockchain, so append the following statements to the end
of blockchain.py :

# return the entire blockchain

@app.route('/blockchain', methods=['GET'])

def full_chain():

response = {

'chain': blockchain.chain,

'length': len(blockchain.chain),

return jsonify(response), 200

Performing Mining

We also need to create a route to allow miners to mine a block so


that it can be added to the blockchain:

@app.route('/mine', methods=['GET'])

def mine_block():
55
Introduction to Blockchain Technology

blockchain.add_transaction(

sender="0",

recipient=node_identifier,

amount=1,

# obtain the hash of last block in the blockchain

last_block_hash =
blockchain.hash_block(blockchain.last_block)

# using PoW, get the nonce for the new block to be added
to the blockchain

index = len(blockchain.chain)

nonce = blockchain.proof_of_work(index,
last_block_hash, blockchain.current_transactions)

# add the new block to the blockchain using the last block

# hash and the current nonce

block = blockchain.append_block(nonce, last_block_hash)

response = {

'message': "New Block Mined",

'index': block['index'],

'hash_of_previous_block':

block['hash_of_previous_block'],

56
Introduction to Blockchain Technology

'nonce': block['nonce'],

'transactions': block['transactions'],

return jsonify(response), 200

When a miner manages to mine a block, he must receive a reward


for finding the proof. Here, we added a transaction to send one
unit of rewards to the miner to signify the rewards for successfully
mining the block.

When mining a block, you need to find the hash of the previous
block and then use it together with the content of the current
block to find the nonce for the block. Once the nonce is found, you
will append it to the blockchain.

Adding Transactions

Another route that you want to add to the API is the ability to add
transactions to the current block:

@app.route('/transactions/new', methods=['POST'])

def new_transaction():

# get the value passed in from the client

values = request.get_json()

# check that the required fields are in the POST'ed data

required_fields = ['sender', 'recipient', 'amount']

if not all(k in values for k in required_fields):

57
Introduction to Blockchain Technology

return ('Missing fields', 400)

# create a new transaction

index = blockchain.add_transaction(

values['sender'],

values['recipient'],

values['amount']

response = {'message':

f'Transaction will be added to Block {index}'}

return (jsonify(response), 201)

Examples of transactions are users sending cryptocurrencies from


one account to another.

Testing Our Blockchain

We are now ready to test the blockchain. In this final step, add the
following statements to the end of blockchain.py:

if __name__ == '__main__':

app.run(host='0.0.0.0', port=int(sys.argv[1]))

In this implementation, we allow the user to run the API based on


the specified port number.

To start the first node, type the following command in Terminal:

$ python blockchain.py 5000

58
Introduction to Blockchain Technology

Synchronizing Blockchains

In real life, a blockchain network consists of multiple nodes


maintaining copies of the same blockchain. So, there must be a
way for the nodes to synchronize so that every single node is
referring to the same identical blockchain.

When you use Python to run the blockchain.py application, only


one node is running. The whole idea of blockchain is
decentralization – there should be multiple nodes maintaining the
blockchain, not just one.

For our example, we shall modify it so that each node can be made
aware of neighboring nodes on the network (see Figure 3.1).

Figure 3.1: A blockchain network should consist of multiple nodes

To do that in our example, let’s add several methods to


the Blockchain class. First, add a nodes member to the constructor
of the Blockchain class and initialize it to an empty set:

def __init__(self):

59
Introduction to Blockchain Technology

self.nodes = set()

# stores all the blocks in the entire blockchain

self.chain = []

...

This nodes member will store the address of other nodes. Next,
add a method called add_node() to the Blockchain class:

def add_node(self, address):

parsed_url = urlparse(address)

self.nodes.add(parsed_url.netloc)

print(parsed_url.netloc)

This method allows a new node to be added to the nodes member,


for example, if “http://192.168.0.5:5000” is passed to the method,
the IP address and port number “192.168.0.5:5000” will be added
to the nodes member.

The next method to add to the Blockchain class is valid_chain() :

# determine if a given blockchain is valid

def valid_chain(self, chain):

last_block = chain[0] # the genesis block

current_index = 1 # starts with the second block

while current_index < len(chain):

block = chain[current_index]

60
Introduction to Blockchain Technology

if block['hash_of_previous_block'] !=

self.hash_block(last_block):

return False

# check for valid nonce

if not self.valid_proof(

current_index,

block['hash_of_previous_block'],

block['transactions'],

block['nonce']):

return False

# move on to the next block on the chain

last_block = block

current_index += 1

# the chain is valid

return True

The valid_chain() method validates that a given blockchain is valid


by performing the following checks:

● It goes through each block in the blockchain and hashes


each block and verifies that the hash of each block is
correctly recorded in the next block.

● It verifies that the nonce in each block is valid.

61
Introduction to Blockchain Technology

Finally, add the update_blockchain() method to


the Blockchain class:

def update_blockchain(self):

# get the nodes around us that has been registered

neighbours = self.nodes

new_chain = None

# for simplicity, look for chains longer than ours

max_length = len(self.chain)

# grab and verify the chains from all the nodes in our

# network

for node in neighbours:

# get the blockchain from the other nodes

response = requests.get(f'http://{node}/blockchain')

if response.status_code == 200:

length = response.json()['length']

chain = response.json()['chain']

# check if the length is longer and the chain

# is valid

if length > max_length and

self.valid_chain(chain):

max_length = length
62
Introduction to Blockchain Technology

new_chain = chain

# replace our chain if we discovered a new, valid

# chain longer than ours

if new_chain:

self.chain = new_chain

return True

return False

The update_blockchain() method works by

● Checking that the blockchain from neighboring nodes is


valid and that the node with the longest valid chain is the
authoritative one; if another node with a valid blockchain
is longer than the current one, it will replace the current
blockchain.

With the methods in the Blockchain class defined, you can now
define the routes for the REST API:

@app.route('/nodes/add_nodes', methods=['POST'])

def add_nodes():

# get the nodes passed in from the client

values = request.get_json()

nodes = values.get('nodes')

if nodes is None:

return "Error: Missing node(s) info", 400

for node in nodes:

63
Introduction to Blockchain Technology

blockchain.add_node(node)

response = {

'message': 'New nodes added',

'nodes': list(blockchain.nodes),

return jsonify(response), 201

The /nodes/add_nodes route allows a node to register one or more


neighboring nodes. The /nodes/sync route allows a node to
synchronize its blockchain with its neighboring nodes:

@app.route('/nodes/sync, methods=['GET'])

def sync():

updated = blockchain.update_blockchain()

if updated:

response = {

'message':

'The blockchain has been updated to the latest',

'blockchain': blockchain.chain

else:

response = {

'message': 'Our blockchain is the latest',

64
Introduction to Blockchain Technology

'blockchain': blockchain.chain

return jsonify(response), 200

Testing the Blockchain with Multiple Nodes

In the Terminal that is running the blockchain.py application,


press Ctrl+C to stop the server. Type the following command to
restart it:

$ python blockchain.py 5000

Open another Terminal window. Type the following command:

$ python blockchain.py 5001

Tip

The preceding command registers a new node with the node at


port 5000 that there is a neighboring node listening at port 5001.

Figure 3.2 shows the two nodes aware of each other’s existence.

65
Introduction to Blockchain Technology

Figure 3.2: A blockchain network should consist of multiple nodes

Figure 2-5 The current states of the two nodes in our blockchain
network

Install Postman

To interact with the blockchain, use the following API call

Install postman on the chrome web browser

GET method

To display the ledger of the blockchain

http://localhost:5000/blockchain

To mine a block

http://localhost:5000/mine

To synchronize the blockchain ledger

http://localhost:5000/nodes/sync

POST method

To add a new transaction

Header: http://localhost:5000/transactions/new

Body:

"sender": "04d0988bfa799f7d7ef9ab3de97ef482",
"recipient":

66
Introduction to Blockchain Technology

"cd0f75d2367ad456607647edde665d8f",
"amount": 111

To add a new node

Header: http://localhost:5001/nodes/add_nodes

Body: {"nodes" : ["http://127.0.0.1:5000"]}

Exercise

1. What is flask? write a minimal application of flask and


describe the statements of the application.
2. Write a flask application to add transactions in a blockchain
class.
3. Write a flask application to mine blocks in a blockchain
class.
4. Write a flask application to synchronize chain of blocks
among multiple nodes in a blockchain
5. Write a flask application to update blocks in a blockchain.

67
Introduction to Blockchain Technology

CHAPTER 4
CONSENSUS PROTOCOL IN
BLOCKCHAIN

A consensus mechanism is a fault-tolerant mechanism used in a


blockchain to reach an agreement on a single state of the network
among distributed nodes. These are protocols that make sure all
nodes are synchronized with each other and agree on transactions,
which are legitimate and are added to the blockchain.

Proof of Work:

Proof of Work (PoW) is the original consensus algorithm in a


blockchain network. The algorithm is used to confirm the
transaction and creates a new block to the chain. In this algorithm,
minors (a group of people) compete against each other to
complete the transaction on the network. The process of
competing against each other is called mining. As soon as miners
successfully created a valid block, he gets rewarded. The most
famous application of Proof of Work (PoW) is Bitcoin.

● Anybody who wants to obtain services from the third party


who has advertised on the network first creates a
transaction (message to the desired recipient).

● Over a given period, there could be many senders (buyers)


and receivers (sellers) creating such transactions.

68
Introduction to Blockchain Technology

● All transactions are broadcast on the network to all nodes.


Note that it is not necessary that a given transaction must
reach each other node in the network.

● Each node assembles the new transactions into a block.


Note that the set of transactions in each block is
independent of the set-in blocks created by others and will
naturally be different from others. This does not matter;
the system ensures that every transaction broadcast on the
network gets included in some block over a reasonable
amount of time. Generally, the sender will incentivize the
node by offering a certain number of bitcoins to the miner
for its efforts. The miner may opt for giving priority for
inclusion in the block to those with higher incentives.

● The node now works on finding the proof-of-work for its


assembled block.

● When the node finds a proof-of-work, it broadcasts the


assembled block on the network.

● The nodes that receive the new block will accept it only
after verifying that all transactions in the block are valid
and not already spent.

● If the block is accepted as valid, the node which is working


on its own new block will have to re-assemble the
transactions in its block ensuring that the transactions are
not duplicated. The node now works on finding the proof-
of-work on its newly created block; while doing so it will
take the hash of the accepted block as the previous hash.

● Likewise, the blockchain continues growing forever.

69
Introduction to Blockchain Technology

Nonce is a number such that the block’s hash meets a certain


criterion. This criterion could be that the generated hash must
have its leading four digits to be zero.

Thus, the generated hash would look like 000010101010xxx.


Generally, the miner starts with a Nonce value of 0 and keeps on
incrementing it until the generated hash meets the specified
criterion.

Note that the hash generation works at random and is beyond your
control - that is you cannot force the hash function to generate a
certain hash. Thus, it may take several iterations until the desired
hash with four leading zeros is generated. The expected time for
generating a block in the bitcoin system is 10 minutes. Once the
miner successfully mines the block, he releases that in the system
making it now the last block in the chain.

70
Introduction to Blockchain Technology

Note that there are multiple miners competing to generate the


legitimate block. The Bitcoin system awards the first successful
miner by giving him certain bitcoins. In general, the miner with
more computing power may be an early winner. This can cause
attacks on the entire system by those who possess a huge
processing power.

Pros Cons
Proof-of-work is neutral. You don't
need ETH to get started and block Proof-of-work uses up so much
rewards allow you to go from 0ETH to energy that it's bad for the
a positive balance. With proof-of- environment.
stake you need ETH to start with.
Proof-of-work is a tried and tested
If you want to mine, you need
consensus mechanism that has kept
such specialized equipment that
Bitcoin and Ethereum secure and
it's a big investment to start.
decentralized for many years.
Due to increasing computation
needed, mining pools could
potentially dominate the
Compared to proof-of-stake it's
mining game, leading to
relatively easy to implement.
centralization and security
risks.

Main issues with the Proof-of-Work consensus:


The Proof-of-Work consensus mechanism has some issues which
are as follows:

● The 51% risk: If a controlling entity owns 51% or more than


51% of nodes in the network, the entity can corrupt the
blockchain by gaining most of the network.

71
Introduction to Blockchain Technology

● Time consuming: Miners must check over many nonce


values to find the right solution to the puzzle that must be
solved to mine the block, which is a time-consuming
process.

● Resource consumption: Miners consume high amounts of


computing power to find the solution to the hard
mathematical puzzle. It leads to a waste of precious
resources (money, energy, space, hardware). It is expected
that 0.3% of the world’s electricity will be spent to verify
transactions by the end of 2018.

● Transaction confirmation takes about 10–60 minutes. So, it


is not an instantaneous transaction; because it takes some
time to mine the transaction and add it to the blockchain
thus committing the transaction.

What is Proof-of-Stake?

As understandable from the name, nodes on a network stake an


amount of cryptocurrency to become candidates to validate the
new block and earn the fee from it. Then, an algorithm chooses
from the pool of candidates the node which will validate the new
block. This selection algorithm combines the quantity of stake
(amount of cryptocurrency) with other factors (like coinage-based
selection, randomization process) to make the selection fair to
everyone on the network.

● Coinage based selection: The algorithm tracks the time


every validator candidate node stays a validator. The older
the node becomes, the higher the chances of it becoming
the new validator.

72
Introduction to Blockchain Technology

● Random Block selection: The validator is chosen with a


combination of ‘lowest hash value’ and ‘highest stake’. The
node having the best weighted combination of these
becomes the new validator.

A typical PoS based mechanism workflow

● Nodes make transactions. The PoS algorithm puts all these


transactions in a pool.

● All the nodes contending to become validators for the next


block raise a stake. This stake is combined with other
factors like ‘coin-age’ or ‘randomized block selection’ to
select the validator.

● The validator verifies all the transactions and publishes the


block. His stake still remains locked and the forging reward
is also not granted yet. This is so that the nodes on the
network can ‘OK’ the new block.

● If the block is ‘OK’-ed, the validator gets the stake back and
the reward too. If the algorithm is using a coin-age based
mechanism to select validators, the validator for the
current block has its coin-age reset to 0. This puts him in a
low priority for the next validator election.

● If the block is not verified by other nodes on the network,


the validator loses its stake and is marked as ‘bad’ by the
algorithm. The process again starts from step 1 to forge the
new block.

Advantages of PoS

● Energy-efficient:
As all the nodes are not competing against each other to

73
Introduction to Blockchain Technology

attach a new block to the blockchain, energy is saved. Also,


no problem has to be solved (as in case of Proof-of-Work
system) thus saving energy.

● Decentralization:
In blockchains like Bitcoin (Proof of Work system to
achieve distributed consensus), an extra incentive of
exponential rewards are in place to join a mining pool
leading to a more centralized nature of blockchain. In the
case of a Proof-of-Stake based system (like Peercoin),
rewards are proportional(linear) to the amount of stake. So,
it provides absolutely no extra edge to join a mining pool;
thus, promoting decentralization.

● Security:
A person attempting to attack a network will have to own
51% of the stakes (pretty expensive). This leads to a secure
network.

Weakness of a PoS mechanism

● Large stake validators: If a group of validator candidates


combine and own a significant share of total
cryptocurrency, they will have more chances of becoming
validators. Increased chances lead to increased selections,
which lead to more and more forging reward earning,
which lead to owning a huge currency share. This can cause
the network to become centralized over time.

● New technology: PoS is still relatively new. Research is


ongoing to find flaws, fix them and make it viable for a live
network with actual currency transactions.

● The ‘Nothing at Stake’ problem: This problem describes


the little to no disadvantage to the nodes in case they
74
Introduction to Blockchain Technology

support multiple blockchains in the event of a blockchain


split (blockchain forking). In the worst-case scenario, every
fork will lead to multiple blockchains, and validators will
work and the nodes in the network will never achieve
consensus.

Delegated Proof of Stake

Delegated Proof of Stake (DPoS) is a consensus algorithm which is


an advancement of the fundamental concepts of Proof Of Stake.
Here is how DPoS consensus works.

Voting: In DPoS consensus users can either directly vote or give


their voting power to another entity to vote on their behalf.
Selected witnesses are responsible for creating blocks by verifying
transactions. If they verify and sign all transactions in a block,
they receive a reward, which is usually shared with those who have
voted for a witness. If a witness fails to verify all transactions in
the given time, a block is missed, all transactions are left
unverified, and no reward is distributed to that witness. The
reward is added up to the reward of the next witness which verifies
that block. Such transactions are collected by the next witness,
and such a block is called stolen.

Votes are proportional to the size of each voter’s stake. A user


need not have a large stake to enter the top tier of witnesses.
Rather, votes from users with large stakes can result in users with
relatively small stakes being elevated to the top tier of witnesses.

Witnesses: Number of witnesses in the top tier is capped at a


certain number which is usually in the range of 21-101. These
witnesses are responsible for validating transactions and creating
blocks and are in return awarded associated fees. Witnesses can

75
Introduction to Blockchain Technology

prevent specific transactions from being included in blocks, but


they cannot change information of any transaction which makes
them similar to miners in Proof Of Work blockchains. Voting is a
continuous process and each witness in the top tier is always at
risk of being replaced by a user who gets more votes and is
therefore considered more trusted. As the number of applicants for
witnesses grows, competition grows, and reputation becomes
critical for each witness to remain competitive.

A witness is kept in check by threat to its loss of income, locking of


stake and reputation score. Witnesses must lock a certain part of
their stake which is seized if they act maliciously or try to attack
blockchain.

A round in a DPoS blockchain with N block producers/witnesses


follows a round robin order as follows:

● N block producers get elected from the pool of witness’s


candidates.

● The kth block producer signs the kth block, until k=N.

● A block is finalized when it is voted on by (2/3+1) of block


producers. In the case of two chains, the longest chain rule
is followed. Block added cannot be reversed.

Delegates: Users in DPoS systems also vote for a group of


delegates who oversee blockchain governance. They do not play a
part in transaction control. Delegates can propose changing the
size of a block, or the amount a witness should be paid in return
for validating a block. Once delegates propose such changes,
blockchain’s users vote on whether to adopt them.

Block validators: Block validators in DPoS refer to full nodes who


verify that blocks created by witnesses follow the consensus rules.
76
Introduction to Blockchain Technology

Any user is able to run a block validator and verify the network.
There is no incentive to be a block validator.

Advantages:

1. DPoS blockchains have good protection from double


spending.

2. DPoS is more democratic and financially inclusive due to


the lesser staking amount required by a user/node.

3. DPoS provides more decentralization as more people take


part in the consensus due to the low entry threshold.

4. DPoS doesn’t require lots of power to run a network, which


makes it more sustainable.

5. Transactions in DPoS are not dependent on computing


power required to run a network, hence it is more scalable.

77
Introduction to Blockchain Technology

6. DPoS separates election of block producers from block


production itself which opens the door for more creative
models to solve both problems in isolation.

7. DPoS method provides the foundation for implementing


interesting governance models in blockchain applications.
In a sense, it forms a kind of democracy.

Disadvantages:

1. Effective operation and decision making of a network


requires delegators to be well informed and appoint honest
witnesses.

2. Limited number of witnesses can lead to centralization of


the network.

3. DPoS blockchain is susceptible to problems of weighted


voting. Users with a smaller stake can refuse from taking
part in voting after considering that their vote is
insignificant.

What is Byzantine Fault Tolerance?

Byzantine Fault Tolerance (BFT) is the feature of a distributed


network to reach consensus (agreement on the same value) even
when some of the nodes in the network fail to respond or respond
with incorrect information. The objective of a BFT mechanism is to
safeguard against the system failures by employing collective
decision making (both – correct and faulty nodes) which aims to
reduce the influence of the faulty nodes. BFT is derived from
Byzantine Generals’ Problem.

How pBFT work?

78
Introduction to Blockchain Technology

pBFT tries to provide a practical Byzantine state machine


replication that can work even when malicious nodes are operating
in the system.

Nodes in a pBFT enabled distributed system are sequentially


ordered with one node being the primary (or the leader node) and
others referred to as secondary (or the backup nodes). Note here
that any eligible node in the system can become the primary by
transitioning from secondary to primary (typically, in the case of a
primary node failure). The goal is that all honest nodes help in
reaching a consensus regarding the state of the system using the
majority rule.

A practical Byzantine Fault Tolerant system can function on the


condition that the maximum number of malicious nodes must not
be greater than or equal to one-third of all the nodes in the
system. As the number of nodes increases, the system becomes
more secure.

pBFT consensus rounds are broken into 4 phases (refer with the
image below):

1. The client sends a request to the primary(leader) node.


2. The primary(leader) node broadcasts the request to all the
secondary(backup) nodes.
3. The nodes (primary and secondaries) perform the service
requested and then send back a reply to the client.
4. The request is served successfully when the client receives
‘m+1’ replies from different nodes in the network with the
same result, where m is the maximum number of faulty
nodes allowed.

79
Introduction to Blockchain Technology

The primary(leader) node is switched during each view (pBFT


consensus rounds) and may be replaced by a view change protocol
if a preset amount of time passes without the leading node
broadcasting a request to the backups (secondary). If necessary, a
majority of honest nodes can vote on the current leading node's
legitimacy and elect the next leading node in line.

Limitations of pBFT

The pBFT consensus model works efficiently only when the


number of nodes in the distributed network is small due to the
high communication overhead that increases exponentially with
every extra node in the network.

80
Introduction to Blockchain Technology

1. Sybil attacks: The pBFT mechanisms are susceptible to


Sybil attacks, where one entity(party) controls many
identities. As the number of nodes in the network increase,
sybil attacks become increasingly difficult to carry out. But
as pBFT mechanisms have scalability issues too, the pBFT
mechanism is used in combination with other
mechanism(s).
2. Scaling: pBFT does not scale well because of its
communication (with all the other nodes at every step)
overhead. As the number of nodes in the network increase
(increases as O(n^k), where n is the messages and k are the
number of nodes), so does the time taken to respond to the
request.

81
Introduction to Blockchain Technology

CHAPTER 5
ETHEREUM BLOCKCHAIN
Ethereum is a decentralized, open source blockchain with smart
contract functionality. Ether is the native cryptocurrency of the
platform. After Bitcoin, it is the largest cryptocurrency by market
capitalization. Ethereum is the most actively used blockchain.

let’s dive deeper into the main components that the Ethereum
system is comprised of:

• accounts
• state
• gas and fees
• transactions
• blocks
• transaction execution
• mining
• proof of work

Accounts

Ethereum's global "shared-state" is made up of many smaller


objects (accounts) that can communicate with one another using a
message-passing architecture. Each account has a 20-byte address
and a state associated with it. In Ethereum, an address is a 160-bit
number that may be used to identify any account. There are two
types of accounts: personal and business.

• Accounts that are controlled by private keys and do not


have a code associated with them.

82
Introduction to Blockchain Technology

• Contract accounts are those that are managed by a contract


code and have a code connected with them.

Account state

The account state is made up of four components that are present


regardless of account type:

• nonce: This number represents the number of transactions


sent from the account's address if it is an externally held
account. The nonce is the number of contracts created by
the account if it is a contract account.
• balance: This address owns a certain number of Wei. Per
Ether, there are 1e+18 Wei.
• storageRoot: A hash of the Merkle Patricia tree's root
node. This tree, which is empty by default, encodes the
hash of this account's storage contents.
• codeHash: The hash of this account's EVM. This is the
code that is hashed and stored as the codeHash for contract
accounts. The codeHash field for externally owned
accounts is the hash of the empty text.

Figure 5.1: Ethereum account

83
Introduction to Blockchain Technology

Every block has a “header” which stores the hash of the root node
of three different Merkle trie structures, including:

• State trie
• Transactions trie
• Receipts trie

Figure 5.2: The state of Ethereum blockchain

The global state of Ethereum is known to be a mapping between


account addresses and account states. This mapping is saved in a
Merkle Patricia tree, which is a data structure.

Gas and payment

One very important concept in Ethereum is the concept of fees.


Every computation that occurs as a result of a transaction on the
Ethereum network incurs a fee — there’s no free lunch! This fee is
paid in a denomination called “gas.”

84
Introduction to Blockchain Technology

Gas is the unit used to measure the fees required for a particular
computation. Gas price is the amount of Ether you are willing to
spend on every unit of gas and is measured in “gwei.” “Wei” is the
smallest unit of Ether, where 1⁰¹⁸ Wei represents 1 Ether. One gwei
is 1,000,000,000 Wei.

With every transaction, a sender sets a gas limit and gas price. The
product of gas price and gas limit represents the maximum
amount of Wei that the sender is willing to pay for executing a
transaction.

For example, let’s say the sender sets the gas limit to 50,000 and a
gas price to 20 gwei. This implies that the sender is willing to
spend at most 50,000 x 20 gwei = 1,000,000,000,000,000 Wei =
0.001 Ether to execute that transaction.

There are fees for storage, too


Not only is gas used to pay for computation steps, it is also used to
pay for storage usage. The total fee for storage is proportional to
the smallest multiple of 32 bytes used.

What’s the purpose of fees?

One important aspect of the way the Ethereum works is that every
single operation executed by the network is simultaneously
affected by every full node. However, computational steps on the
Ethereum Virtual Machine are very expensive. Therefore,
Ethereum smart contracts are best used for simple tasks, like
running simple business logic or verifying signatures and other
cryptographic objects, rather than more complex uses, like file
storage, email, or machine learning, which can put a strain on the
network. Imposing fees prevents users from overtaxing the
network.

85
Introduction to Blockchain Technology

Ethereum is a Turing complete language. (In short, a Turing


machine is a machine that can simulate any computer algorithm
(for those not familiar with Turing machines, check out this and
this). This allows for loops and makes Ethereum susceptible to the
halting problem, a problem in which you cannot determine
whether or not a program will run infinitely. If there were no fees,
a malicious actor could easily try to disrupt the network by
executing an infinite loop within a transaction, without any
repercussions. Thus, fees protect the network from deliberate
attacks.

Transaction and messages

We noted earlier that Ethereum is a transaction-based state


machine. In other words, transactions occurring between different
accounts are what move the global state of Ethereum from one
state to the next.

In the most basic sense, a transaction is a cryptographically signed


piece of instruction that is generated by an externally owned
account, serialized, and then submitted to the blockchain. There
are two types of transactions: message calls and contract
creations (i.e. transactions that create new Ethereum contracts).
All transactions contain the following components, regardless of
their type:

• nonce: a count of the number of transactions sent by the


sender.
• gasPrice: the number of Wei that the sender is willing to
pay per unit of gas required to execute the transaction.

86
Introduction to Blockchain Technology

• gasLimit: the maximum amount of gas that the sender is


willing to pay for executing this transaction. This amount
is set and paid upfront, before any computation is done.
• to: the address of the recipient. In a contract-creating
transaction, the contract account address does not yet
exist, and so an empty value is used.
• value: the amount of Wei to be transferred from the sender
to the recipient. In a contract-creating transaction, this
value serves as the starting balance within the newly
created contract account.
• v, r, s: used to generate the signature that identifies the
sender of the transaction.
• init (only exists for contract-creating transactions): An
EVM code fragment that is used to initialize the new
contract account. init is run only once, and then is
discarded. When init is first run, it returns the body of the
account code, which is the piece of code that is
permanently associated with the contract account.
• data (optional field that only exists for message calls):
the input data (i.e. parameters) of the message call. For
example, if a smart contract serves as a domain registration
service, a call to that contract might expect input fields
such as the domain and IP address.

87
Introduction to Blockchain Technology

Figure 5.3: Structure of transaction in Ethereum

We learned in the “Accounts” section that transactions — both


message calls and contract-creating transactions — are always
initiated by externally owned accounts and submitted to the
blockchain. Another way to think about it is that transactions are
what bridge the external world to the internal state of Ethereum.

Blocks

All transactions are grouped together into “blocks.” A blockchain


contains a series of such blocks that are chained together.

In Ethereum, a block consists of:

• the block header

88
Introduction to Blockchain Technology

• information about the set of transactions included in that


block
• a set of other block headers for the current block’s ommers.

Ommers explained

An ommer is a block whose parent is equal to the current block’s


parent’s parent. Let’s take a quick dive into what ommers are used
for and why a block contains the block headers for ommers.

Because of the way Ethereum is built, block times are much lower
(~15 seconds) than those of other blockchains, like Bitcoin (~10
minutes). This enables faster transaction processing. However, one
of the downsides of shorter block times is that more competing
block solutions are found by miners. These competing blocks are
also referred to as “orphaned blocks” (i.e. mined blocks do not
make it into the main chain).

Figure 5.4: Ommers in Ethereum

The purpose of ommers is to help reward miners for including


these orphaned blocks. The ommers that miners include must be

89
Introduction to Blockchain Technology

“valid,” meaning within the sixth generation or smaller of the


present block. After six children, stale orphaned blocks can no
longer be referenced (because including older transactions would
complicate things a bit).

Ommer blocks receive a smaller reward than a full block.


Nonetheless, there’s still some incentive for miners to include
these orphaned blocks and reap a reward.

Block header

Let’s get back to blocks for a moment. We mentioned previously


that every block has a block “header,” but what exactly is this? A
block header is a portion of the block consisting of:

• parentHash: a hash of the parent block’s header (this is


what makes the block set a “chain”)
• ommersHash: a hash of the current block’s list of ommers
• beneficiary: the account address that receives the fees for
mining this block
• stateRoot: the hash of the root node of the state trie
(recall how we learned that the state trie is stored in the
header and makes it easy for light clients to verify anything
about the state)
• transactionsRoot: the hash of the root node of the trie
that contains all transactions listed in this block
• receiptsRoot: the hash of the root node of the trie that
contains the receipts of all transactions listed in this block
• logsBloom: a Bloom filter (data structure) that consists of
log information
• difficulty: the difficulty level of this block

90
Introduction to Blockchain Technology

• number: the count of current block (the genesis block has


a block number of zero; the block number increases by 1 for
each each subsequent block)
• gasLimit: the current gas limit per block
• gasUsed: the sum of the total gas used by transactions in
this block
• timestamp: the unix timestamp of this block’s inception
• extraData: extra data related to this block
• mixHash: a hash that, when combined with the nonce,
proves that this block has carried out enough computation
• nonce: a hash that, when combined with the mixHash,
proves that this block has carried out enough computation

Contract creation

Remember that there are two kinds of accounts in Ethereum:


contract accounts and externally owned accounts. When we say
that a transaction is "contract-creating," we indicate that its goal
is to generate a new contract account.

To create a new contract account, we first declare the address of


the new account using a special formula. Then we initialize the
new account by:

• Setting the nonce to zero


• If the sender sent some amount of Ether as value with the
transaction, setting the account balance to that value
• Deducting the value added to this new account’s balance
from the sender’s balance
• Setting the storage as empty
• Setting the contract’s codeHash as the hash of an empty
string

91
Introduction to Blockchain Technology

Once we initialize the account, we can actually create the account,


using the init code sent with the transaction (see the “Transaction
and messages” section for a refresher on the init code). What
happens during the execution of this init code is varied.
Depending on the constructor of the contract, it might update the
account’s storage, create other contract accounts, make other
message calls, etc.

As the code to initialize a contract is executed, it uses gas. The


transaction is not allowed to use up more gas than the remaining
gas. If it does, the execution will hit an out-of-gas (OOG)
exception and exit. If the transaction exits due to an out-of-gas
exception, then the state is reverted to the point immediately prior
to transaction. The sender is not refunded the gas that was spent
before running out.

However, if the sender sent any Ether value with the transaction,
the Ether value will be refunded even if the contract creation
fails. If the initialization code executes successfully, a final
contract-creation cost is paid. This is a storage cost and is
proportional to the size of the created contract’s code (again, no
free lunch!) If there’s not enough gas remaining to pay this final
cost, then the transaction again declares an out-of-gas exception
and aborts. If all goes well and we make it this far without
exceptions, then any remaining unused gas is refunded to the
original sender of the transaction, and the altered state is now
allowed to persist.

Exercise

1. Determine if the statement is true or false. If false, provide


the true answer.
92
Introduction to Blockchain Technology

a. Ethereum maintains three kinds of account.


b. 20 bytes address is associated with Ethereum
account.
c. Ethereum block header contains three different
Merkle trie.
d. Fee is not required for storage and computation on
the Ethereum.
e. The transaction is not allowed to use up more gas
than the remaining gas.
2. What are the different components of Ethereum?
3. Briefly discuss the elements of an Ethereum transaction.
4. Draw the structure of Ethereum block’s header.
5. Why is fee required in Ethereum blockchain to execute
user’s smart contract?
6. Explain ommers block in the Ethereum.
7. What are the different accounts maintained by the
Ethereum blockchain? State the differences between them.
8. Shortly describe the features/structures of an Ethereum
account.

93
Introduction to Blockchain Technology

CHAPTER 6
SMART CONTRACT USING SOLIDITY
LANGUAGE

Smart Contract

The Ethereum blockchain allows us to execute code with the


Ethereum Virtual Machine (EVM) on the blockchain with
something called a smart contract.

Smart contracts are where all the business logic of our application
lives. This is where we’ll code the decentralized portion of our app
discussed in the next chapter. Smart contracts are in charge of
reading and writing data to the blockchain, as well as executing
business logic. Smart contacts are written in a programming
language called Solidity, which looks a lot like Javascript. It is a
full-blown programming language that will allow us to do many of
the same types of things Javascript is capable of, but it behaves a
bit differently because of its use case.

Solidity Language

The complete manual of solidity language is available on the


following website:

https://docs.soliditylang.org/en/v0.8.4/introduction-to-smart-
contracts.html#a-simple-smart-contract

The first line is a pragma directive which tells that the source code
is written for Solidity version 0.4.0 or anything newer that does
not break functionality up to, but not including, version 0.6.0.

94
Introduction to Blockchain Technology

pragma solidity >=0.4.0;

contract SimpleStorage {

uint storedData;

function set(uint x) public {

storedData = x;

function get() public view returns (uint) {

return storedData; }

Contract

A Solidity contract is a collection of code (its functions) and data


(its state) that resides at a specific address on the Ethereum
Blockchain.

The line uint storedData declares a state variable called storedData


of type uint and the functions set and get can be used to modify or
retrieve the value of the variable.

Importing Files

Though the above example does not have an import statement,


Solidity supports import statements that are very similar to those
available in JavaScript. The following statement imports all global
symbols from "filename".

import "filename";

The following example creates a new global symbol symbolName


whose members are all the global symbols from "filename".

95
Introduction to Blockchain Technology

import * as symbolName from "filename";

To import a file x from the same directory as the current file, use
import "./x" as x;. If you use import "x" as x; instead, a different file
could be referenced in a global "include directory".

Reserved Keywords

Following are the reserved keywords in Solidity −

abstract after alias apply

auto case catch copyof

default define final immutable

implements in inline let

macro match mutable null

of override partial promise

reference relocatable sealed sizeof

static supports switch try

typedef typeof unchecked

Run a Smart Contract

Step 1: Go to the remix (mix.ethereum.org) online editor and paste


the following code segment.

pragma solidity ^0.5.0;

96
Introduction to Blockchain Technology

contract SolidityTest {

constructor() public{

function getResult() public view returns(uint){

uint a = 1;

uint b = 2;

uint result = a + b;

return result;

Step 2 − Under the Compile Tab, click Start to Compile button.


Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.

Solidity supports both C-style and C++-style comments, Thus −


• Any text between a // and the end of a line is treated as a
comment and is ignored by Solidity Compiler.
• Any text between the characters /* and */ is treated as a
comment. This may span multiple lines.

Example

The following example shows how to use comments in Solidity.


function getResult() public view returns(uint){
// This is a comment. It is similar to comments in C++

/*
* This is a multi-line comment in solidity
* It is very similar to comments in C Programming
*/
uint a = 1;

97
Introduction to Blockchain Technology

uint b = 2;
uint result = a + b;
return result;
}

Value Types

Solidity offers the programmer a rich assortment of built-in as well as


user defined data types. Following table lists down seven basic C++ data
types

Type Keyword Values

Boolean bool true/false

Signed and unsigned integers of varying


Integer int/uint
sizes.

Signed int from 8 bits to 256 bits. int256 is


Integer int8 to int256
same as int.

uint8 to Unsigned int from 8 bits to 256 bits. uint256


Integer
uint256 is same as uint.

Fixed
Signed and unsigned fixed point numbers of
Point fixed/unfixed
varying sizes.
Numbers
Fixed
Signed and unsigned fixed point numbers of
Point fixed/unfixed
varying sizes.
Numbers
Signed fixed point number where M
represents number of bits taken by type and
Fixed
N represents the decimal points. M should
Point fixedMxN
be divisible by 8 and goes from 8 to 256. N
Numbers
can be from 0 to 80. fixed is same as
fixed128x18.

98
Introduction to Blockchain Technology

Unsigned fixed point number where M


represents number of bits taken by type and
Fixed
N represents the decimal points. M should
Point ufixedMxN
be divisible by 8 and goes from 8 to 256. N
Numbers
can be from 0 to 80. ufixed is same as
ufixed128x18.

Enums and Struct

Enums are the way of creating user-defined data types, it is usually


used to provide names for integral constants which makes the
contract better for maintenance and reading. Enums restrict the
variable with one of few predefined values, these values of the
enumerated list are called enums. Options are represented with
integer values starting from zero, a default value can also be given
for the enum. By using enums it is possible to reduce the bugs in
the code.

Syntax:

enum <enumerator_name> {

element 1, element 2,....,element n

Example: In the below example, the contract Types consist of an


enumerator week_days, and functions are defined to set and get
the value of a variable of type enumerator.

99
Introduction to Blockchain Technology

//Solidity program to // Setting a default value


demonstrate week_days constant
// how to use 'enumerator' default_value
pragma solidity ^0.5.0; = week_days.Sunday;

// Creating a contract // Defining a function to


contract Types { // set value of choice
// Creating an enumerator function set_value() public {
enum week_days choice = week_days.Thursday;
{ }
Monday,
Tuesday, // Defining a function to
Wednesday, // return value of choice
Thursday, function get_choice(
Friday, ) public view returns
Saturday, (week_days) {
Sunday return choice;
} }

// Defining function to
// Declaring variables of type // return default value
enumerator function getdefaultvalue(
) public pure
week_days week; returns(week_days) {
return default_value;
week_days choice; }
}

Output:

100
Introduction to Blockchain Technology

Struct

Solidity allows users to create their own data type in the form of
structure. The struct contains a group of elements with a different
data type. Generally, it is used to represent a record. To define a
structure struct keyword is used, which creates a new data type.

Syntax:

struct <structure_name> {
<data type> variable_1;
<data type> variable_2;
}
Struct student
{
String name;
String id;
Uint age;
}

For accessing any element of the structure dot operator is used,


which separates the struct variable and the element we wish to

101
Introduction to Blockchain Technology

access. To define the variable of structure data type structure


name is used.

Example: In the below example, the contract Test consists of a


structure Book, and functions are defined to set and get values of
the elements of the structure.

//Solidity program to "Roberto Infante ",


demonstrate 2, false);
// how to use 'structures'
pragma solidity ^0.5.0; // Defining a function to set values
// for the fields for structure book1
// Creating a contract function set_book_detail() public {
contract test { book1 = Book("Introducing
Ethereum and Solidity",
// Declaring a structure "Chris Dannen",
struct Book { 1, true);
string name; }
string writter; // Defining function to print book2
uint id; details
bool available; function book_info(
} )public view returns (
string memory, string memory,
// Declaring a structure object uint, bool) {
Book book1;
//Assigning values to the return(book2.name,
fields for the structure object book2.writter,
book2 book2.id, book2.available);
}
Book book2
= Book("Building Ethereum // Defining function to print
DApps", // book1 details
function get_details(

102
Introduction to Blockchain Technology

) public view returns (string memory,


uint) {
return (book1.name, book1.id);
}
}

Output :

Address

Address holds the 20-byte value representing the size of an


Ethereum address. An address can be used to get the balance
using. balance method and can be used to transfer balance to
another address using. transfer method.

address x = 0x212;

103
Introduction to Blockchain Technology

address myAddress = this;


if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);

Solidity supports three types of variables.

• State Variables: Variables whose values are permanently


stored in a contract storage.
• Local Variables: Variables whose values are present till
function is executing.
• Global Variables: Special variables exist in the global
namespace used to get information about the blockchain.

Solidity is a statically typed language, which means that the state


or local variable type needs to be specified during declaration.
Each declared variable always has a default value based on its type.
There is no concept of "undefined" or "null".

State Variable

Variables whose values are permanently stored in a contract


storage.

pragma solidity ^0.5.0;


contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10; // Using State variable
}
}

Local Variable

Variables whose values are available only within a function where


it is defined. Function parameters are always local to that
function.

104
Introduction to Blockchain Technology

Example:
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result; //access the local variable
}
}
Run the above program using steps provided in the beginning of
the chapter.

Output

0: uint256: 10

Global Variables

These are special variables that exist in the global workspace and
provide information about the blockchain and transaction
properties.

Name Returns

blockhash(uint Hash of the given block - only works for


blockNumber) returns 256 most recent, excluding current,
(bytes32) blocks
block.coinbase (address
Current block miner's address
payable)

105
Introduction to Blockchain Technology

block.difficulty (uint) Current block difficulty

block.gaslimit (uint) Current block gaslimit

block.number (uint) Current block number

Current block timestamp as seconds since


block.timestamp (uint)
unix epoch

gasleft() returns (uint256) Remaining gas

msg.data (bytes calldata) Complete calldata

msg.sender (address
Sender of the message (current caller)
payable)
First four bytes of the calldata (function
msg.sig (bytes4)
identifier)

msg.value (uint) Number of wei sent with the message

now (uint) Current block timestamp

tx.gasprice (uint) Gas price of the transaction

tx.origin (address payable) Sender of the transaction

Solidity Variable Names

While naming your variables in Solidity, keep the following rules


in mind.

• You should not use any of the Solidity reserved keywords as


a variable name. These keywords are mentioned in the next
section. For example, break or boolean variable names are
not valid.
• Solidity variable names should not start with a numeral (0-
9). They must begin with a letter or an underscore

106
Introduction to Blockchain Technology

character. For example, 123test is an invalid variable name


but _123test is a valid one.
• Solidity variable names are case-sensitive. For example,
Name and name are two different variables.

Variable Scope

Scope of local variables is limited to the function in which they are


defined but State variables can have three types of scopes.

• Public: Public state variables can be accessed internally as


well as via messages. For a public state variable, an
automatic getter function is generated.
• Internal: Internal state variables can be accessed only
internally from the current contract or contract deriving
from it without using this.
• Private: Private state variables can be accessed only
internally from the current contract; they are defined not
in the derived contract from it.

Example

pragma solidity ^0.5.0;


contract C {
uint public data = 30;
uint internal iData= 10;

function x() public returns (uint) {


data = 3; // internal access
return data;
}
}
contract Caller {
C c = new C();

107
Introduction to Blockchain Technology

function f() public view returns (uint) {


return c.data(); //external access }
}
contract D is C {
function y() public returns (uint) {
iData = 3; // internal access
return iData;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return storedData; //access the state variable
}
}

Mapping in Solidity

Mapping in Solidity acts like a hashtable or dictionary in any other


language. These are used to store the data in the form of key-value
pairs, a key can be any of the built-in data types but reference
types are not allowed while the value can be of any type. Mappings
are mostly used to associate the unique Ethereum address with the
associated value type.

Syntax:

mapping(key => value) <access specifier> <name>;

Creating a Mapping

Mapping is defined as any other variable type, which accepts a key


type and a value type. More on mapping types can be found in the

108
Introduction to Blockchain Technology

following link. https://coursetro.com/posts/code/102/Solidity-


Mappings-&-Structs-Tutorial

contract Courses {

struct Instructor {
uint age;
string fName;
string lName;
}

mapping (address => Instructor) instructors;


address[] public instructorAccts;

Example

Try the following code to see the use of msg, a special variable to
get the sender address in Solidity.

pragma solidity ^0.5.0;


contract LedgerBalance {
mapping(address => uint) public balances;

function updateBalance(uint newBalance) public {


balances[msg.sender] = newBalance;
}
}
contract Updater {
function updateBalance() public returns (uint) {
LedgerBalance ledgerBalance = new LedgerBalance();
ledgerBalance.updateBalance(10);
return ledgerBalance.balances(address(this));

109
Introduction to Blockchain Technology

}
}
Run the above program. First Click updateBalance Button to set
the value as 10 then look into the logs which will show the
decoded output as −

Output

{
"0": "uint256: 10"
}

Storage and Memory

Storage and Memory keywords in Solidity are analogous to


Computer’s hard drive and a Computer’s RAM. Much like RAM,
Memory in Solidity is a temporary place to store data whereas
Storage holds data between function calls. The Solidity Smart
Contract can use any amount of memory during the execution but
once the execution stops, the Memory is completely wiped off for
the next execution. Whereas Storage on the other hand is
persistent, each execution of the Smart contract has access to the
data previously stored on the storage area.

Every transaction on Ethereum Virtual Machine costs us some


amount of Gas. The lower the Gas consumption the better is your
Solidity code. The Gas consumption of Memory is not very
significant as compared to the gas consumption of Storage.
Therefore, it is always better to use Memory for intermediate
calculations and store the result in Storage.

110
Introduction to Blockchain Technology

State variables and Local Variables of structs, arrays are always


stored in storage by default.

Function arguments are in memory.

Whenever a new instance of an array is created using the keyword


‘memory’, a new copy of that variable is created. Changing the
array value of the new instance does not affect the original array.

Example#1: In the below example, a contract is created to


demonstrate the ‘storage’ keyword.

pragma solidity ^0.4.17; function Numbers() public


// Creating a contract {
contract helloGeeks numbers.push(1);
{ numbers.push(2);
// Initialising array numbers
int[] public numbers; //Creating a new instance
int[] storage myArray = numbers;
// Function to insert values
// in the array numbers // Adding value to the
// first index of the new Instance
myArray[0] = 0;
}
}

Output:

When we retrieve the value of the array numbers in the above


code, note that the output of the array is [0,2] and not [1,2]. This
can be understood from the following diagram.

111
Introduction to Blockchain Technology

Example#2: In the below example, a contract is created to


demonstrate the keyword ‘memory’.

pragma solidity ^0.4.17; numbers.push(1);


numbers.push(2);
// Creating a contract
contract helloGeeks //creating a new instance
{ int[] memory myArray = numbers;
// Initialising array numbers
int[] public numbers; // Adding value to the first
// index of the array at myArray
// Function to insert myArray[0] = 0;
// values in the array }
// numbers }
function Numbers() public
{

Output:

When we retrieve the value of the array numbers in the above


code, note that the output of the array is [1,2]. In this case,
changing the value of myArray does not affect the value in the

112
Introduction to Blockchain Technology

array numbers. This can be understood from the following


diagram.

Addition, subtraction, multiplication, and division

Go to the following link and run the programs on Remix.


https://www.geeksforgeeks.org/mathematical-operations-in-
solidity/

Function Definition

Before we use a function, we need to define it. The most common


way to define a function in Solidity is by using the function
keyword, followed by a unique function name, a list of parameters
(that might be empty), and a statement block surrounded by curly
braces.

Syntax

The basic syntax is shown here.

function function-name(parameter-list) scope returns() {

//statements }

113
Introduction to Blockchain Technology

Example

Try the following example. It defines a function called getResult


that takes no parameters −

pragma solidity ^0.5.0;


contract Test {
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result;
}
}

Calling a Function

To invoke a function somewhere later in the Contract, you would


simply need to write the name of that function as shown in the
following code. Try the following code to understand how the
string works in Solidity.

pragma solidity ^0.5.0;


contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {

114
Introduction to Blockchain Technology

if (_i == 0) {
return "0";
}
uint j = _i;
uint len;

while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;

while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);//access local variable
}
}
Run the above program.

Output

0: string: 3

Function Parameters

Till now, we have seen functions without parameters. But there is


a facility to pass different parameters while calling a function.
These passed parameters can be captured inside the function and
any manipulation can be done over those parameters. A function
can take multiple parameters separated by a comma.

115
Introduction to Blockchain Technology

Example

Try the following example. We have used a uint2str function here.


It takes one parameter.

pragma solidity ^0.5.0;


contract SolidityTest {
constructor() public{
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {

if (_i == 0) {
return "0";
}
uint j = _i;
uint len;

while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;

while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}

116
Introduction to Blockchain Technology

return string(bstr);//access local variable


}
}

Run the above program.

Output

0: string: 3

The return Statement

A Solidity function can have an optional return statement. This is


required if you want to return a value from a function. This
statement should be the last statement in a function. As in the
above example, we are using uint2str function to return a string.

In Solidity, a function can return multiple values as well. See the


example below −

pragma solidity ^0.5.0;


contract Test {
function getResult() public view returns(uint product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
//alternative return statement to return multiple values
//return(a*b, a+b);
}
}
Run the above program using steps provided in the beginning of
the chapter.

Output

117
Introduction to Blockchain Technology

0: uint256: product 2

1: uint256: sum 3

Function Modifier

Function Modifiers are used to modify the behaviour of a function.


For example to add a prerequisite to a function. First we create a
modifier with or without parameters.

contract Owner {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
The function body is inserted where the special symbol "_;"
appears in the definition of a modifier. So, if the condition of the
modifier is satisfied while calling this function, the function is
executed and otherwise, an exception is thrown. See the example
below.

pragma solidity ^0.5.0;


contract Owner {
address owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);

118
Introduction to Blockchain Technology

_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
contract Register is Owner {
mapping (address => bool) registeredAddresses;
uint price;
constructor(uint initialPrice) public { price = initialPrice; }

function register() public payable costs(price) {


registeredAddresses[msg.sender] = true;
}
function changePrice(uint _price) public onlyOwner {
price = _price;
}
}

View functions ensure that they will not modify the state. A
function can be declared as a view. The following statements if
present in the function are considered modifying the state and the
compiler will throw a warning in such cases.

• Modifying state variables.


• Emitting events.
• Creating other contracts.
• Using self-destruct.
• Sending Ether via calls.
• Calling any function which is not marked view or pure.
• Using low-level calls.
• Using inline assembly containing certain opcodes.

119
Introduction to Blockchain Technology

• Getter methods are by default view functions.


• See the example below using a view function.

Example

pragma solidity ^0.5.0;

contract Test {
function getResult() public view returns(uint
product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
}
}
Run the above program.

Output

0: uint256: product 2

1: uint256: sum 3

Pure functions ensure that they do not read or modify the state. A
function can be declared as pure. The following statements if
present in the function are considered reading the state and the
compiler will throw a warning in such cases.

Reading state variables.

Accessing address (this).balance or <address>.balance.

120
Introduction to Blockchain Technology

Accessing any of the special variables of block, tx, msg (msg.sig


and msg.data can be read). Calling any function not marked pure.

• Using inline assembly that contains certain opcodes.


• Pure functions can use the revert() and require() functions
to revert potential state changes if an error occurs.

See the example below using a view function.

Example

pragma solidity ^0.5.0;


contract Test {
function getResult() public pure returns(uint
product, uint sum){
uint a = 1;
uint b = 2;
product = a * b;
sum = a + b;
}
}
Run the above program.

Output

0: uint256: product 2

1: uint256: sum 3

Cryptographic functions

Solidity provides inbuilt cryptographic functions as well. Following


are important methods.

121
Introduction to Blockchain Technology

• keccak256(bytes memory) returns (bytes32): computes the


Keccak-256 hash of the input.
• sha256(bytes memory) returns (bytes32) − computes the
SHA-256 hash of the input.
• ripemd160(bytes memory) returns (bytes20) − compute
RIPEMD-160 hash of the input.
• sha256(bytes memory) returns (bytes32) − computes the
SHA-256 hash of the input.
• ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
returns (address) − recover the address associated with the
public key from elliptic curve signature or return zero on
error. The function parameters correspond to ECDSA
values of the signature: r - first 32 bytes of signature; s:
second 32 bytes of signature; v: final 1 byte of signature.
This method returns an address.

The following example shows the usage of cryptographic function


in Solidity.

Example

pragma solidity ^0.5.0;


contract Test {
function callKeccak256() public pure returns(bytes32 result){
return keccak256("ABC");
}
}
Run the above program.

Output

122
Introduction to Blockchain Technology

0: bytes32: result
0xe1629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa
35d54f3c8

Event

Generally, events are used to inform the calling application about


the current state of the contract, with the help of the logging
facility of EVM. Events notify the applications about the change
made to the contracts and applications which can be used to
execute the dependent logic.

Creating an event

Events are defined within the contracts as global and called within
its functions. Events are declared by using the event keyword,
followed by an identifier and the parameter list, and ends with a
semicolon. The parameter values are used to log the information
or for executing the conditional logic. Its information and values
are saved as part of the transactions inside the block. There is no
need of providing variables, only datatypes are sufficient. An event
can be called from any method by using its name and passing the
required parameters.

event <eventName>(parameters) ;

123
Introduction to Blockchain Technology

// Solidity program to demonstrate


// creating an event
pragma solidity ^0.4.21;

// Creating a contract
contract eventExample {

// Declaring state variables


uint256 public value = 0;

// Declaring an event
event Increment(address owner);

// Defining a function for logging event


function getValue(uint _a, uint _b) public {
emit Increment(msg.sender);
value = _a + _b;
}
}

Event is an inheritable member of a contract. An event is emitted,


it stores the arguments passed in transaction logs. These logs are
stored on blockchain and are accessible using the address of the
contract till the contract is present on the blockchain. An event
generated is not accessible from within contracts, not even the one
which has created and emitted them. An event can be declared
using the event keyword.

//Declare an Event
event Deposit(address indexed _from, bytes32 indexed _id, uint
_value);

124
Introduction to Blockchain Technology

//Emit an event
emit Deposit(msg.sender, _id, msg.value);

Example

Try the following code to understand how an event works in


Solidity. First Create a contract and emit an event.

pragma solidity ^0.5.0;

contract Test {
event Deposit(address indexed _from, bytes32 indexed _id, uint
_value);
function deposit(bytes32 _id) public payable {
emit Deposit(msg.sender, _id, msg.value);
}
}
Then access the contract's event in JavaScript code.
var abi = /* abi as generated using compiler */;
var ClientReceipt = web3.eth.contract(abi);
var clientReceiptContract = ClientReceipt.at("0x1234...ab67" /*
address */);

var event = clientReceiptContract.Deposit(function(error, result)


{
if (!error)console.log(result);
});
It should print details similar to as following.

Output

{
"returnValues": {
"_from": "0x1111...FFFFCCCC",
"_id": "0x50...sd5adb20",

125
Introduction to Blockchain Technology

"_value": "0x420042"
},
"raw": {
"data": "0x7f...91385",
"topics": ["0xfd4...b4ead7", "0x7f...1a91385"]
}
}

Creating and verifying signature

Go to the following link to create and verify digital signature using


solidity language. https://docs.soliditylang.org/en/latest/solidity-
by-example.html

The Ethereum Virtual Machine

The Ethereum Virtual Machine or EVM is the runtime


environment for smart contracts in Ethereum. It is not only
sandboxed but actually completely isolated, which means that
code running inside the EVM has no access to the network,
filesystem or other processes. Smart contracts even have limited
access to other smart contracts.

Accounts

There are two kinds of accounts in Ethereum which share the same
address space: External accounts that are controlled by public-
private key pairs (i.e. humans) and contract accounts which are
controlled by the code stored together with the account.

The address of an external account is determined from the public


key while the address of a contract is determined at the time the
contract is created (it is derived from the creator address and the

126
Introduction to Blockchain Technology

number of transactions sent from that address, the so-called


“nonce”). Regardless of whether the account stores code, the two
types are treated equally by the EVM. Every account has a
persistent key-value store mapping 256-bit words to 256-bit words
called storage. Furthermore, every account has a balance in Ether
(in “Wei” to be exact, 1 ether is 10**18 wei) which can be modified
by sending transactions that include Ether.

Transactions

A transaction is an electronic message delivered from one account


to another (which might be the same or empty, see below). It can
contain binary data (referred to as "payload") as well as Ether. If
the target account contains code, the target account's code is
executed, and the payload is used as input data.

If the target account is not specified (because the transaction lacks


a recipient or the recipient is set to null), the transaction generates
a new contract. As previously stated, the contract's address is not
zero, but is formed from the sender and the number of
transactions sent (the "nonce"). The payload of such a contract
generation transaction is interpreted and executed as EVM
bytecode. The contract's code is permanently recorded as the
output data from this execution. This means that when you create
a contract, you do not send the contract's actual code, but rather
code that returns the contract's code when performed.

Note

While the contract is being generated, the contract's code remains


empty. As a result, you should refrain from calling back into the

127
Introduction to Blockchain Technology

contract in progress until its constructor has completed its


execution.

Gas

Each transaction is created with a certain amount of gas with the


goal of minimizing the amount of work necessary to execute a
transaction. The gas is steadily reduced while the EVM processes
the transaction.

The gas price is determined by the author of the transactions, who


must pay gas_price * gas from the sending account. If any gas
remains after the execution, it is reimbursed to the creator. If the
gas runs out (becomes negative), an out-of-gas exception is
thrown, reverting all state changes done in the current call frame.

Storage, Memory, and the Stack

The Ethereum Virtual Machine has three areas where it can store
data- storage, memory, and the stack, which are explained in the
following paragraphs.

Each account has a data area called storage, which is persistent


between function calls and transactions. Storage is a key-value
store that maps 256-bit words to 256-bit words. It is not possible
to enumerate storage from within a contract, it is comparatively
costly to read, and even more to initialize and modify storage.
Because of this cost, you should minimize what you store in
persistent storage to what the contract needs to run. Store data
like derived calculations, caching, and aggregates outside of the
contract. A contract can neither read nor write to any storage apart
from its own.

128
Introduction to Blockchain Technology

The second data area is called memory, of which a contract obtains


a freshly cleared instance for each message call. Memory is linear
and can be addressed at byte level but reads are limited to a width
of 256 bits, while writes can be either 8 bits or 256 bits wide.
Memory is expanded by a word (256-bit), when accessing (either
reading or writing) a previously untouched memory word (i.e. any
offset within a word). At the time of expansion, the cost of gas
must be paid. Memory is more costly the larger it grows (it scales
quadratically).

The EVM is not a register machine but a stack machine, so all


computations are performed on a data area called the stack. It has
a maximum size of 1024 elements and contains words of 256 bits.
Access to the stack is limited to the top end in the following way:
It is possible to copy one of the topmost 16 elements to the top of
the stack or swap the topmost element with one of the 16 elements
below it. All other operations take the topmost two (or one, or
more, depending on the operation) elements from the stack and
push the result onto the stack. Of course, it is possible to move
stack elements to storage or memory in order to get deeper access
to the stack, but it is not possible to just access arbitrary elements
deeper in the stack without first removing the top of the stack.

Instruction Set

The instruction set of the EVM is kept minimal in order to avoid


incorrect or inconsistent implementations which could cause
consensus problems. All instructions operate on the basic data
type, 256-bit words or on slices of memory (or other byte arrays).
The usual arithmetic, bit, logical and comparison operations are
present. Conditional and unconditional jumps are possible.

129
Introduction to Blockchain Technology

Furthermore, contracts can access relevant properties of the


current block like its number and timestamp.

For a complete list, please see the list of opcodes as part of the
inline assembly documentation.

Message Calls

Contracts can call other contracts or send Ether to non-contract


accounts by the means of message calls. Message calls are similar
to transactions, in that they have a source, a target, data payload,
Ether, gas and return data. In fact, every transaction consists of a
top-level message call which in turn can create further message
calls.

A contract can decide how much of its remaining gas should be


sent with the inner message call and how much it wants to retain.
If an out-of-gas exception happens in the inner call (or any other
exception), this will be signaled by an error value put onto the
stack. In this case, only the gas sent together with the call is used
up. In Solidity, the calling contract causes a manual exception by
default in such situations, so that exceptions “bubble up” the call
stack.

As already said, the called contract (which can be the same as the
caller) will receive a freshly cleared instance of memory and has
access to the call payload - which will be provided in a separate
area called the calldata. After it has finished execution, it can
return data which will be stored at a location in the caller’s
memory preallocated by the caller. All such calls are fully
synchronous.

130
Introduction to Blockchain Technology

Calls are limited to a depth of 1024, which means that for more
complex operations, loops should be preferred over recursive calls.
Furthermore, only 63/64th of the gas can be forwarded in a
message call, which causes a depth limit of a little less than 1000
in practice.

Delegatecall / Callcode and Libraries

There exists a special variant of a message call, named delegatecall


which is identical to a message call apart from the fact that the
code at the target address is executed in the context of the calling
contract and msg.sender and msg.value do not change their
values.

This means that a contract can dynamically load code from a


different address at runtime. Storage, current address, and balance
still refer to the calling contract, only the code is taken from the
called address.

This makes it possible to implement the “library” feature in


Solidity: Reusable library code that can be applied to a contract’s
storage, e.g. in order to implement a complex data structure.

Logs

It is possible to store data in a specially indexed data structure that


maps all the way up to the block level. This feature called logs is
used by Solidity in order to implement events. Contracts cannot
access log data after it has been created, but they can be efficiently
accessed from outside the blockchain. Since some part of the log
data is stored in bloom filters, it is possible to search for this data
in an efficient and cryptographically secure way, so network peers

131
Introduction to Blockchain Technology

that do not download the whole blockchain (so-called “light


clients”) can still find these logs.

Exercise

1. Differentiate between storage and memory variables.


2. Explain public, view, external, and pure.
3. Provide an example of mapping in Solidity Language.
4. Write two global special variables(built-in).
5. What is the event in Solidity? Provide an example of a
smart contract that uses events.
6. Write a smart contract that can do the following
7. Declare a struct which contains id, name, gpa of a student.
8. Declare a mapping for the struct defined above.
9. Define the construction function of the smart contract.
10. Define get function to display information of a student and
set function to set id, name and change the gpa of a
student.
11. Describe two account types of Ethereum virtual machine.
12. Run the following on Remix and explain the output.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Coin {
// The keyword "public" makes variables
// accessible from other contracts
address public minter;
mapping (address => uint) public balances;

132
Introduction to Blockchain Technology

// Events allow clients to react to specific


// contract changes you declare
event Sent(address from, address to, uint
amount);

// Constructor code is only run when the contract


// is created
constructor() {
minter = msg.sender;
}

// Sends an amount of newly created coins to an


address
// Can only be called by the contract creator
function mint(address receiver, uint amount)
public {
require(msg.sender == minter);
balances[receiver] += amount;
}

// Errors allow you to provide information about


// why an operation failed. They are returned
// to the caller of the function.
error InsufficientBalance(uint requested, uint
available);

// Sends an amount of existing coins


// from any caller to an address
function send(address receiver, uint amount)
public {
if (amount > balances[msg.sender])

133
Introduction to Blockchain Technology

revert InsufficientBalance({
requested: amount,
available: balances[msg.sender]
});

balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}

134
Introduction to Blockchain Technology

CHAPTER 7
DECENTRALIZED
APPLICATION

The function of smart contracts on the blockchain is very similar


to a microservice on the web. If the public ledger represents the
database layer of the blockchain, then smart contracts are where
all the business logic that transacts with that data lives.

Also, they're called smart contracts because they represent a


covenant or agreement. In the case of our voting dApp, it is an
agreement that my vote will count, that other votes are only
counted once, and that the candidate with the most votes will win
the election.

Now let’s take a quick look at the structure of the dApp we’re
building.

135
Introduction to Blockchain Technology

Figure 7.1: Design view of a dApp

We’ll have a traditional front-end client that is written in HTML,


CSS, and Javascript. Instead of talking to a back-end server, this
client will connect to a local Ethereum blockchain that we’ll
install. We’ll code all the business logic about our dApp in an
Election smart contract with the Solidity programming language.
We’ll deploy this smart contract to our local Etherum blockchain,
and allow accounts to start voting.

Now we’ve seen what a blockchain is and how it works. We’ve seen
why we want to build our voting dApp on the blockchain instead of
the current web. And we’ve seen that we want to code our dApp by
writing a smart contract that will be deployed to the Ethereum
blockchain. The following steps need to be followed to implement
a dApp.

1. Set up the development environment.

o Install Node.js

o Install Local Ethereum network- Ganache

136
Introduction to Blockchain Technology

o Install Development Framework- Truffle

o Add Metamask Extension on the web browser

2. Development of Front-end: HTML, CSS, JS, Web3js,


React

3. Learn the process of writing a contract, compiling it and


deploying it in your development environment. Building
Smart Contract: Solidity Language, Tools: Visual
Studio Code + Blockchain Development Kit for
Ethereum or Remix

4. Write web3js code in Front-end (UI) to establish


connection & interaction between the UI and Smart
Contract through Metamask

5. Testing Smart Contract. Deploying Smart Contract on


Ganache Local P2P Ethereum network.

The process of building a e-voting dApp

• Set up the development environment.


• Learn the process of writing a contract, compiling it and
deploying it in your development environment.
• Interact with the contract on the blockchain through a
nodejs console.
• Interact with the contract through a simple web page to
display the vote counts and vote for candidates through the
page.

The application that will be built looks like this.

137
Introduction to Blockchain Technology

Figure 7.2: The structure of an e-voting dApp

To build our dApp, we need a few dependencies first.

Node Package Manager (NPM)

The first dependency we need is Node Package Manager, or NPM,


which comes with Node.js. You can see if you have node already
installed by going to your terminal and typing:

$ node -v

Truffle Framework

The next dependency is the Truffle Framework, which allows us to


build decentralized applications on the Ethereum blockchain. It
provides a suite of tools that allow us to write smart contacts with
the Solidity programming language. It also enables us to test our
smart contracts and deploy them to the blockchain. It also gives us
a place to develop our client-side application.
138
Introduction to Blockchain Technology

You can install Truffle with NPM in your command line like this:

$ npm install -g truffle

Ganache

The next dependency is Ganache, a local in-memory blockchain.


You can install Ganache by downloading it from the Truffle
Framework website. It will give us 10 external accounts with
addresses on our local Ethereum blockchain. Each account is
preloaded with 100 fake ethers. You can use the following
command to install Ganache-cli.

$ npm install -g ganache-cli

Metamask

The next dependency is the Metamask extension for Google


Chrome. To use the blockchain, we must connect to it (remember,
I said the block chain is a network). We’ll have to install a special
browser extension to use the Ethereum block chain. That’s where
metamask comes in. We’ll be able to connect to our local
Ethereum blockchain with our personal account and interact with
our smart contract.

We’re going to be using the Metamask chrome extension for this


tutorial, so you’ll also need to install the google chrome browser if
you don’t have it already. To install Metamask, search for the
Metamask Chrome plugin in the Google Chrome web store. Once
you’ve installed it, be sure that it is checked in your list of
extensions. You’ll see the fox icon in the top right-hand side of
your Chrome browser when it’s installed.

Different components of a dApp

139
Introduction to Blockchain Technology

contracts directory: this is where all smart contacts live. We


already have a Migration contract that handles our migrations to
the blockchain.
migrations directory: this is where all the migration files live.
These migrations are like other web development frameworks that
require migrations to change the state of a database. Whenever we
deploy smart contracts to the blockchain, we are updating the
blockchain's state, and therefore need a migration.

node_modules directory: this is the home of all of our Node


dependencies.
src directory: this is where we'll develop our client-side
application.
test directory: this is where we'll write our tests for our smart
contracts.
truffle.js file: this is the main configuration file for our Truffle
project

140
Introduction to Blockchain Technology

Figure 7.3: Structure of a dApp project

Go to the following link to implement e-voting dApp:


https://www.dappuniversity.com/articles/the-ultimate-ethereum-
dapp-tutorial

Download the complete code from the following link:


https://drive.google.com/drive/folders/1ay86n90zr9h8jundOjtBXF
-xJK7GntXG?usp=sharing

Blockchain dApp in Digital Forensics

141
Introduction to Blockchain Technology

Blockchain of extreme importance to guarantee integrity,


authenticity, and auditability of digital evidence as it moves along
different levels of hierarchy in chain of custody during cybercrime
investigation. Blockchain technology’s capability of enabling a
comprehensive view of transactions (events/actions) back to
origination provides enormous promise for the forensic
community. The forensic implications of this powerful technology
include:

• Improved transactional efficiency (owing to increased trust


in the exchanging parties)
• The reduction of fraud (owing to the increased
transparency of the audit trail)
• Reduced costs of certain kinds of transactions owing to the
increased transparency and trust factors which mitigate
against the need for third-party validation of certain
claims, like valuation amounts or the specific ownership of
an asset at a given point in time.

Use case of Blockchain in Digital Forensics

Blockchain and the Digital Forensics Chain of Custody:


Forensic Chain is a blockchain based solution for maintaining and
tracing digital forensics chain of custody. Blockchain is a data
structure that allows to create a digital ledger for recording and
storing transactions (events/records) shared by all participating
parties over a distributed network of computers. Blockchain makes
use of cryptography for protecting the process of recording and
storing transactions (events/records) that happen within the
network, creating unimpeachable audit trail.

142
Introduction to Blockchain Technology

Forensic-Chain is initiated or triggered by First Responder, taking


hash of digital evidence, and recording them securely on
blockchain through smart contract. Other details like location,
time, and date etc. of crime scene also gets recorded on
blockchain.

Using Blockchain Hotel Registries to track criminals and


missing persons: To adopt a blockchain security solution in
hotels across the province, this product merges blockchain and
artificial intelligence (AI) to securely store data about hotel guests
and aims to both bring convenience to customers and to help
prevent criminal activities. The same technology can also be
implemented to secure land registry, employee, educational
certification, and other high-value records. Laws requiring hotels
to report guest information to police daily have resulted in privacy
risks from manual processes and sharing of paper documents. By
storing hotel guest data in blockchain, a hotel manager can
provide guests with a his or her ID, and the ability to consent to
any data transaction. Hotels benefit from a much faster and less
laborious process of compliance with the legal obligation, the
company says.

The data collected is compared with the police database of


criminals, missing persons and so on to ascertain whether the
guest has any criminal background. Digitization of hotel guest
authentication and records has also been encouraged in some
countries including India, Japan, Singapore.

143
Introduction to Blockchain Technology

A decentralized application for storing digital forensics


report in Blockchain

Our dApp will take a digital forensics report as input from a user
and upload it to the IPFS by invoking an Ethereum contract. The
hash of the file will be stored on Ethereum. This is the process
we’ll go through:

• Take a digital forensics report as an input


• Convert file to buffer
• Upload buffer to IPFS
• Store hash of file returned by IPFS
• Get the user’s Metamask Ethereum address
• User confirms transaction to Ethereum via Metamask
• IPFS hash is written on Ethereum

144
Introduction to Blockchain Technology

Figure 8.1: The block diagram of an application that uses IPFS

What is IPFS?

The InterPlanetary File System (IPFS) is a protocol and peer-to-


peer network for storing and sharing data in a distributed file
system. IPFS uses content-addressing to uniquely identify each file
in a global namespace connecting all computing devices.

IPFS allows users to host and receive content in a manner similar


to BitTorrent. As opposed to a centrally located server, IPFS is
built around a decentralized system of user-operators who hold a
portion of the overall data, creating a resilient system of file
storage and sharing. Any user in the network can serve a file by its
content address, and other peers in the network can find and
request that content from any node that has it using a distributed
hash table (DHT).

145
Introduction to Blockchain Technology

How does IPFS work?

IPFS seeks to create a permanent and distributed web. It does this


by using a content-addressed system instead of HTTP’s location-
based system. An HTTP request would look like
http://10.20.30.40/folder/file.txt

An IPFS request would look like


/ipfs/QmT5NvUtoM5n/folder/file.txt

Instead of using a location address, IPFS uses a representation of


the content itself to address the content. This is done using a
cryptographic hash on a file and that is used as the address. The
hash represents a root object and other objects can be found in its
path. Instead of talking to a server, you gain access to this
“starting point” of data. This way the system leverages physical
proximity. If someone very close to me has what I want, I’ll get it
directly from them instead of connecting to a central server. In the
lecture example from earlier, the students in the classroom can
pull the data from each other without all having to establish their
own communication with the server. With HTTP you are asking
what is at a certain location whereas with IPFS you are asking
where a certain file is. To accomplish this, IPFS synthesizes a few
successful ideas from other peer-to-peer systems.

146
Introduction to Blockchain Technology

To store data, IPFS uses a Distributed Hash Table, or DHT. Once


we have a hash, we ask the peer network who has the content
located at that hash and we download the content directly from
the node that has the data I want. Data is transferred between the
nodes in the network using mechanisms similar to BitTorrent. A
user looking for some content on the IPFS web finds neighbours
who have access to that content. They then download small bits of
the content from those neighbours. On top of the DHT and the
BitTorrent protocols, IPFS uses a Merkle Tree. This is a data
structure similar to the one Git uses as a version control system
and the protocol used in the bitcoin blockchain. In Git, it's used to
track versions of source code, whereas in IPFS it’s used to track
content across the entire web.

IPFS and Blockchains

Because of the similarity in their structure, IPFS and blockchains


can work well together. In fact, Juan Benet, the inventor of IPFS
calls this a “great marriage.” IPFS is one of a few projects that are
part of a group called Protocol Labs, which was also founded by
Benet. Some projects from Protocol Labs closely related to IPFS
are IPLD (Inter-Planetary Linked Data) and Filecoin. IPLD is a data
model for distributed data structures like blockchains. This model
allows for easy storage and access of blockchain data through IPFS.
Users willing to store IPFS data will be rewarded with Filecoin.
IPLD allows users to seamlessly interact with multiple blockchains
and has been integrated with Ethereum and Bitcoin.

Tech Stack Involved

React — Front end library

Solidity — The language used to build smart contracts that run on


Ethereum

147
Introduction to Blockchain Technology

IPFS — Decentralized storage

Infura —API access to Ethereum network and IPFS

Dependencies:

The following dependencies are required to create a react-app:

First of all, install node.js. Follow this link to install node.js


Node.js. Install the following dependencies.

npm i create-react-app
npm install react-bootstrap
npm install fs-extra
npm install ipfs-api
npm install web3
npm install @babel/core @babel/register --save-dev
Download code from the following link and keep the file on the
Desktop:
https://drive.google.com/drive/folders/1UCXQQENuX8RJsf7AOgei
CUvNHhGuJY9B?usp=sharing

Open Terminal or command line interface and change the


directory as follows

~ % cd Desktop

Desktop % cd Lab12
Install all dependencies using the following command:

$ npm install

Install Ganache ( https://www.trufflesuite.com/ganache)

Command to install the Ganache

npm install -g ganache-cli


148
Introduction to Blockchain Technology

Install Truffle suite :

$npm install truffle -g

Migrate all the contracts in the project to the local network:

$ truffle migrate

If the above command does not work, use the following command:

$ npx truffle migrate

Get metamask for the browser: (MetaMask)

Run the following command to start the project:

$npm run start

149
Introduction to Blockchain Technology

CHAPTER 8
BLOCKCHAIN IN IOT

Nowadays, the Internet of Things (IoT) has attracted interest from


academics and entrepreneurs thanks to their tremendous ability to
provide innovative services through various applications [1]. IoT
seamlessly interconnects heterogeneous devices and objects to
create a physical system in which sensing, processing, and
communication are automatically controlled without human
intervention [2]. With the advent of smart homes, smart cities, and
other intelligent things, IoT has become a field of immense
influence, opportunity and development with Cisco Inc.
anticipating 50 billion connected devices by 2020[3]. The Wireless
Sensor Networks (WSNs) and Machine- to-Machine (M2M) or
Cyber-Physical Systems (CPS) have now emerged in the research
literature as indispensable elements for the broader term IoT.
Consequently, security concerns relating to WSN, M2M, or CPS
arise in IoT with the standard network IP protocol. The entire
application infrastructure must be protected against attacks that
can obstruct IoT services as well as endanger data protection,
privacy, or confidentiality.

Blockchain first successfully applied in cryptocurrencies has


potentially emerged to be a highly secure and privacy-preserving
technology in IoT applications [4, 5]. Blockchain (BC) refers to a
decentralized, tamper-proof, and transactional database that
provides a secure way to store and process information across
many network participants [6]. In current settings, large quantities
of data produced from large numbers of IoT devices may

150
Introduction to Blockchain Technology

bottleneck the IoT system, resulting in a poor quality of service


(QoS) [7].

A single point of failure refers to a part of a system that can


interrupt the whole network from running if it crashes, which is
undesirable in any system with a goal of high availability or
reliability [8]. The peer-to-peer network of the Blockchain is seen
as a possible solution to problems with a single point of failure and
bottleneck [9, 10]. The adoption of Blockchain in IoT might be
adequate means to securely and efficiently store and process IoT
data [6].

Blockchain technology has evolved as an important remedy for


eliminating trust in conventional authorities or more broadly,
online intermediaries, as BC supposedly removes the need for trust
amongst entities. In BC technology, participants are subject to
authority of a technological mechanism rather than using
authority of a centralized organization that is often perceived to
be untrustworthy. Filippi et al. [11] made a point that Blockchain-
based systems are intended to create trust in a particular system,
not by entirely removing trust, but rather by maximizing the
degree of confidence between participants as a means of indirectly
reducing the need for trust. BC al- lows a circle of trust between
independent parties who do not agree to rely on a single third-
party trust. This confidence or trust can be achieved more readily
because of technical arrangements, particularly open-source
software which indicates that to the extent, the code of a specific
piece of software can be open, the possible outcome can be more
readily predicted theoretically. Therefore, the higher predictability
of the software code, the greater belief in the system and the lower
need for faith in that technical system’s developers or operators.
For instance, anybody can study the open Bitcoin protocol. As a

151
Introduction to Blockchain Technology

result, this assures participants that the network will produce a


certain number of new Bitcoins (12.5 bitcoins) at a particular
speed (one Block per 10 minutes) when a miner wins in Proof of
Work without relying on any financial institution or a centralized
authority. Therefore, BC technology makes participants believe
that no one needs to be trusted, and none can pretend to be a
trusted party, as no one exists in the BC [12].

However, the integration of Blockchain and IoT with the restricted


power and storage re- sources, are challenged by the structure of
Blockchain that involves high computational costs and delay [13].
The challenges while handling IoT data on the Blockchain are
depicted in Figure 8.1 and summarized below.

Figure 8.1: The challenges of adopting Blockchain in IoT

• The trade-off between power consumption,


performance, and security: The high computational
power required to run Blockchain algorithms has slowed
down the advancement of these technology-based
applications on resource constrained devices. For instance,
Bitcoin’s energy consumption was compared with the
domestic power consumption of Ireland, which IoT devices
cannot undertake [14]. Zhou et al. [9] reported that the
entire Bitcoin network absorbs considerably more energy
than several nations, including Austria and Colombia. In

152
Introduction to Blockchain Technology

addition, researchers have questioned the performance of


Blockchain to process IoT data and suggested optimizing
its central algorithms to increase the number of confirmed
Blocks per second [7]. Elimination of Blockchain Proof of
Work (PoW) consensus mechanism can reduce the power
consumption and improve performances [15]. But, PoW
helps prevents malicious, Sybil attacks and makes the
Blocks tamper-proof. Consequently, the goal is to refine
Blockchain processes to appropriately align security and
efficiency [8].
• Data concurrency and throughput issue [7]: In IoT
systems, the IoT devices continuously stream data which
results in high concurrency [16]. The Blockchain
throughput is limited thanks to its complex cryptographic
security protocol and consensus mechanisms. The rapid
synchronization of new Blocks among BC nodes in a chain-
structured ledger requires a higher amount of bandwidth,
which can improve BC throughput [9, 17]. Therefore, the
challenge is to boost Blockchain’s throughput to meet the
need of frequent transactions in IoT systems.
• Connectivity challenges of IoT [18]: The IoT devices are
expected to be connected to high computing storage and
networking resources to share IoT data with potential
stakeholders. The IoT has limited capabilities to connect
them with BC technology to provide novel business
opportunities for the implementation of new applications
and services in various domains.
• Handling Big data on the Blockchain: In the Blockchain
network, every participant maintains a local copy of the
complete distributed ledger. Upon the confirmation of a
new Block, the Block is broadcast throughout the entire

153
Introduction to Blockchain Technology

peer-to-peer network, and every node appends the


confirmed Block to their local ledger. While this
decentralized storage structure improves efficiency, solves
the bottleneck problem, and removes the need for third-
party trust [19], the management of IoT data on the
Blockchain puts a burden on participants’ storage space.
The study in [20] calculated that a Blockchain node would
need approximately 730 GB of data storage per year if 1000
participants exchange a single 2 MB image per day in a
Blockchain application. Therefore, the challenge is to
address the increasing data storage requirements when
Blockchain deals with IoT data.
• Challenges in maintaining both transparency and
privacy: Blockchain can guarantee the transparency of the
transactions, which is essential in some applications like
finance. However, user’s confidentiality may be adversely
affected when storing and accessing IoT data from certain
IoT systems such as eHealth on the BC [21]. To maintain a
balanced degree of transparency and privacy, the
development of cost-effective access control for IoT using
Blockchain is necessary.
• Regulating challenges of BC in IoT: While several BC
technological features including decentralization,
immutability, anonymity, and automation are promising
security solutions for diverse IoT applications, these
features combinedly pose various new regulatory
challenges [22]. The immutability feature implies that data
is permanently published in DLT (decentralized ledger
technology) on the peer-to-peer network and cannot be
deleted or modified. In addition, due to the absence of
governance, records cannot be filtered for maintaining

154
Introduction to Blockchain Technology

privacy before publishing them on the BC. Actions


resulting from executing code such as smart contracts on a
DLT can breach law. Due to the anonymity of the DLT, it is
not so straightforward to distinguish the parties carrying
out transactions for illegal services. Whilst the automation
feature of the BC brings many advantages, the actors that
cause some behaviors including errors in code and
obfuscating code are ambiguous. Current IoT laws and
regulations are becoming outdated especially with the
advent of new disruptive technology such as Blockchain
and need to be revised to undertake the DLT [23].

To deal with the challenges mentioned above, Uddin et al. enabled


low power, resource constrained IoT devices to securely transmit
and access their data to a customized Blockchain managed storage
system. To achieve this, a smart Agent is introduced to connect
low-profiled IoT devices with a peer-to-peer Blockchain network
where the Agent performs the following important tasks: 1) decide
repositories for permanently storing IoT data, 2) implement access
control on the Blockchain and, 3) manage the mining process on
behalf of the IoT devices. The software Agent adopts the
customized Blockchain to provide users with a decentralized
trustless network for processing IoT data, and a distributed storage
for selective kinds of IoT data. Furthermore, the Agent makes
secure communication between IoT devices and Blockchain and
regulates the Blockchain’s consensus mechanism to minimize
power consumption and improve the Blockchain’s throughput.

155
Introduction to Blockchain Technology

A PCA Managed Blockchain Based IoT eHealth


Framework

Blockchain technologies bring several attractive benefits to


eHealth such as decentralized, tamper- proof management of
health data without the oversight of a third party. However, the
integration of Blockchain with body area sensors raises many
issues:

• designing scalable eHealth framework


• unbalanced processing rate between the sensors’ data
streaming and Blockchain miners
• patient’s privacy concerns due to the transparent nature of
Blockchain
• Blockchain’s incapacity to accommodate a large volume of
data
• sensor’s limited processing and storage capacities to
execute Blockchain security and mining algorithms.

To meet these challenges, in this chapter, we introduced a Patient-


Centric Agent that is a software agent running on dedicated
hardware to connect Body Area Sensor Networks with a Blockchain
peer to peer network. The Patient-Centric Agent incorporates
three significant mod- ules: medical data management, Blockchain
mining management and security management. Each of these
modules includes different sub-services based on the patient’s
needs and preferences. Previous studies that attempted to
integrate IoT with Blockchain technology suggested a smart
Gateway to coordinate the IoT ecosystem on behalf of users.
However, a Gateway service is limited in managing security for IoT
devices. In contrast, our Patient-Centric Agent is envisaged to
manage health data, multiple Blockchains and patient privacy and

156
Introduction to Blockchain Technology

security. The Patient-Centric Agent organizes transactions into


Blocks which increases throughput in the Blockchain and re- duces
the number of transactions propagating in the Blockchain
network. We advanced an End-to-End secure eHealth framework
with the inclusion of the Patient-Centric Agent that bridges the
gap between Body Area Sensor Networks and a customized
Blockchain. Our main contributions include the following design
elements:

1. We designed a two-tier End to End secure eHealth


architecture (depicted in Figure 8.2) where the upper layer
deals with administrative activities, and the lower layer
handles data streaming and storage. The upper layer
contains the HCU (Healthcare Control Unit) that produces
public parameters and cryptographic keys for healthcare
professionals. The HCU handles legitimate complaints
against users and healthcare professionals. The HCU
reveals a target user’s identity and bans him or her. The
HCU’s function does not conflict with the Blockchain as it
only serves to initialize parameters and disclose healthcare
professionals’ identity.
2. In the lower layer, we developed a lightweight
authentication protocol for establishing secure
communication between different components of the
eHealth system including the Patient- Centric Agent,
Blockchain and body area sensors. The key features of the
protocol include dynamic key generation and the
integration of proximity authentication with a lightweight
HMAC (Hash MAC). The advantage of using dynamic key is
that in future, an attacker will not be able to hack
communication channels repeatedly using the same key.
The justification for using Hash-based proximity

157
Introduction to Blockchain Technology

authentication is that a malicious device may not hack a


patient’s device due to its geographical locations.
Furthermore, Hash-based authentication consumes lower
power, making it ideal for IoT devices. The Patient Centric
Agent also incorporates a Hash oriented role-based access
control mechanism. The PCA makes separate lightweight
secret symmetric keys for producing ciphertext of data on
every Block. To provide healthcare providers with access to
patient’s data, the PCA creates an access grant transaction
which includes an access control code and access grant
expiration time. As a result, a healthcare provider cannot
gain access to a patient’s data for an indefinite time once
the healthcare provider obtains patient’s secret key.
Furthermore, additional security and data anonymity is
ensured because patient’s data on each Block is encrypted
using a distinct secret key. The flow diagram illustrated in
Figure 8.1 presents the communication protocol described
above.
3. We customized a private Blockchain with the aid of the
Patient-Centric Agent to facilitate health data on the
Blockchain and optimize Blockchain in terms of power
consumption. The Blockchain is customized in the
following ways.
a) The Patient-Centric Agent governs the mining
process by selecting a group of miners to compete
to add a Block whereas conventional consensus
algorithms allow all miners to compete. A key
feature of the selection algorithm includes a hybrid
consensus algorithm that integrates Proof of Work
and Proof of Stake approaches with a measure of
the miner’s reputation in the form of trust. With

158
Introduction to Blockchain Technology

respect to energy consumption and processing time,


this approach can substantially increase efficiency
over the traditional consensus mechanism.
However, because a single Miner is responsible for
computing the target hash code of a Block, the
consensus mechanism is vulnerable to cyberattacks
such as Sybil attack, single point of failure, and
selfish mining attacks. To avoid these attacks, a set
of potential Miners first are nominated using Proof
of Stake and Proof of Capacity. Second, the Miners’
rating is estimated using Miners’ trust value.
Finally, a secretary algorithm selects a Miner based
on Miners’ rating to perform Proof of Work. The
Proof of Stake entails that every Miner must deposit
certain amount to participate in validating Block.
So, a Miner found to be malicious will lose its
deposit which prevents them from engaging in
selfish mining. The trust value is estimated based
on a range of Miner’s properties including their
avail- ability, mining rate, processing capacities,
previous records regarding their honesty etc. This
trust value can filter malicious Miners. The most
fitted Miner is discovered based on rating using
secretary hiring algorithm which provides some
degree of randomness. As a result, the same Miner
has very little chance to be repeatedly elected.
Given the adversarial chosen candidates, the
secretary hiring algorithm [325] is a technique to
maximize the likelihood of finding the best miner
candidate in a randomly selected order.

159
Introduction to Blockchain Technology

Health Data

Yes New dynamic key generation


Key Validation Time
Expire? without exchanging control
packet
No

Perform Authentication using


Proximity and HMAC

Yes Generate Hash based data


Authentication is encryption key using patient's
Successful? public key, transaction identifier and
timestamp
No

Report to Patient Centric Define rule based access control


Agent and make access grant transaction

End

Figure 8.1: The communication protocol of the proposed IoT


healthcare system

b) The Blockchain is further modified using a Tri tree


instead of a Merkle tree to pack the transactions
into the Block more efficiently. The Tri tree
structure allows data retrieval faster than Merkle
tree. At the same time, the Tri tree can serve the
purpose of Merkle tree which generates a single
hash code as a root to be inserted into the Block’s
header so that the Block does not need to hold the
entire contents while being propagated throughout
BC peer to peer network.
c) The incorporation of a secure payment protocol
where the Patient Centric Agent and Miners have an
account with traditional banks to purchase virtual
credits using conventional currency. The payment
protocol improves the system ’s sustainability.

Finally, the performances of the fundamental algorithms in the


framework were analyzed by designing a private Blockchain using
simulators. The high-level view of the IoT eHealth framework is
illustrated in Figure 8.2. The architecture presented in Figure 8.2
160
Introduction to Blockchain Technology

includes the Patient- Centric Agent between Sensor Data


Processing component in the patient end and Blockchain. The PCA
has three main features: Data Management Module (DMM) to
decide the storage medium of health data, Miner Management
Module (MMM) to control and manage a customized Blockchain
and Security Service Module (SSM) to perform authentication,
control access, and generate dynamic security keys.

Figure 8.2: The high-level view of the PCA managed IoT eHealth
Architecture.

161
Introduction to Blockchain Technology

The PCA Managed Decentralized IoT eHealth


Framework

The limitation of the work presented in the previous chapter is


that the Patient-Centric Agent (PCA) is vulnerable to single point
of failure (SPF) and Denial of Service (DoS) attack due to its
centralized architecture. The eHealth architecture includes the
PCA which executes on dedicated hardware and participates in
administrating a portion of a customized Blockchain. As a result, if
the PCA is down, the patient's data will not be recorded in the
Blockchain (BC) because the PCA captures sensor's streaming data
for transmitting the data to the Blockchain.

The potential safeguard against most cyberattacks is to develop a


fault tolerant PCA enabled eHealth system. Faults tolerance refers
to a system's ability to continue its service without interruption
even if one or more devices or software module fails. A system can
be made fault-tolerant by installing multiple hardware or
replicating system instances in various devices so that a backup
instance of the entire system can be resumed while DoS or SPF
attacks disrupt services of the current instance.

Recent technologies such as Fog and Cloud have enhanced the


capabilities of the smartphone by accomplishing its heavyweight
services. Therefore, instances of eHealth app can be deployed not
only on a smartphone but also on Fog and Cloud, which can
enhance the reliability and availability of such a system. Instead of
saving information to the local drive on a single device, most
current IoT applications store information on multiple servers in
Cloud which is a standard virtualized storage and processing
system maintained by third party.

162
Introduction to Blockchain Technology

However, the current Cloud system is not designed for meeting all
requirements of IoT data including volume, variety, and velocity of
data. Every day, billions of interconnected IoT devices generate
more than two exabytes of data. Transferring all IoT data to the
Cloud takes huge quantities of bandwidth. Instead of sending vast
amounts of IoT data to the Cloud, the most time-sensitive data
can be analyzed at the network edge, near the user’s devices where
data is generated. The selected data that requires historical
analysis and longer-term storage can be transmitted to the Cloud.

The concept of Fog computing was coined by Cisco in 2014 that


describes the decentralization of the infrastructure of computing
or bringing the Cloud resources to user’s devices rather than data
being transmitted to a Cloud data center. Fog computing and edge
computing, both often termed interchangeably are concerned with
exploiting computational resources within a local network to
perform computing tasks close to user’s devices. The Fog
networking comprises control plane and data plane which
facilitates computing resources at the edge of the network. The
Fog nodes extending features of Cloud servers can be mounted
anywhere such as on a factory floor, on top of a power pole, next
to a railroad track, in a truck, or on an oil rig. The Fog node can be
any devices including industrial controllers, switches, routers,
embedded servers, and cameras for video surveillance processing,
storage, and network access. Fog computing offers a range of
benefits, such as speeding up event response by avoiding a round
trip, expensive bandwidth to discharge data to the Cloud, and
preserving confidential IoT data by analyzing it inside the
company / user network.

To merge Fog and Cloud technologies with Blockchain


technologies, in this chapter, a decentralized Blockchain leveraged

163
Introduction to Blockchain Technology

eHealth system is proposed where the main innovation involves


multiple instances of a Patient-Centric Agent each hosted at
multiple layers including smartphone, Fog and the Cloud. The
instance of the PCA with all functionalities in a layer can
automatically resume its service if a cyberattack stops the main
instance of the PCA.

Replicating Patient Centric Agent in different layers rather than


installing an independent program in each of those layers has
benefits. Replicated instances can ensure trustworthy, secure,
privacy preserving and reliable communication channels among
them while processing patient data. If one of the PCAs in a layer is
under cyberattack, other PCA can take over the role of the
compromised instance without sacrificing a patient’s privacy
because replicated instances update their states at a certain time
interval. The PCA in a layer can monitor and analyze requests from
other replicated PCAs of other layers. One of the replicated PCA in
each layer acting as master PCA can activate other instances of
PCA in that layer if the master PCA experiences flood of responses
from malicious nodes or other PCAs of higher or lower layer.

Fault tolerance refers to a process of leveraging and handling


redundancy. The redundancy relates to more resources to
accomplish a task than minimal resource to do the task at hand.
During failure of a system, redundant resources are exploited to
retain normal operations of the system, thereby preserving the
desired level of functionality. Four ways of redundancy exist:
hardware, software, information, and time. Redundancy of
hardware allows additional hardware to be inserted into the design
to either detect or circumvent the effects of a failed device.
Software redundancy refers to the development of several software
instances such that if there are failures in some significant part of

164
Introduction to Blockchain Technology

the software or down because of cyberattacks, new instances can


be mounted. Our concept of replicating PCA in various layers and
devices covers redundancy in both hardware and software, which
offers fault tolerance capabilities for the system.

Although this contributes to fault tolerance, this architecture


raises an issue about how multiple PCAs manage the Blockchain to
record and process patient data and at which layer the Blockchain
can be deployed for its maximum efficiency. Fog or Cloud
technologies are regarded as an ideal platform to facilitate a
distributed peer to peer network for BC technologies. However,
both technologies involve several issues while implementing BC
with the Internet of Things. The Cloud with virtually unlimited
storage and processing capacities experiences an excessive delay
in responding to patient's queries.

In contrast, the Fog, which is called an extension of Cloud brings


virtual resources close to its affiliated hosts to provide users with
the rapid response of their queries. However, unlike Cloud, the Fog
devices are attributed with limited processing and memory
capacities which are challenged to run most of the
computationally intensive BC consensus protocol and cannot
support BC storage. In fact, the BC technologies involve multiple
independent operations including structuring transactions, and
Block, generating cryptographic keys, executing consensus
protocols, and storing confirmed Blocks on a peer-to-peer
network. These BC operations demand a high level of
computational, storage and network resources. To address the
issues of BC while adopting it in Fog and Cloud, the instances of
PCA at different layers are allocated parts of Blockchain
operations depending on the layer's processing and storage
capacities. For instance, the PCA on the smartphone can define

165
Introduction to Blockchain Technology

transactions, Blocks, and security keys, the PCA on the Fog can
execute the consensus protocol for rapid outcomes related to
Blocks and the PCA on the Cloud permanently stores patient data.
The BC nodes require the consensus protocol to confirm and insert
a Block into a decentralized ledger. The standard consensus
mechanism such as Proof of Work (PoW) which is the most
decentralized protocol needs excessive computational resources
and experiences lower throughput when it is applied to the Fog
network.

The Patient-Centric Agent introduced in the previous chapter is


shown to minimize energy consumption and increase the
throughput of the Blockchain by modifying the Proof of Work
consensus mechanism and the structure of Block. However, the
Proof of Work consensus protocol cannot execute on Fog level
devices due to their high processing power requirements and
excessive Block's confirmation latency. Researchers have
suggested Practical Byzantine Fault Tolerance (pBFT), PoS, DPoS
and other variations of PoS. However, standard PoS and DPoS have
limitations, such as nothing at stakes and long-range attacks.
Further, these protocols work in a flat network where nodes'
variation in terms of processing and storage is reduced, making
them unsuitable for IoT deployment.

In contrast, the Fog network comprises of hierarchical


heterogeneous low profiling devices including router, switch,
modem that widely vary in the level of processing and memory
capacities. Therefore, the standard PoS protocol does not fit in the
Fog network. Considering these facts, we incorporated a
lightweight consensus mechanism for Fog devices which is a Fuzzy
Inference System (FIS) assisted modified Proof of Stake consensus
mechanism in the proposed eHealth architecture.

166
Introduction to Blockchain Technology

Since the PCA deployed at multiple layers is hosted by the devices


which are equipped with various levels of processing and memory
capacities, an instance of the PCA can be overloaded by medical
tasks. A PCA needs to offload tasks to a host with spare computing
resources available to enhance the quality of service in the entire
system. The preservation of a patient's privacy is challenged while
outsourcing tasks to foreign Fog devices in the distributed Fog
network because Fog devices are usually manufactured by
heterogeneous stakeholders and maintained by third parties.
Therefore, there needs to design the privacy-preserving tasks
offloading algorithm for the Fog network. To address the task
offloading issue, a Blockchain leveraged privacy-preserving task
migration which assigns the tasks to different Fog and Cloud
devices based on the task's sensitivity was designed for a PCA. In
this process, Blockchain helps to avoid third parties while
processing a task and ensure a tamper-free execution
environment.

As mentioned earlier, the Patient-Centric Agent on each layer can


outsource its task to other nodes having available resources. The
tasks on health data may include a broad range of services
including data compression, filtration, cleaning, billing, key
management, mining, and data analytics related processing etc.
The existing state-of-the-art works in task offloading considered
all tasks as similar same category and designed task migration
algorithm accordingly. However, tasks on health data vary in the
level of sensitivity with respect to privacy, time and energy
required.

To bridge this gap, in the proposed task offloading algorithm, the


tasks are classified as Privacy Sensitive or Normal Task. Each of
these types is further categorized as Time Sensitive or Energy

167
Introduction to Blockchain Technology

Sensitive tasks. Privacy Sensitive tasks are scheduled among the


homogeneous Patient-Centric Agent at different layers to ensure
patient's privacy and security. Other two kinds of tasks are
outsourced to heterogenous PCA using a Hungarian optimization
algorithm. The tasks that are performed on sensitive medical data
such as pregnancy, sexual orientation data are defined as privacy-
sensitive tasks. The reason for classifying the tasks before
outsourcing to remote/foreign Agents is to preserve a patient's
privacy and optimize the migration process with respect to either
power consumption or processing time. Exchanging a patient's
sensitive medical data with a remote/foreign Agent might risk the
patient's privacy. So, the privacy-sensitive tasks of a patient are
outsourced to its Agents in the three layers. For other kinds of
tasks, two different matrices called time matrix for delay-sensitive
tasks and energy matrix for energy sensitive tasks are estimated,
and then an optimization algorithm is applied on them separately
whereas existing methods formed a single equation or matrix by
combining time and energy parameter to compromise both
parameters. For instance, real-time surgery, and cardiovascular
monitoring patient requires a network with ultra-low latency as a
rapid response of these tasks is important in the eHealth system.
So, optimizing the scheduling of these tasks with respect to only
time is preferable and results in a better outcome. The last issue of
designing an efficient task offloading algorithm is important,
which is to securely collect and maintain execution environment
and performance parameters of remote devices. A PCA needs to
know performance parameters of foreign agents including CPU
processing rate, memory capacities, location, and network
bandwidth to decide which tasks to offload to other agents.

Foreign devices may not accurately convey their performance


parameters to a Patient Agent intentionally or not. To address

168
Introduction to Blockchain Technology

this issue, every PCA records their execution and performance


parameters in the BC ledger and updates their execution
parameters at a certain interval. The miner nodes verify a remote
agent's performance parameters using a special transaction on the
Blockchain. Hence, a foreign agent cannot pretend to be a device
with high computing resources. Our Blockchain-based
decentralized architecture depicted in Figure 8.3 comprises three
layers explained below:

Figure 8.3: High-level view of decentralized eHealth framework

1. The Sensing layer includes body area sensors and


smartphone. The devices in this layer sense data and
perform pre-processing on the data before transmitting
those to higher layers. The instance of PCA on the
smartphone plays the role of coordinating and controlling
other instances placed in Fog and Cloud layers. The
smartphone Agent acting as a master agent nominates an
agent from each layer to monitor the activities of other
instances and reports abnormalities of any instances to the
master agent.
2. The NEAR processing layer consists of Edge servers, which
are at one hop from the sensing devices. The devices in the

169
Introduction to Blockchain Technology

NEAR processing layer are organized hierarchically. The


entire network is divided into several clusters, and one
leader or cluster head is elected from each cluster based on
several nodes' attributes using a Fuzzy Inference Process
(FIS). The FIS makes a set of fuzzy rules using several
nodes’ features including include a node's trust value,
performances, and stake to nominate a leader from each
cluster. The leaders from each cluster participate in
collecting and validating transactions produced in its
subnetwork. A super leader is randomly chosen from the
list of nominated leaders to make a Block, and the node
remains active for a certain period or makes a certain
number of Blocks. The lead nodes from each cluster verify
and validate a Block to be included in the ledger running
the upper layer.
The consensus mechanism is designed to address the
shortcomings of the standard Proof of Stake consensus
protocol. The proposed consensus protocol applies cluster-
based transactions validation process. As a result, nodes
from the entire network do not require to utilize their
bandwidth to verify transactions which increases
throughput. In standard PoS, miners are selected from the
whole network based on the nodes' stake amount. As a
result, a particular group of nodes can collude and might
repeatedly win mining, whereas our modified PoS allows
only one miner from each cluster which prevents BC nodes
from colluding and makes the protocol more decentralized
than the standard PoS. Further, in the proposed PoS,
authorities in private or consortium Blockchain can change
or set new fuzzy rules as well rule's attribute for selecting
miner nodes overtime. The modified Proof of Stake
methods utilized Fuzzy Logic System which is flexible and

170
Introduction to Blockchain Technology

allows the rules to be changed. Such system can accept


imprecise, skewed, and mistaken input data.
3. The FAR processing layer consists of Cloud servers.
Multiple Cloud servers from the same providers or different
providers form a peer-to-peer network to maintain the
Blockchain ledger. The Cloud servers store health data on
the Blockchain ledger and perform heavyweight tasks.

According to Figure 8.3, the Patient-Centric Agent is replicated at


the above three layers with extended features. Each layer can
contain more than one replica of the same Patient-Centric Agent
to increase the fault tolerance of the system. In addition, we
discussed how the Patient Agent could fit on the 5G network to
serve various medical services. To secure the framework, each
replica of the Patient-Centric Agent shares a data encryption key
using Shamir's Secret Sharing (SSS) and utilizes Ring Signature to
preserve their privacy.

Shamir's Secret Sharing (SSS)[1] protects a secret key/password in


a distributed manner where the secret key is divided into different
parts and distributed among multiple entities. A certain number
of such shares are required to recreate the original secret key.
Similarly, in the proposed eHealth system, a patient's secret key is
split into multiple parts, and each part is distributed among the
instances of Patient-Centric Agent deployed in each layer.
Consequently, no single PCA is in possession of the hidden key. If
a replicated Agent is subject to cyberattacks, the compromised
agent cannot take control over other instances of PCA because the
attacker needs to compromise other instances too to reconstruct
the secret key. Therefore, this approach can preserve the privacy of
replicated homogenous Patient-Centric Agents (copy of the same
Patient Agent) at each layer.

171
Introduction to Blockchain Technology

Most Blockchains like Bitcoin or Ethereum generate a digital


signature for endorsing transactions using PKI (public/private key
infrastructure) where an owner's transactions are signed by his or
her private key. Although PKI can ensure some degree of
anonymity for the owner, a malicious attacker can discover the
owner's identity because all the owner's transactions are being
endorsed using the same set of PKIs. However, a ring signature is
considered as a potential solution to this problem in research.

A ring signature is a form of creating an anonymous digital


signature that can be generated by any member of a group. Any
individuals of the group can also endorse the message signed with
a ring signature. The significant feature of the ring signature is
that malicious attackers cannot decide which member's key is used
to produce the signature. Hence, the ring signature is suitable for
ensuring the anonymity of replicated Patient-Centric Agents. The
replicated PCA at different layers form a group for endorsing the
ring signature.

One of the replicated PCA builds ring signatures on the patient's


transactions. The digital signature also contains other agents'
public key. Therefore, other PCAs outside this group cannot
discover who belongs to the transaction and the digital signature (
A foreign agent cannot parse the digital signature to find which
member’s public key is in the signature to discover the owner
agent’s private key). Figure 8.4 presented the functionalities of the
Patient-Centric Agent replicated at three layers. The PCA has four
main modules: Data Management Module (DMM), Blockchain
Management Module (BMM), Task Migration Module (TMM) and
Security Service Module (SSM). The DMM handles pre-processing
of sensors' data and determines the health data storage
repositories. The BMM performs Blockchain-related operations

172
Introduction to Blockchain Technology

such as mining, building, and endorsing transactions. The TMM


decides to migrate patient's tasks and choose remote/foreign
agents for outsourcing tasks if necessary. The SSM encrypts or
decrypts patient's data, produces digital signature and update
security key.

Finally, the performance of the framework is analyzed by


simulating the key algorithms using Java Programming. The
security protocols are simulated on Scyther tools[2] to measure
their strengths against cyberattacks.

Figure 8. 4: The functionalities of blockchain leveraged eHealth


system

Replicating Patient Centric Agent in different layers rather than


installing an independent program in each of those layers has
benefits. Replicated instances can ensure trustworthy, secure,
privacy preserving and reliable communication channels among
them while processing patient data. If one of the PCAs in a layer is
under cyberattack, other PCA can take over the role of the
compromised instance without sacrificing a patient’s privacy
because replicated instances update their states at a certain time
interval.

173
Introduction to Blockchain Technology

The PCA in a layer can monitor and analyze requests from other
replicated PCAs of other layers. One of the replicated PCA in each
layer acting as master PCA can activate other instances of PCA in
that layer if the master PCA experiences flood of responses from
malicious nodes or other PCAs of higher or lower layer. The
existing state-of-the-art works in task offloading considered all
tasks as similar same category and designed task migration
algorithm accordingly. However, tasks on health data vary in the
level of sensitivity with respect to privacy, time and energy
required.

The PCA Managed Framework for Underwater IoT


Monitoring

we have investigated the Patient-Centric Agent to manage and


control data in BC eHealth. The autonomous nature of an agent
and higher security and privacy providing BC technology in
eHealth applications have motivated us to adopt both technologies
in other IoT applications such as underwater IoT, smart home or
cities. The Internet of Things has evolved well in autonomous
fields such as aquaculture, submarine communication, and
underwater monitoring. Also, seafood and fish are in high demand
so maintaining the quality and security of aquatic products is
important. Emerging technologies like Blockchain (BC) are being
undertaken for advancing and monitoring submarine sensor
networks. Blockchain technologies can provide new ways of
gathering information from underwater IoT sensors and
guaranteeing the quality of the products without the requirements
for third parties.

In this chapter, we describe a framework of underwater IoT


monitoring that adopted smart Gateway Agents to supervise the

174
Introduction to Blockchain Technology

underwater Internet of Things network. From the architectural


point of view, the framework comprises the three layers:
Underwater Internet of Things layer, Edge Network Layer and
Cloud Network Layer, each described below.

1. Underwater Internet of Things layer consists of sensors


deployed at a different level of an underwater
environment. A level based hierarchical routing protocol
using a minimum number of encrypted control packets was
devised. The entire monitoring area is divided into sub-
areas, each called a grid that has a cluster head. All cluster
heads in the under- water network accommodate a
lightweight Blockchain for managing control key, updating
firmware, storing sensor nodes’ identifier, and log
information. Cluster heads are responsible for forwarding
the data packet from the source to the destination based on
the level inserted into data packet. The cluster head
authorizes its member nodes and maintains the privacy of
its member nodes using Bloom filter. A Bloom filter refers
to a probabilistic data structure containing a list of
pseudonymous identifiers or elements in memory
efficiently. The filter is designed to rapidly tell whether an
element is present in the list or not. The Blockchain on the
Underwater Internet of Things does not store data and
execute lightweight consensus protocol due to limited
power, and memory capacities of IoT nodes. Preferably, all
cluster heads hosting BC verify and certify transactions
related to log information, security key and node’s identity
to add these transactions in their local BC ledger. The BC
on the cluster heads of Internet of Things layer has twofold
merits. The malicious nodes cannot forge the identifier of a
registered node. Further, communication flights can be

175
Introduction to Blockchain Technology

reduced to perform the node’s authentication when a


sensor node moves to a new cluster head because the
cluster head can retrieve necessary information regarding
the node from its BC ledger.
2. The Edge layer nodes are at one hop away from the surface
nodes of IoUT. The Edge layer houses multiple smart
Agents owned by users and different stakeholders to
receive under- water sensors data and transmit the data to
the Cloud Blockchain. The intelligent Agent on the Edge
authorizes the cluster heads in the Underwater Internet of
Things layer. Further, the smart Agent affiliated with
stakeholders governs the mining process on the Cloud
Blockchain. In addition, the intelligent Agent selects a
group of healthy miners based on their attributes using the
TOPSIS method for Proof of Stake consensus mechanism.
The significance of using TOPSIS method is that it can
generate balanced rating for Miners, considering the
weight of each rating attribute. State-of-the-art works
linearly combined several attributes to pick Miners for
processing transactions and Blocks. However, not all
selection attributes, including the reputation, stake,
processing, storage and network capabilities of a miner,
carry equal significance. For instance, the mining fee of a
miner is two or three times important than that of the
processing rate for a use case. On the other hand, for
different use cases such as firmware update, the reputation
of a miner is more important than that of its mining fee.
The TOPSIS method allows the system to assign the weight
for each attribute and rank the miners by the combined
rating of their attributes considering diverse use cases.

176
Introduction to Blockchain Technology

3. The Cloud layer hosts the second Blockchain for


maintaining the data ledger. The Cloud Blockchain
provides the cluster heads in the IoUT layer with the
security key and firmware updates via smart Agent placed
in the Edge nodes. The Cloud servers perform processing
and support permanent storage for IoT data. In this IoUT
framework, we described two use cases of IoUT data
processing on the Blockchain network. One of the use cases
is to detect anoma- lies from IoT data where a group of
Miners selected using TOPSIS method trains a machine
learning algorithm and produces transactions with
accuracy level. Another group of Miners assesses the
outcome and offer rewards to the node producing higher
accuracy. The purpose of this use case is to utilize the
Blockchain platform for solving the user’s problem without
the need of third parties.

In Figure 8.5, a lightweight framework for underwater IoT


monitoring is presented. Two different peer-to-peer networks for
hosting Blockchain are formed on the Internet of Things layer and
Cloud layer respectively. On the Internet of Things layer, only
cluster heads accommodate a lightweight Blockchain for managing
security keys and routing protocol. In contrast, the Cloud servers
maintain a distributed ledger for storing sensor’s data and other
information including node’s firmware, customers’ identities etc.
The smart Gateway Agent placed in the Fog network bridges the
two different Blockchain networks. We examined the performance
of the proposed framework with Proof of Stake consensus
algorithm with respect to two use cases. The security and privacy
of the framework are also analyzed in terms of known security
attacks.

177
Introduction to Blockchain Technology

Figure 8.5: The multilayer BC architecture for IoUT monitoring.

178
Introduction to Blockchain Technology

Exercise

1. Write down the role of blockchain in ensuring security and


privacy in IoT.
2. What are the challenges to adopt blockchain in controlling
and managing IoT?
3. Describe use cases of blockchain and IoT applications in
addressing privacy and security challenges.
4. How can IoT agent address the challenges of merging
blockchain technology with IoT?
5. How can you incorporate blockchain technology in MEC
(Medium Access Edge Computing)?

References
[1] D. C. Nguyen, P. N. Pathirana, M. Ding, and A. Seneviratne, “Integration of
blockchain and cloud of things: Architecture, applications and challenges,” arXiv
preprint arXiv:1908.09058, 2019.

[2] S. S. Panda, U. Satapathy, B. K. Mohanta, D. Jena, and D. Gountia, “A


blockchain based de- centralized authentication framework for resource
constrained iot devices,” in 2019 10th In- ternational Conference on Computing,
Communication and Networking Technologies (IC- CCNT). IEEE, 2019, pp. 1–6.

[3] M. A. Khan and K. Salah, “Iot security: Review, blockchain solutions, and open
challenges,”

Future Generation Computer Systems, vol. 82, pp. 395–411, 2018.

[4] N. Siegfried, T. Rosenthal, A. Benlian et al., “Blockchain and the industrial


internet of things: A requirement taxonomy and systematic fit analysis,”

179
Introduction to Blockchain Technology

Darmstadt Technical Univer- sity, Department of Business Administration . . . ,


Tech. Rep., 2020.

[5] R. A. Michelin, A. Dorri, M. Steger, R. C. Lunardi, S. S. Kanhere, R. Jurdak, and


A. F. Zorzo, “Speedychain: A framework for decoupling data from blockchain for
smart cities,” in Proceedings of the 15th EAI International Conference on Mobile
and Ubiquitous Systems: Computing, Networking and Services, 2018, pp. 145–
154.

[6] Y. Yu, Y. Li, J. Tian, and J. Liu, “Blockchain-based solutions to security and
privacy issues in the internet of things,” IEEE Wireless Communications, vol. 25,
no. 6, pp. 12–18, 2018.

[7] A. Panarello, N. Tapas, G. Merlino, F. Longo, and A. Puliafito, “Blockchain and


iot integra- tion: A systematic survey,” Sensors, vol. 18, no. 8, p. 2575, 2018.

[8] J. Huang, L. Kong, G. Chen, M.-Y. Wu, X. Liu, and P. Zeng, “Towards secure
industrial iot: Blockchain system with credit-based consensus mechanism,” IEEE
Transactions on Industrial Informatics, vol. 15, no. 6, pp. 3680–3689, 2019.

[9] Q. Zhou, H. Huang, Z. Zheng, and J. Bian, “Solutions to scalability of


blockchain: A sur- vey,” IEEE Access, vol. 8, pp. 16 440–16 455, 2020.

[10] P. P. Ray, D. Dash, K. Salah, and N. Kumar, “Blockchain for iot-based


healthcare: Back- ground, consensus, platforms, and use cases,” IEEE Systems
Journal, 2020.

[11] P. De Filippi, M. Mannan, and W. Reijers, “Blockchain as a confidence


machine: The prob- lem of trust & challenges of governance,” Technology in
Society, vol. 62, p. 101284, 2020.

[12] A. Antonopoulos, “Bitcoin security model: trust by computation,” O’Reilly


Radar. Re- trieved October, vol. 4, p. 2015, 2014.

[13] K. R. O¨ zyılmaz and A. Yurdakul, “Work-in-progress: integrating low-power


iot devices to a blockchain-based infrastructure,” in 2017 International
Conference on Embedded Software (EMSOFT). IEEE, 2017, pp. 1–2.

[14] K. J. O’Dwyer and D. Malone, “Bitcoin mining and its energy footprint,” 2014.

180
Introduction to Blockchain Technology

[15] M. A. Uddin, A. Stranieri, I. Gondal, and V. Balasubramanian, “An efficient


selective miner consensus protocol in blockchain oriented iot smart monitoring.”
in ICIT, 2019, pp. 1135– 1142.

[16] P. K. Sharma, N. Kumar, and J. H. Park, “Blockchain technology toward green


iot: Oppor- tunities and challenges,” IEEE Network, 2020.

[17] A. D. Dwivedi, L. Malina, P. Dzurenda, and G. Srivastava, “Optimized


blockchain model for internet of things based healthcare applications,” in 2019
42nd International Conference on Telecommunications and Signal Processing
(TSP). IEEE, 2019, pp. 135–139.

[18] H. F. Atlam and G. B. Wills, “Technical aspects of blockchain and iot,” in


Advances in Computers. Elsevier, 2019, vol. 115, pp. 1–39.

[19] E. Karafiloski and A. Mishev, “Blockchain solutions for big data challenges: A
literature review,” in IEEE EUROCON 2017-17th International Conference on
Smart Technologies. IEEE, 2017, pp. 763–768.

[20] “Blockchain issues: 1: Data storage, retrieved from


https://medium.com/@kyle.may/blockchain-issues-1-data-storage.”

[21] T. Yu, X. Wang, and Y. Zhu, “Blockchain technology for the 5g-enabled
internet of things systems: Principle, applications and challenges,” 5G-Enabled
Internet of Things, 2019.

[22] J. Ellul, J. Galea, M. Ganado, S. Mccarthy, and G. J. Pace, “Regulating


blockchain, dlt and smart contracts: a technology regulator’s perspective,” in ERA
Forum, vol. 21, no. 2. Springer, 2020, pp. 209–220.

[23] A. Reyna, C. Mart´ın, J. Chen, E. Soler, and M. D´ıaz, “On blockchain and its
integration with iot. challenges and opportunities,” Future Generation Computer
Systems, vol. 88, pp. 173–190, 2018.

181

You might also like