0% found this document useful (0 votes)
181 views193 pages

BCT Techknowledge

This document provides an introduction to blockchain technology. It discusses key concepts such as: 1. The origin and evolution of blockchain from cryptographic hash functions and Merkle trees. 2. The components that make up blockchain including blocks, nodes, ledgers, wallets, hashes, and consensus protocols. 3. The differences between traditional and blockchain transactions including their peer-to-peer nature, use of asymmetric cryptography, and distributed consensus.

Uploaded by

ks9465207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views193 pages

BCT Techknowledge

This document provides an introduction to blockchain technology. It discusses key concepts such as: 1. The origin and evolution of blockchain from cryptographic hash functions and Merkle trees. 2. The components that make up blockchain including blocks, nodes, ledgers, wallets, hashes, and consensus protocols. 3. The differences between traditional and blockchain transactions including their peer-to-peer nature, use of asymmetric cryptography, and distributed consensus.

Uploaded by

ks9465207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 193

Blockchain(MU) Tableof Contents

Module

Chapter 1: Introduction To Blockchain 1-1to 1-27


syfllabus:
1.1 What is a blockchain, Origin of blockchain (cryptographically secure hash functions), Foundation of
Merkle trees
blockchain
1.2 Components of blockchain, Block in blockchain, Types: Public, Private, and Consortium, Consensus Protocol,
Limitations and Challenges of biockchain
1.1 Introduction. 1-1
e*******

1.2 Origin of Blockchain.*****e one**osos** oeosss***eo* e*******o******e******a***** 1-1

1.2.1 What is Blockchain?. *******s********


********** 1-2

1.2.2 Blockchain and Bitcoin. soouusovnun


***** 1-2

1.2.3 Blockchain Evolution. ********** oeoso*.


* * * * * ** * * * 1-2

1.2.4 Blockchain Generations.. *. ********************* 1-3

1.3 Blockchain Solution.s******e**secseoseeeoseeee****************sessssess********ess***. ******************asnaanenses

(131/ Traditional vs. Blockchain Transactions..

1.3.2 Peer-to-Peer Network..***********************************nses********* .. 1-4

1.3.3 Asymmetric Cryptography.. ********"********************************************usursso************cao* 5


1.3.4 Distributed Consensu...******************************************************************************************a******a**a************enannpoea*************** *. 5

14 Foundation of Block chain : Merkle Trees... ********** **************e***************anaaaeaae*ao*****eo******esesese 1-7

1.4.1 Advantages of Merkle Tree.*****************************************************************anensmsone****************************************************************nsroseose***** 1-9

15 Components of Blockchain. **** ******e**********


2
******aeseseeenss****aee
1-99

1.5.1 Node ***********************"***********************************************************************************************************ae*********************************a****. 1-9

(152 Ledger or Database.****************'***************************************************************************************************************************************s*******.


. .1-10

1.5.3 Wallet. *******************************************************"*******************"******"***************************************a*******************************e*sauose**************. 1-10

1.5.4 Nonce.*********************"""*********'*****°****************" ** *****"*****"***********************"************************* ******************..1-10

1.5.5 Hash.************************************************************ **** * * *** ********************************************************************************.1-11

1.5.6 Mining **** * "******"'*****"****************"************* *********************************************************************************************************. .1-11

1.5.7 Consensus Protocol..


********" *** ** *******************

.1-12
************************************************************ ****.

1.6 What is Block in


Blockchain?. e*******e******. a******
*******
1-12

1.6.1 Block in Blockchain. ****************** ****************** ******************************************" . 12


Tech Kaouledge
Blockchain (MU) Table of Contents
Steps in Blockchain Transaction..
**************************o********************** *******'**************************************esse .s......
1.6.2 ********************************ees.,
..1-13
1.6.3 Double Spending.. ******************************************************************************** ********* *******************.
...-13

1.7 Blockchain Layers.. **********°******°°°.


o * * ° * * * * ° * ° °°*°Te******°****

************°° °*°*°*°°°°°7****°°9****
"1-13

A.8 Types of Blockchain.********** e****************e********e********e*************************eeeoo*o*eo*******e********eeseo***ee* aed

1.8.1 Public Blockchain. *************


**************************************** ..1-15
*ssenpeness**********************************************************************ssso.

1.8.2 Private Blockchain.. ********************************e*****************************************snsse.


******************************************.

.1-16
*******************************

1.8.3 Consortium Blockchain. . *************nneseee**************************************************************************************.


.1-16
1.8.4 Hybrid Blockchain..
***********e********************************************************************************"***********
*****************"***********************nssni,
17

1.8.5 Comparison between Public, Private and Consortium Blockchain. o****** *********************************** 17

1.9 Consensus Protocol..****************e****************e*******es*******e************0 **** **°*e°°°°°*°°O°***** 1-18

1.9.1 Byzantine Generals Problem..


*******o*******e***************** ************** ********************** * -19

1.9.2 Objectives of Consensus Protocol.. ******************************"****** *******************.


.19

1.9.3 Consensus Algorithms. **********************e***************e***************** **************************************************************************.


-20

1.9.4 Other Consensus Mechanisms..* **********************************************************************************************************************n u1-22

1.10 Limitations and Challenges of Blockchain. **************°************** **°°*°°**°*****°****°**°*****°*°°e°****°****°*e**°**°e******e*****


M123
1.11 The Benefits of Blockchain Technology...
**eesee*oeesee***co****°eo****°e************** 2.1-25
Module lI

Chapter 2: Cryptocurrency 2-1 to 2-34

Syllabus:
2.1 Cryptocurrency: Bitcoin, Altcoin, and Tokens (Utility and Security)., Cryptocurrency wallets: Hot and cold wallets
Cryptocurrency usage, Transactions in Blockchain, UTXO and double spending problem.

2.2 Bitcoin blockchain : Consensus in Bitcoin, Proof-of-Work (Pow), Proof-of-Burn (PoB), Proof-of-Stake (Po), and
Proof-of-ElapsedTime (PoED, Life ofaminer, Mining difficulty,Mining pool andits methods
2.1 Introduction... 2-1
*************************************************************************************************oeeeossssoao*sesseeeen**seees* eonneesessesad

2.2 Bitcoin..*********************** . .2-1

2.3 Cryptocurrency Basics.****************o********** *****°*°°°°°***°°°**°°*****°°*°**°°°****°**°°°*

2.3.1 Forking. * ***********************************************************************


********************************
a***

2.3.2 Characteristics of Cryptocurrencies.. " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *


2******
23

2.4 Cryptocurrency Wallets.. ***********************


eeseeaaseaa*

2.5 Types of Cryptocurrency... 2-6


************

Tech Kuouled
L t i e
Blockchain (MU) Table of Contents
2.5.1 Altcoins.. **************************************************************** *************************
**********************************
-7

2.5.2 Tokens... *********************


************************************************************************************************** .2-7

2.5.3 Popular Coins and Tokens .


******** **..2-10

2.6 Cryptocurrency Usage. 2-12

2.6.1 Ecosystem Players . . .2-12


*******************************************************************************

2.6.2 Cryptomining. **********************************e********************* ***************.G ..2-13

(26.3 Airdrop *********


******e* **********************************************. *******eesenme********************.
2-14

2.6.4 Tokens or Coin Burning. ..2-16


**********************************************************************************

2.6.5 Investing and Trading..


*****.*************************. ***
**********.2-16
Cryptocurrency Safety. ********************************* *************e******************
. .2-17
2.7 Transactions in Blockchain. eeooe******ooo**0eoo**o ********* **eee* *eeeeeee ****ee**°**°**°e*****e*****°***°e0*°° 2-18

2.8 UTXO and Double 2-20


ng...o*o*o***oo********************* *************e** **e***************e***************

2.9 Bitcoin Blockchain... e******e******.*******e**************e**************.e*****ee** ******aeseeo* 2-21

2.10 Consensus in Bitcoin..


***°***** *°°°**°°°°°*°°*°. ********************e******.*************.****°******o******e****Toi*** . 2-23

2.11 Proof-of-Burn (PoB).. ****


************* ***°°9 ************o******o****°°e***°*. 2-26

2.12 Proof-of-Stake (PoS). . e***e****** -27


e********p******e*******e

21 Proof of Elapsed Time (PoET).. eo********e**oooooeoe*********eo********************* *****°*******°*****°*°*° .2-28

2.14/Life of a Miner..
*****.eo*****eeeeco**ee*s****o*e***ee*****eee****. *******************ee***oeesnoeaesosseasass***esansoosacoosenesseaaaaeeaseeseessaaaasesae.2-29

15 Mining Difficulty. eeeeceeeeaeseeeeeseeeeeseeeee *****°°**** ************esaeeeeeeeeae**eeeee* 2-29

2.16/ Mining Pool and its Methods..


****o*****eeo***eo******e*****°e*******eees***e*******o*****eeeoaeeeneeeseeee*ee. ************ 30

Module ll

Chapter 3: Programming for Bilockchain 3-1 to 3-45


Syllabus
3.1 Introduction to Smart Contracts, Types of Smart Contracts, Structure of a Smart Contract, Smart Contract
Approaches, Limitations of Smart Contracts.
3.2 Introduction to Programming: Solidity Programming Basics, functions, Visibility and Activity Qualifiers, Address
and Address Payable, Bytes and Enums, Arrays-Fixed and Dynamic Arrays, Special Arrays-Bytes and strings, Struct,
Mapping, Inheritance, Error handling
3.3 Case Study- Voting Contract App, Preparingfor smart contractdevelopment
3.1
Introduction to Smart Contracts.. sssussnssssseeeeseososesesssssaaneeaeaseaaesssoneseaaanaaasoosssssssessss*** oosossssssssssesvoreeasssan eaas 3
3.2 Types of Smart Contracts. ..**soensoeoeeo*****************************************a*oooesne*asessnennea******eoeceeeeneeeeseeeseeense*s*nsnnee.3-3

Tech Kaouledge
4 Table of Contents
Blockchain (MU)
3.3 Structure of a Smart Contract.
********************e***************************°*********** **°° °o°
*******************s*

.3-5
***
*3-10
********°***°°****°***°******°°**°°***°°**

3.4 Types of Oracles. * * * * * * * * * * * *

*******so*****************************************e..

3.5 Benefits and Limitations of


Smart Contracts.. ***o************
3-10
S o l i d i t y P r o g r a m m i n g
* *.* .
* * * * * * * e * * * * * * * * * * * * * * * e * * * * * * * * * * * * * * * * * * * * * * *
aneerososessoeeoeeeee********e**oo*****eeasessesee.ok
3.6
* * * * * * * * * * * * * * * * * * * * * * * * * * *

..*******************************************e.3-11
3.6.1 Basics ****

3.6.2 Data Types...


***********************************************************
12

** -13
Variables..
** *********************************************
3.6.3
************ ******

Variable Scope.. ****************************. * * * * * * * * * * * * * * * * *

-16
3.6.4

Arrays: Fixed and Dynamic Arrays... **** **********ussawe rs 3-19


3.6.5 ********** ***** ******

************************
22
Special Arrays: Bytes and Strings.
********

3.6.6 *************"******"******

3.6.7 Enums.. *********


************************************
*****************************
.3-23

3.6.8 Structs...
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * .
**************"**** .3-23

.3-24
3.69 Mapping ***********
*************************
*****************************.

3.6.10 Functions. ***********°******* **** **** ************************** .3-27

3.6.11 Visibility and Activity Qualifiers.. ***************°*°°*****°'**°****°** **'* ***


3-28

3.6.12 Solidity Contracts and Constructors... *********** ** ***********"********


.3-31

3.6.13 Inheritance in Solidity.************"********************


. ******************* **********
.3-33
* * * * * * * * * * * * * * * * * *

3.6.14 Solidity Error Handling. ****************************************"**************************e************************sso*************e***.


*********************"** .3-34

3.7 Case Study: Voting Contract App. ****


3-35
3.8 Preparing for Smart Contract Development...
e******s*****°***°*°****°*°eooo***eo*****ee***°* *************** ****eeeeeaee*****
3-39

Module IVV

Chapter 4: Public Blockchain 4-1 to 4-35

Syllabus Introduction to Public Blockchain, Ethereum and its


Components, Mining in Ethereum, Ethereum
rtual
v
Machine(EVM), Transaction, Accounts, Architecture and workflow,
Comparison between Bitcoin and Ethereum.
Types of test-networks used in Ethereum, Transferring Ethers using Metamask, Mist Wallet, Case
Ethereum frameworks,
study of Ganache for Ethereum Blockchain, Exploring etherscan.io, and
ether block structure.
4.1 Introduction to Public Blockchain.. **e*******ee******
********************e*****************************************e********.
4.2
Ethereum...enneesesean*********. ****************************************************************.********* * ******e********************°
4-2

4.3 Ethereum Components.***********************e***********************************e*************eo************.**************e******e************ ***ee****


4-3

4.4 Mining in Ethereum. *******s**************************************** ****e***********.************************************


. 4-5
E E l e c h K n o w l e d g e
Blockchain (MU) Table of Contents
Ethereum Virtual Machine (EVM) ....
4.5 **************************sssnssssannn .ssss * *nosssasenssoesaoasssaaanassoaaaneensn 4-6
Transaction and Accounts...
4.6 ***************°*°*******************e*********4********e*************eo* *****2*********e***********
4-7

4.6.1 Transaction. *************"""'************** *a*** ********************************'****************


4-7

4.6.2 Accounts. ***** *** ******* * *************************************


,4-9

4.7 Architecture and Workflow ...


*************************************ssoessessseeeses**sssssesescsesseneree**oseesseeeesseeesssseesseosssd 11

Comparison between Bitcoin and Ethereum..************************e*******


2.4-14
***********ae*******************

49 Types of test-networks used in Ethereum.


********************************** * * * * * ** * *
****** ******* 4-15

410 Transferring Ethers using Metamask.. -17

4.11 Mist Wallet.. ****


**********************eeo*************e****************************************** -24

412 Ethereum Frameworks..**************************e**************e************** ***** ****


4-24

413 Case study of Ganache for Ethereum Blockchain... ******e***e*** * -28

4.14 Exploring Etherscan.io, and Ether Block Structure.eeeeeee*******. ***************


*e**a****oceceeeesoeescsscseoresee 4 . -30

4.14.1 Etherscan.io. ********************* ****

*****************************.***********a * n* ******************* .
********************************* 4-30)

4.14.2 Ether Block Structure... ****************************°*****"*******************"**"***************************** *********" .4-34

Module V

Chapter 5: Private Blockchain 5-1 to 5-31


Syllabus: Introduction, Key characteristics, Need of Private Blockchain, Smart Contract in a Private Environment, State
Machine Replication, Consensus Algorithms for Private Blockchain PAXOS and RAFT, Byzantine Faults: Byzantine Fault
Tolerant( BFT and Practical BFT

Introduction to Hyperledger, Tools and Frameworks, Hyperledger Fabric, Comparison between Hyperledger Fabric & Other
Technologies
Hyperledger Fabric Architecture, Components of Hyperledger Fabric: MSP, Chain Codes, Transaction Flow, Working of

Hyperledger Fabric, Creating Hyperledger Network,Case Study ofSupply Chain ManagementusingHyperledger


5.1
Introduction. *******.
**esece ******* 5-1

5.2 Key Characteristics. .neeneseeencenee********n******e*********e**e************************e**e*e**ae*********eeeesneeee********aeneenenaeo 5-1

5.3 Need of Private Blockchain **************************e**********" **ae*********4**********°°** *s***eaae* *aa* *********** 5-2

5A
Smart Cotract in a Private Environment. ********
*** 2..5-2
************°

5.5 Sute Machine 2


Replication *********
* * * * * * * e * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

***************************

5.6 onsensus Algorithms for Private Blockchain -PAXOS and RAFT. 5-5

561 PAXOS Consensus Algorithm.. 5-5

Tech Kaowledge
Blockchain (MU) 6
Table of Contents
5.6.2 RAFT ******* ************************************************ *** *****eeaee****
** ********************************a**e.

S-8
5.7 Byzantine Faults : Byzantine Fault Tolerant (BFT) and Practical BFT.
******.***s. 5-9
5.7.1 Byzantine Fault Tolerant (BFT)..
******** .5-9
5.7.2 Practical BFT. *************
e************************************************************************a* ************e**s*-ess.n.
12

5.8 Introduction to Hyperledger *******ee*

* 5-14
5.9 Tools and Frameworks .
******e«s.
5-14
5.9.1 Hyperledger Frameworks...******************************a******************************************************************°*****************************e******s*.s.s. . ********.
.5-14
5.9.2 Hyperledger Tools... *****e*********
*********eeeto**ese**************** ***************************************************************************************so**na..
.S-15

5.10 Hyperledger Fabric.. *eeeeeeeeeeeeeeeen.


******e*******
5-15

5.11 Comparison between Hyperledger Fabric & Other Technologies ** 5-16


5.12 Hyperledger Fabric Architecture.. "5-17
5.14 Working of Hyperledger Fabric..
-.5-22
5.15 Creating Hyperledger Network.
5-23
5.16 Case Study of Supply Chain Management using Hyperledger. -..5-27

Module VI

Chapter 6: Tools and Applicatlons In Blockchaln


6-1 to 6-15
: :

Syllabus: Corda, Ripple, Quorum and other Emerging Blockchain Platforms, Blockchain in DeFi: Case Study on any of
theBlockchain Platforms.
6.1 Corda. seseeeeeeeeeess
6-1
6.2 Ripple. 6-3
6.3 Quorum.
6-5
6.4 Emerging Blockchain Platforms.. 6-8

6.5 Blockchain in DeFi: Case


Study on any of the Blockchain Platforms... .611
PROGRAMMING FOR
3
MODULE- 3
BLOCKCHAIN

Syllabus
Introduction to Smart Contracts, Types of Smart Contracts, Structure of a Smart Contract, Smas
3.1

Approaches, Limitations of Smart Contracts.

3.2 introduction to Programming: Solidity Programming Basics, functions, Visibility and Activity Qualit
Address and Address Payable, Bytes and Enums, Arrays-Fixed and Dynamic Arrays, Special Arays-8ytesa
and
strings, Struct, Mapping, Inheritance, Error handling.

3.3 Case Study-Voting Contract App, Preparing for smart contract development

3.1 Introduction to Smart Contracts


A Smart Contract or cryptocontract is a code that automatically controls the transfer of digital assets between the
different parties under certain conditions. The functioning of the smart contract is similar to the traditional contra
while also automatically enforcing the contract. Smart contracts code performs exactly specified work in ther
implementation. Hence, smart contracts are enforceable by code. On the contrary, traditional contract s
enforceable by law.
In the year 1994, Nick Szabo, a legal scholar and a cryptographer, known the application of decentralized ledge
for smart contracts. He realized that, these contracts could be programmed and code can be stored and replicate
on the nodes and administered by the network of computers that constitute the blockchain. These smart contrat

could also offer the transfer of digital assets between the parties under certain conditions.
1. Definition of Smart Contract

The smart contract is the software program implementing a set of rules or conditions and operates on the top
blockchain. These set of rules are used by different parties to that smart contract to transfer the digital as
between them.
2. Smart Contract
nteract
Based on set of rules implemented in smart contracts, different parties to the smart contracts agree to
mart

with each other. This agreement automatically gets executed after fulfilling the pre-defined rules. Ine
nd t
contract code ease, validate and ensure the transaction or agreement. Hence, they are fully automate
is possible to automate the records of real-life agreements related to purchase and sale of assets.
that
A smart contract implements security coding of the blockchain and include details and permi at
e
require a precise sequence of events to happen to trigger the agreement of the terms stated
tract
contract. It can also comprise the time constraints that can enforce the deadlines in the contract.
is embedded in the blockchain and hence, it is transparent, immutable, inexpensive and decentraEG zed.
Blockchain (MU) 3-2 Programming for Blockchain

All the smart contracts are with their address in the blockchain. The contract address is used to interact with
the contract by presuming that it has been broadcasted to all the participant nodes.

The set of rules of the smart contract is coded at protocol level or application level. This ensures to reduce
transaction cost related to the following.

o Reaching the agreement as rules on which agreement is based are pre-defined.

New agreements among the people, institutions and about asset they hold can be formalized by
implementing them in the form of software code.
Agreements are enforced automatically as per rule/conditions implemented are met.

Today, there are so many organizations that are offering services to their consumers. These organizations are
with centralized control. Smart contracts now provide the opportunities for innovation to be caried out in
business where interactions are directly between the different business entities or end users of the business.
There is no need to have third party involvement in this peer-to-peer interaction. There are several critical
areas where smart contract can play the key role to ensure the better trust compared to its traditional
counterpart related to predefined agreement.

Following are the benefits of smart contracts.

o Real-time updates are supported and they are simple and faster.

o They eliminate the mediator and other centralized entities.

Cost effective by saving cost of paying to mediator.

o As they execute automatically, there is no delay in producing expected and agreed outcome.

3. Smart Contract Example


If John wants to purchase piece of lands from other Smith, then there are so many government agencies
works as trusted third parties in this purchase deal. These agencies are land revenue office, government
registrar's office, local authorities in combination with lawyer's office and land brokers etc. These third parties

play role in verification and authentication of land document.


f all these concerned authorities and government agencies are on the blockchain, then all the rules or
conditions of valid sale could be implemented in smart contract. If the John want to buy land in 40000 USD
using smart contract in blockchain, then the transaction would be validated/verified by all the members in
blockchain. In this verification, nodes in network verifies whether the Smith is real owner ofthe land anddall
the government taxes are clear, encumbrance is valid and the John has a credentials to buy the land.

if the blockchain network confirms that all the conditions are met, John automatically gets access code to the
land document. Land gets transferred to his name and Smith's account is added with 40000 USD without

involvemet of any intermediatory.


All the nodes in blockchain network, could check whether person is real owner of the land. They also check the
seller's and buyer's identity and security records.
4. How Smart Contract Works
All the smart contracts are with their address in the blockchain. The contract address is used to interact with
the contract by presuming that it has been broadcasted to all the participant nodes. The smat contracts are
implemented on blockchain where logic for validation is kept inside the block. Also, block contains the

messages needed for smart contract.

Tech neuledge
Blockchain (MU) 3-3 Programming for Blockh
Participant in permissionless
blockchain
Blockchain
who want to participate in smart contract can dowr
also generates private key
for the particinanOPenwnload open-sourte
software and publish its public key.
wants to carry out smart
contract transaction
on the related ledger, then softws àdress. f the
software sends
participant
message (encrypted with its private key) to other
active participants. initiat
nodes having private key.
Other participants with public k
This message is signed by venty te
content. If more than 50%%
nodes in public biockchs
transaction and authenticate the message
added in blockchain. Most ofthe time smart contracts
has to access reach the
consensus the message
browser.
external use
or applications through web
Characteristics of a Smart Contract
5.
transactions is carried out by smart contracts. It also
also contributes i
tracking of performance and
co.
Real-time
"information oracles" are used which providar
the overall cost. For external information,
imexterma
saving
through web browser interaction. Following are some of the
information to smart contracts portant
characteristics of the smart contracts.

verify and execute itself and are tamper resistant. As it is develm


Independence Smart contracts can
eloped
by individual node, authorization is not dependent
on an agent, notary or other third parties Han.
Hence
legal transactions that defines nule and
tampering by any intermediator not possible. They
automate

conditions and also offers high security.


Cost Effective There is no need to have trusted intermediatory in any sell or purchase deal and hence

having lower transaction costs.


o Trustfulness: As transactions are encoded and encrypted on a distributed replicated ledger, No one can
announce that it has been lost.

Recovery and Backup: It is possible as same copies are available on multiple nodes

O
Protection: Addresses are encrypted and hence contracts are well-preserved and prevented from an
malicious activities.

O
Agility: All the business-related activities to be carried out are done/executed automatically.
Truth based Accuracy: There is no intervention of human and smart contracts gets execu
automatically. Hence, operation is error free.

3.2 Types of Smart Contracts


Following are the categories of smart contracts using natural language for encoding9
The contracts which are entirely in code
Contracts embedded in code using distinct version of the natural language.
"Split natural language contract with encoded performance. offered

The contracts with encoded payment scheme. Encoding is in natural language. Here, the automation re use

Smart contracts can be used in many industries with several benefits. The different domains where cturing

are: banking, health, finance, insurance, energy, e-governance, media, telecommunication, educato
and many other domains. The smart contracts can be classified into 4 types on the basis of application
Smart legal Contracts 2. Distributed Applications (DAppS
3. Decentralized Autonomous Organizations (DAO) 4. Smart Contracting Devices (SCD)
Publafo"
ech
Blockchain (MU) 3-4
Programming for Blockchain

1. Smart Legal Contracts


These are the most common type of smart contracts. They are with legal contract templates. They involve

legal requirements such as mutual agreement which expresses a valid offer and acceptance, acceptable
consideration, capacity and legality. These requirements are similar to their traditional counterpart.
These are created to hold concerned parties responsible for fulfiling their end of an agreement. When set up
correctly, a smart contract is lawfully enforceable and requires the parties to fulfil their duties. If parties fail to
fulfill obligations in the contract then a legal action is triggered by the smart contract automatically against
the party that is in breach.

The laws and its contexts are different in different countries. Hence, they lack adequate support for smart and
automated contracts on the blockchain and their legal status is unclear. However, once the laws are created,
smart contracts can be created to ease processes which presently involve strict regulatory oversight such as
transactions in the financial and real estate market, government subsidies, international trade erc

2. Decentralized Applications (DApps)


Smart contracts and DApps are closely related with each other. DApps interacts with the blockchain and
controls the state of all network members. Smart contracts demonstrate the core logic of a decentralized app
DApps have unlimited number of members or participants in market.

The user iterface (U) of DApps is similar to a typical website or mobile application. DApps front end
represent the user's interaction, and its back end is implemented for all business logic. The business logic of
DApps is depicted by one or more smart contracts communicating with the underlying technology of

blockchain
3. Decentralized Autonomous Organizations (DAO)

DAO are the communities that exist on the blockchain. These communities can be defined by a set of
stipulatory rules which are implemented via smart contracts. Every participant and their actions are bound by
the community's rules with the task of imposing these rules. These rules are constituted from many smart
contracts and collaborate to watch over activities in the community.

The Genesis DAO was created by Ethereum members in May 2016. The main aim of community was for
crowdfunding and as a venture capital platform. In an unexpectedly short time, they succeeded to raise an
astonishing $150 milion. However, hackers got some loopholes in the system and succeeded to steal about
s50 milion dllars' worth of Ethers from the crowdfund investors. The hack and its consequences resulted in a

fork of the Ethereum blockchain into Ethereum and Ethereum Classic.


So, DAO is the organization that is represented by logic implemented in transparent manner that is controlled
by shareholder community without any central authority. DAOs are sophisticated form of smart contracts.
There are some activities that needs manual intervention to execute certain tasks which cannot be executed

automatically. These activities are


Tokens: Tokens are used to reward certain activities which are funded directly upon creation of

organizations.
Autonomous The DAO code after deployment, cannot be controlled by its creator or any outsiders.

Hence, it is transparent and incorruptible.


Tech neuledge
Blockchain (MU) 3-5
Programming for Blocke
The number
Agreement: DAO's stakeholder should agree towithdraw or move funds. of ctakehoders t,
mentioned in DAO code.
agree is already
out product and hardware building,
Contractor: To elect contractor for carrying and.

voting of token holders is necessary. This is because, the DAO cannot perform these taske ing as we
tasks and
is appointed to achieve the gaols defined. contracto
Proposals: Used only for decision making in DAO. DAO need monetary deposit to
to avoid deposit
overloading because of many proposals from many people. This discourages people from e
people from networ
network. spamming t
Voting: Once the proposal is submitted, voting takes place. DAO permits participants to .
economic value with any person in global network without any intermediatory.

4 Smart Contracting Devices (SCD)

Internet of things (oT) in combination with the blockchain, talks about Application logic contacts (ALC w
contain an
application-based code that remains
in-step with other blockchain contracts. Thev all
whicn
communication across various devices and enable the allo
merging of the Internet ot Things (loT) with blockchas
technology. a .

ALCS are anessential piece of multi-function smart contract and


typically work under a managing
Such smart contracts
comprise application specific code that function in combination with progra
contracts and programs on the blockchain. other sman
They assist in communicating with and validating
between loT devices. communication

3.3 Structure of a Smart Contract

In Ethereum blockchain, transactions are


implemented via smart contract code, which is activated the data and
inputs from external account by
automatically. When external account triggers the smart
within the contract contract, the business log
gets executed and status of
ledger balances of all the accounts
updated on all the nodes in blockchain. gets updated. This is also ges
The data gets written on
all the nodes while
adjacent node. Hence, more efforts and writing
but during
reading, it is only in read only from the
resources are involved in nearest
Ethereum blockchain. writing and updating the informato n in
To pay the reward for this work, Gas
is native
currency of Ethereum concept is used. It is a conversion unit OT which
blockchain. ee
Smart Contract Messages to
Transaction other contracts
Externally Owned (Data,Value) Value Address (Data, Value)
Account (EDA)
State
Functions Events
A Fig.3.3.1: Basie Structure of Smart
smart contract contains the value, Contract
With this input address,
it
executes the corresponding functions, and state. The
input to the smart contract is transactio
program that resides on a code and
Blockchain and it has its triggers the output events. A smartcontrac software

unique address. contract

h n n l e g
Blockchain (MU) 3-6 Programmingfor Blockchain
Smart contract is identified by this unique address. A smart contract contains a set of executable functions and

state variables. The execution of the function happens when transactions are made to these functions. Ihe
transactions contain input parameters which are needed by the functions in the contract. When function executes,
the state variables in the contract changes depending on the logic implemented in the function.

Contracts are written in various high-level languages like Solidity or Python. Language-specific compilers are used
to compile the smart contract code into byte code. The compiled code of contracts is uploaded to the Blockchain
network which assigns unique addresses to the contracts. Any participarnt or member on the Blockchain network
can trigger the functions in the contract by sending transactions to the contract. The contract code runs on each
node participating in the network as part of the verification of new blocks. Figure 3.1 shows the structure of a
smart contract.

Structure of a Smart Contract in Ethereum

As stated above, a contract is like a class which contains state variables, functions, function modifiers, events,
structures, and enums. The inheritance and polymorphism are also supported by contract. Following is a very basic
smart contract structure overview written in Solidity language. The details about Solidity language is explained in
section 3.6

pragma solidity ^0.8.2;


contract Customer {
string id;
function setld(string serial) public {
id = serlal;

function getid0 public constant returns (string) {


return id;

Here pragma keyword, which is used to enable certain compiler features or checks; pragma indicates the version of
the solidity compiler that should be used to compile the current file. This way, an incompatible change introduced by a
future compiler version will be rejected. New versions of solidity are frequently released and some of them introduce

incompatible changes.
f the compilation fails, you need to check the compiler version, you are using.

Next is contract keyword and name of the contract. The contract source code is placed between a pair of curly
braces, The name of the contract will not be saved on the blockchain. At deployment, each contractor receives a unique

address that will uniquely identify the contract.


Each contract can contain declaration of state variables that will be saved on blockchain, functions, events.function

modifiers, structs, and enum types.


State Variables: State variables are stored in contract storage. These can be set as constants. Expensive to use,

they cost gas.

BE Technowledge
Blockchain (MU)
3-7 Programming for Blocke.
kchain
pragma solidity ^0.8.2;

contract myContract(
varlable unsigned integer type//.
uint myData://State
-

perform something within the contract.


Function: Punctions are like a
few lines of code that can

contract Customer {
string id = 34;

function getld) public constant returns (string) {// function


return id;

State variables values are permanently stored in contract storage.

Function getID) is a getter function, as it creates a call that returns the value of the state variable.

Function Modifiers: Function modifiers


the main function.
are similar to a function that checks the validation rules priortoexecuting
contract Purchase{
address public seller;

modifier onlySeller0 {// Modifier


require(msg.sender == seller);

function abort0 public


onlySeller {// Modifier usage

ere tunction modifier onlySeller) which changes the behavior of the function to which it is
example, it is applies to abort). appe
Struct Types: Struct is custom defined data
types that consists of several variables declared in
pragma solidity ^0.8.2;
contract Node {

struct caller {// Struct


uint id;

bool isEXists;
Blockchain (MU) 3-8 Programming for Blockchain
address delegate;

uint age:

>Events Events are functions that are bubbled up after compilation of function execution if event code written
there it provide EVM logging functionality.

pragma solidity ^0.8.2;


contract Auction {

event HighestBid (address user, uint amount); // Event

function bid0 public payable {

emit HighestBid (msg.sender, msg.value): // Triggering event

Enum Types: Enum is used to create custom types and it has fixed the set of values

pragma solidity ^0.8.2;


contract shoping {
enum KIT { cricket, hokey, table-tansis} // Enum

Structure of a Smart Contract in Ethereum

pragma solidity ^0.8.2;

import "browser/ERC20.sol";
contract MyFirstToken is ERC20 {

string public constant symbol "MFT";


=

uint8 public constant decimals = 18;

uint private constanttotalSupply = 1000;

=> uint)) private allowances;


mapping (address => mapping (address
function MyFirstToken(0{
balance0f|msg.sender)] =_totalSupply:

Tunction constant returns (uint_totalSupply) {


totalSupply(0
totalSupply = _totalSupply:
Be Tech lneuledge
Blockchain (MU)
ProgramminE
returns (uint balance) {
constant
balanceOffaddress_addr)

Tunction

return balanceOf|_addr};

success){
transfer(address_to,
uint_value) returns (bool
function
balance0f(msg.sender))
«=
if (value » 0 &&_value

balanceOffmsg.sender)= _value;
balanceOf[_ to] *= _value;
return true;

return false;

function transferFrom(address from, address to, uint_value) returns (bool success){


if(allowances[from][msg.sender)> 0&&
value>0 &&
allowances[from][msg.sender]>=value &&
balanceOf[ from]=_value) {
balance0f[Lfrom)=value;
balance0f[ to]+= value;
/Missed from the video
allowances[ from][msg.sender] -=
value;
return true;

return false;

function
approve{address _spender, uint _value)
allowances[msg.sender][Lspender) =value; returns (bool success)
return true;
Blockchain (MU) 3-10 Programming for Blockchain

3.4 Types of Oracles

Oracle is an agent that verifies off-chain occurrences and submit facts to a blockchain. For example, trustee agree
release fund if certain conditions are fulfilled. Then, to release any fund, oracle has to sign smart contract as well.
Following are the different types of oracles
Software Oracles: These oracles deal with information that is available over the internet. For example,
Temperature in city, delay in train arrival etc. Such data originates from online sources.

In this case,
Hardware
Oracles : some
smart contract directy receive input from physical devices such
sensors
It can be used for example, to track details of car passing particular cross junction or to track movement of trucks
as

carrying the goods.

Inbound and Outbound Oracles : Here, inbound oracles provide data from external world to smart contract and
outbound oracles permits the smart contract to send data to outside world.

Consensus-based Oracles: Prediction markets use more than one oracle to get consensus about future
outcomes. Majority of oracles will determine the outcome of the event

3.5 Benefits and Limitations of Smart Contracts

Following are the benefits and limitations of the smart contracts.

Benefits of Smart Contract

Organizations can make use of smat contracts to automate the contract lifecycle, improve collaboration, and
digitize their assets or transactions.
1 Security: Smart contracts support data encryption and its tampering is not possible. Hence, they are highly secure
alternative to paper-based contracts. Smart contracts can be used in financial institutions and government offices

due to high security.


2. Speed: Because of the automation of contract lifecycle process and the self-enforcement capability, Smart
contracts speed the process significantly. Automation of the contract lifecycle management (CLM) process makes it

less prone to human error.


3. Fewerlntermediaries: There's a reduced dependence on intermediaries for trust services.

and hence lower execution risk. Any alteration to


Transparency: Smart contracts guarantee highertransparency
4. a

the contract needs the mutual consent of the involved parties. There is no scope of manipulation or non

performance due to any individual.


of reduced dependence on intermediaries and
5. COst-Effective: Smart contracts are very cost-effective because
ease of storage.
5. multiple times copying of the documents
in blockchain, it ensures a secure digital
Digital backup: As there are

to the contract in the event of a loss.


ackup and easy accessibility
7. involvement. The data record is also distributed across the entire chain. Hence,
Trust: There is no any third-party
This ensures trust among all members of the contract.
changing the information for personal profit is challenging.
down efficiency lost to gaps in communication.
Communication: Smart contracts can drastically cut
on
Clear
Tech Kneuledge
Blockchain (MU)
3-11 Programming for Bloce.
Limitations of Smart Contracts
a few reasons to not. Followinn
to adopt smart contracts, there are are the few
reasons
While there are many of
smart contracts.
the
limitations of
challenges and
consider the law firms, the logic-based
execution is often them. CContract creaton
chalenging for them
1 Flexibility : If we like 'good faith' or 'reasonable" to hs
deliberate usage of terms
subjective element in it and has
has a
is when the parties want to create a relational contract
obligatory
rat
flexibility. This type of
contract
than a
In this situation, smart contracts fail
to offer utility.
transactional one.

intermediaries and lawyers, it's imperativetn.


contracts reduce dependence on
2. Legal Difficulties: Smart
criminal, and commercial law.
invotved
of the legal consequences of public, private,
parties to be aware
to be a nuisance rather than a ben
3. Delayed Transactions: There are
cases where technology proves benefit. The
lead to a delayed transaction and finally push transactional cost aho
bove the
congestion in a blockchain network can
cost incurred in traditional contracts.

mechanism that works withouthe


4. Inflexibility : Practically, smart contracts are a fully self-operating human
intervention after being deployed on a blockchain. However, the most of the commercial relationships are
very
complex in nature. Accounting for al likely contingencies and nuances in a contract is not possible both in write
ten
and digital agreements. Conventionally, parties believe on judicial assistance to help them resolve contracha
issues that are often imposed by unexpected circumstances. While this problem can't be totally eased regardlesd
the type of contract, smart contracts can automatically reference an external arbitrager when unanticipated facton

come into play.


5. Link to the real world: Many contractual agreements need some sort of a connection to the real wonld, whi
hinders the promise of smart contracts to be fully autonomous.
6. Speed and scalability: Smart contracts are deployed on blockchain platforms such as Ethereum. Hena
transaction processing speed depends on the blockchain. For example, Ethereum processes 13 transactionsp
second. This severely limits the number of transactions that the network can process in any given second.
7. Immutable : AS smart Contracts are tamper-proof, it can be difficult or impossible to fix the problemsthat occus
8. Technical challenges: To carry out the audit of smart contract, technical proficiency is necessary which fallss
t
in common investors and end-users. This lack of knowledge leads to foolish investment, which mightle3
insecure smart contracts, permitting hackers to steal millions of dollars.
9. Legal enforcement : any intermediatory involved in smart contracts. If a contract works
There are no
a
cts are
agreement, then the users do not have to go to court for settlement. In case of disagreements, thesecontraco
not legally enforceable in all countries.

3.6 Solidity Programming

3.6.1 Basics
t run on

Solidity is a statically-typed curly-braces programming language used for developing smart contrae idiy
the Ethereum Virtual Machine (EVM) which is the runtime
environment for smart contracts in Etnere chine

vastly influenced by C++, Python and JavaScript and has been designed Ethereum vir
to target the
(EVM). Solidity supports inheritance and libraries.
Frart Kno
Blockchain (MU) 3 12 Programming for Blockchain
Solidity language can be used to create contracts for
voting, crowdfunding, blind auctions, and multi-signature
wallets. Smart contract programs execute inside a peer-to-peer network where execution is not controlled by any
authority, and thus they permit to implement tokens of value, ownership, voting and other kinds of logics. For

deploying the contracts, the latest released version of


Solidity is the requirement.
The reason is, breaking changes along with the new features and bug fixes are introduced regularly. Presently, 0.x
version numbers are being used to specify the fast pace of change. Solidity was publicly introduced for the first
time in November 2014 at Devcon0. Solidity v0.1.0 turned 5 years old on July 8th 2020.
The Solidity programming language is an open-source, community project governed by a core team that is
sponsored by the Ethereum Foundation. The Ethereum blockchain platform runs smart contracts which are the
applications that run precisely as they are programmed.

The key "product" of the Solidity project is the Solidity compiler (solc). Solidity compilers convert solidity
programs
to EVM bytecode. The project also manages the important application binary interface (AB) standard for Ethereum
smart contracts.

Solidity is case sensitive.

.Everystatement must end with semicolon.


Most of the control structures are available: if, else, for, while, continue, break, return.
1 / represents a single line comment.
/ represents a multi-line comment.

3.6.2 Data Types

Following are the basic data types in Solidity.

Boolean (bool)

Boolean value is either true or false. Following are the logical operators used.

Operator Logical Meaning


not

&8& and

or

equal
not equal

Signed (int) and unsigned (uint) integers


These integers declared in increments of 8 bits from int8 to uint256. Without a size suffix, 256-bit quantities are
Used, to match the word size of the EVM.
Fixed point (fixed, ufixed)
Fixed-point numbers, declared with (ufixedMxN where M is the size in bits (increments of 8 up to 256) and N is
the number of decimals after the point (up to 18); e.g, ufixed32x2.

Tech Kneuledgo
Blockchain (MU) 3- 13
Programming for Blockch
Address hain
Address contains the 20-byte value that represents the size of an Ethereum address. An addrece
member functions. For example, to get the balance, balance method and to transfer balance to
dress object has
transfer method is used.
her address

Byte array (fixed)


Fixed-size arrays of bytes, declared with bytes1 up to bytes32.

Byte array (dynamic)


Variable-sized arrays of bytes, declared with bytes or string.

Enum

User-defined typefor enumerating discrete values: enum NAME (LABELI, LABEL 2,.
Arays
An array of any type, either fixed or dynamic: uint32015] is a fixed-size array of five dynamic arrays of
unsianes
integers. gned
Struct

User-defined data containers for grouping variables: struct NAME


(TYPE1 VARIABLE1; TYPE2 VARIABLE2;.
Mapping
Hash lookup tables for key » value pairs: mapping(KEY_TYPE VALUE_TYPE) NAME.
In addition to these data
types, Solidity also offers a
variety of value literals that can be used to calculate different
units:

Time units

The units seconds, minutes, hours, and days can be used as suffixes, converting to multiples of the base unit
seconds.
Ether units

The units wei, finney, szabo, and ether can be used as suffixes, converting to multiples of the base unit wei.
3.6.3 Variables

Solidity supports three types of variables.


State Variables: These variable's
values permanently stored in a contract storage.
are

Local Variables: Variables whose


values exist till function is
executing.
Global Variables Special variables present in the global namespace and used to receive the
blockchain. information ddo
The state local variable
or
type needs to be specified during declaration. default

value based on its The declared variable always nds


type. There is no concept of "undefined" or
"null". Remix IDE is used to
osolidity
program. Consider the following compile and run tne
solidity program. The first line is a pragma directive codeis
written for Solidity version 0.5.0 which tells that the source
Tech Knouled
bit atien
Blockchain (MU)
3- 14
pragma solidity ^0.8.2; Programming for Blockchain
contract SolidityTest (

constructorO public

function getResult) public view returns(uint){


uint a = 1;:

uint b = 2;

uint result = a + b;

return result;

The output of the above code is 0: uint256: 3


The comments are written with // symbol. We can also write multiline comments. For
example.
//This is a comment. (Single line)

/This is a comment written in more than one line


This a comment written in more than one line

State Variable

Following is the example of state variables.

pragma solidity ^0.8.2;


contractSolidityTest{
uint storedData; // State variable

constructorO public {
stored Data = 10; // Using State variable

Local Varlable

Following is the example of local variable.


pragma solidity ^0.8.2;
contract SolidityTest {
uint
storedData; // State variable
constructor) public {
storedData = 10;

TechPuE Knouledg
tin
3-15 Programming tor Blocke
Blockchain (MU)
function getResult0 public view returns(uint){

uinta =
1;// local variable
uint 2;
uint result = a + b;
variable
return result://access the local
variable
return storedData; //access the state

Global Variables
information about the blockchain
which present in global workspace and offer
.

These are special variables


the EVM, it has access to a small set of global objects whi
contract is executed in
transaction properties. When a
includes block, msg, and tx objects.

message call context

msg.sender(address payable) Sender of the message. It represents the address that initiated this contractcall
not necessarily the originating EOA that sent the transaction. If our contract was called directly by an EOA
it will be contract address.
transaction, then this is the address that signed the transaction, but otherwise
a

msg.value : Number of wei sent with this call.

msg.gas: The amount of gas left in the gas supply of this execution environment. This was deprecated in Solidity

v0.4.21 and replaced by the gasleft function.

msg.data: The data payload of this call into our contract.

msg.sig(bytes4) : The first four bytes of the data payload, which is the function selector.

Transaction context

The transaction-related information is accessed through tx object.

tx.gasprice (uint): Gas price ofthe transaction


tx.origin (address payable): Sender ofthe transaction
Block context

The block object contains information about the current block:


block.blockhash(blockNumber): The block hash of the specified block number, up to 256 blocks in the pas
block.coinbase: Current block miner's address.

block.difficulty: The difficulty (PoW) of the current block.


block.gaslimit: Current block gaslimit.
block.number:The current block number (blockchain height).
block.timestamp: The timestamp placed in the current block.
(Number of seconds since the Unix
epo
Tech
Knoulea

Pubiltalie
Programming for B i c n a a
Blockchain (MU) 3-16

Solidity Variable Names

While naming your variables in Solidity, keep the following rules in mind.
boolean variabie names z e
Solidity reserved keywords cannot be used as a variable name. For example, break or

not valid.

letter underscore crarace


Variable names should not start with a numeral (0-9). They should begin with a or an

For example, _123test is a valid and 123test is an invalid variable name.

Solidity variable names are case-sensitive.

Address Object
metno0s
object, has number of attributes and
Any address, either passed as an input or cast from a contract a

current contract balanceS


address.balance It denotes the balance of the address in wei. For example, the
address(this).balance.

address.transfer(amount): Transfers the amount (in wei) to this address. It throws an exception on
any eror
and does not throw any exception Aways
It is similar to transfer. It returns false on error
address.send (amount):
check the return value of send.
message call with
a datz
low-level CALL function-can construct
an arbitrary
address.call(payload): This is a

payload. Returns false on error.


contract to hait with
can accidentally or maliciously use up all your gas, causing your
WARNING: unsafe-recipient
value of cal.
an 00G exception; always check the return
code
with this contract's
like address(this).call() but
:Low-level CALLCODE function,
address.callcode(payload)
address. Returns false on error.
replaced with that of
WARNING: advanced use only!
but with the full msg contet seen by
function, like callcode(.)
Low-level DELEGATECALL
address.delegatecallO only!
WARNING: advanced use
Returns false on error.
the current contract.

3.6.4 Variable Scope three


can have
but State variables
function in which they are defined
remains within the
Scope of local variables is
types of scopes. state variable, an
as well as via messages. For a public
variables can be accessed internally
Public: Public state

automatic getter function


is generated. or contract deriving
accessed only internaly from
the current contract
variables can be
internal: Internal state

from it without using this. current contract they are defined


not in
the
only internally from
variables can be accessed
Private: Private state

the derived contract from it.

Example
pragma solidity ^0.8.2;
Tec eie
contract C {
Progra ing for Blodkc
3-17
Blockchain (MU)
uint public data = 30;

uint internal iData= 10;

function x) public returns (uint){


data 3: // internal access
return data;

contract Caller
Cc=new C0
function f0 public view returns (uint) {
return c.data): //external access

contract D is C {
function y0 public returns (uint) {

iData 3;// internal access


return iData;

function getResult0 public view returns(uint)H

uint a =
1:// local variable
uintb 2;
uint resut = a + b;

return storedData; //access the state variable

Arithmetic Operators

Following are the arithmetic operators used.

Operator Meaning
Addition

Subtraction

Multiplication
Division
TechNinaes

Pattnr
Programming for Blockchain
Blockchain (MU) 3- 18

Operator Meaning
% Modulus

Increment

Decrement

Comparison Operators

Following are the comparison operators used.

Operator Meaning
Greater than

Less than

Greater than and Equal to

Less than and Equal to

Bitwise Operators

Operator Meaning9
& Boolean AND

Boolean OR

Boolean exclusive OR

Bitwise NOT

Left Shift

Right Shift

>>> Right shift with Zero

Assignment Operators
Operator Meaning
Simple Assignment
+ Add and Assignment

Subtract and Assignment

Multiply and Assignment

Divide and Assignment

% Modules and Assignment

Tech&neuledg
Blockchain (MU) 3-19
Programming for Blockchain
String
String literal using are used with both double quote () and single quote (). It offers string as a data type to da.
a variable of type String.

pragma solidity ^0.8.2;


contract SolidityTest {
string data = "test";

In above code, "test" is a string literal and data is a string variable. If byte types are used instead of
String as stiod
ing
operation, then less gas is required compared to string operation. Solidity supports inbuilt conversion betweenbytes th
string and vice versa. It is easily possible to assign String literal to a byte32 type variable. Solidity considers it as
byte32 literal.

pragma solidity ^0.8.2;


contract SolidityTest{
bytes32 data= "test

3.6.5 Arrays: Fixed and Dynamic Arrays


Array data structure stores a fixed-size sequential collection of elements of the same type. It is more useful to thint
array as a collection of same type variables. There is
no need to declare individual variables, for
example, numberd
number1, and number99. Instead of this, it is sufficient to declare one variable such as numbers and use numbers|0)
numbers[1], and ., numbers[99] to represent individual variables. A particular element in an array is directly accessed by
an index. In Solidity, two types of arrays are supported. One is compile-time fixed size and another is of dynamic size. In
case of storage array, different types of elements can be stored. For
memory array, element type cannot be mapping
and in case it is to be used as function then
parameter element type should be an ABI type. All arrays comprse
contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last
element of an array.

Fixed Size Array

In Solidity, to declare fixed size of


array, programmer has to specify the type of the elements and the
elements in an
numbe
array.
type arrayName [ arraySize ]:
This issingle-dimension array. The arraySize must be an integer constant
a valid
greater than zero and type s ay
Solidity data type. For example, to declare a 20-element array called account
of type uint, use this statement
uint account|20]:

Following program demonstrate the use of fixed size array.


1/ Solidity program to demonstrate
creating a fixed-size array
pragma solidity ^0.8.2;
// Creating a contract
Techn o l
Puniurattu
Blockchain (MU)
-20
contract Types { Programming for Blockchain

/ Declaring state variables of type array


uint[6] data1;

1/ Defining function to add values to an arrTay


function array_example0 public returns (
int[5] memory, uint[6] memory){
int5] memory data [int(50), -63, 77,-28,
=

90];
datal [uint(10), 20, 30, 40, 50, 60:
return (data, data1);

Output

"0:"int256[5]: 50,-63, 77,-28, 90,


"1: "uint256[6] 10, 20, 30, 40,50,
60"
Dynamic Arrays
In Solidity, to declare an array of dynamic size, the
programmer has to specify the type of the elements as follows.
typell arrayName;
Dynamic memory arrays are created using new keyword.
uint size = 3;

uint account] = new uint|(size);

Following single statement initializes Solidity array elements.


uint account[3] =
[10, 20, 30]
Following is an example to assign a single element of the array :

account[2]=5;
he above statement assigns element number 3rd in the array a value of 5.
uint salary account[2];
he above statement assigns the value of third element in array to salary variable.

Example:
0lidity program to demonstrate creating a dynamic array
pragma solidity ^0.8.2;
I/
Creating a
contract
contract Types {
D
Declaring state variable oftype array. One is fixed-size and the other is dynamic array
uint) data
[10, 20, 30, 40, 50];
int] data1;
BE Tech Kneutedgi
nan (MUJ 3 21
Programminy for Blockchain,
I/ Defining function to assign values to dynamic array
function dynamic_arrayO public returns(
uint memory, int[| memory){
datal =
[int(-60), 70,-80, 90, -100,-120, 140]:
return (data, data1);

Output:
0": "

int2560 10,20, 30, 40, 50,


1:"int2560 -60, 70,-80, 90, 100,-120, 140"
Members

Length It returns the size of the array. 1It can be can be also used to change the size of dynamic array.
Push: push is used to append element to
an a dynamic storage array at the end. It returns the new
length of t
array.
Declaration, assignment and accessing the arrays is demonstrated in following example.

Example
pragma solidity ^0.8.2;
contract test {
function testArray0 public purel
uint len =7;
//dynamic array
uint] memory a = new uint[](7):

//bytes is same as byte]


bytes memory b = new bytes(len);

assertla.length == 7);

assert(b.length == len):

//access array variable


a[6) 8;
//test array variable

assert(a[6]==8);
//static array
uint[3 memory c = luint(1), 2, 3];

assert[c.length == 3);

TechKnoul
ubiiiatie
Blockchain (MU)
3 22
Programming for Blockchain
3.6.6 Special Arrays: Bytes and Strings
3.6.6

Byte Arrays

In Solidity language,
byte array is a dynamic array and hold any number of
which takes 32B for each variable. bytes. It is different from the bytes value
type Following are the ways to use the byte array.
It allows to declare a state element with initial
length size
tic DOSsible divide into code lines that
are
similar to
the arrays.
Can assign values directly and have values
pushed into it.
.offera read/write length property
Example:

pragma solidity ^0.8.2;


/ code illustration of byte array in solidity

ContractSampleBytesArray
1/ as a state variable

bytes simBytes = riBytes (2)

1/ as divided code lines

bytes simBytes
simBytes=riBytes (8)
1/ with directly assigned values
simBytes=" Lorem Modi "
// with values pushed into it
simBytes. push ( byte(10))
I/ as read/write length property
simBytes. length 5;// setting bytes length to 5 bytes

String arrays
tring arrays are also dynamic arrays similar to byte arrays. The string does not have an index and hence, array
hembers such as length, push, and pop does not present. If needed then we must convert string variables to bytes first,
are composed of characters within a single or double
n then convert back tostrings after the operation. Strings
yOte.in following example, strings are declared and the values are assigned directly:

pragma solidity ^0.8.2;


code illustration of a string array in solidity
Contract SampleString
String name "Solidity
=
"

/convert back to bytes


ytes ByteName bytes (name );
=

TechKnowledga
Blockchain (MU) 3-23 Programming for Blocke+
3.6.7 Enums
Enums alows for variable to have one of only a few predefined values. Enums are values
s in this
this enumers
enumerated is
Enums helps to reduce the number of bugs in your program. Consider the example of a fresh juice shop. it wo
possible to limit the glass size to small, medium, and large. This would ensure to order only size that
would b
that isis small, me
smal,
or large.
medium
pragma solidity ^0.8.2;
contract test {

enum FreshJuiceSize{ SMALL, MEDIUM, LARGE}

FreshJuiceSize choice;
FreshjuiceSize constant defaultChoice FreshjuiceSize.MEDIUM;
function setLarge0 public{
choice FreshJuiceSize.LARGE;

function getChoice0 publicview returns (FreshJuiceSize){


return choice;

function getDefaultChoice0 public pure returns (uint) {


return uint(defaultChoice);

3.6.8 Structs

Struct types represents a record. Following are the attributes to keep track of your books in a library.

Book-Title

Author

Subject
Book 1D
n
The struct keyword is used to define structure. The struct keyword defines a new data type, with more tia

member. Following is the syntax of struct statement.

struct struct_name {

type1 type_name1;
type2 type_name_2;
type3 type_name 3;

PuDii(t
Blockchain (MU) 3-24 Programming for Blockchain

E x a m p l e

structBook{

string title;

string author;

uint bookid;

member access operator () Is used to access any member of the structure. The member access operator is
The
an as a period between the structure variable name and
the structure member that we wish to access. Following
demonstrate the use of struct.
program
pragma solidity ^0.5.0;
,

contract test {

structBook{
string title;
string author;
uint book id;

Book book

function setBook0 public {


book= Book('Learn Java', "TP', 1):

function getBookld) public view returns (uint){


Teturn book.book_id;

First Click setBook Button to set the value as LARGE then click getBookld to get the selected book id.

Output
5uint256:1
3.6.9
Mapping
Mapp
tapping in Solidity are used to store the data in the form of key-value pairs. A key is any of the buit-in data types
ierence types are not allowed while the value can be of any type. Mappings are typically used to associate the
Ereum address with the associated value type. Following is the syntax to declare a mapping type. All kevs
must have ne same type and all values must have the same type. Mapping is always stored in storage, it's a state
the same
variable. The mapt is constant no
matter of size.
Ppng advantage is that lookup time
mapping( => _ValueType)
Tech nled
Pub atia
Blockchain (MU) 3-25

Where
Programming tor Blockchain
KeyType: can be any built-in types plus bytes and string. No reference type or complex objects are allow
ed,
ValueType: can be any type.
Creating Mapping: Following example shows the creation of mapping.
// Solidty program to demonstrate mapping
pragma solidity ^0.8.2;
// Defining contract

contract mapping.example{
I/Defining structure
struct student
*

:******:

// Declaring different structure elements


string name;
string subject; ****

:
uint8 marks; *
.

**

1/ Creating a mapping
mapping (
address=> student) result; :::: ...

address] public student result; :***::

..

Adding values to mapping : Example shows mapping is created and values are added to the mapping.
I/ Solidity program to demonstrate adding values to mapping
pragma solidity ^0.8.2;
// Creating contract

contract mapping_example{
//Defining structure
struct student {
//Declaring different structure elements
string name;
string subject;
uint8 marks;

I/ Creating mapping
mapping (
c h n e a

PuILl"""
Blockchain (MU) 3-26 Programmng tor Blockhhain

address=> student) result;


address] public studentresult;
/ Function adding values to the mapping

function adding values0 public {


var student

=result[0xDEE7796E89c82c36BAdd1375076139D69FafE252]
student.name = "John";

student.subject = "Chemistry";

student.marks = 88;

student result.push(
OxDEE7796E89C82C36BAdd137507639D69FafE252)-1;

Output
result: mapping(address struct
=>
mapping_example.student
000000000000000000000000dee7796e89c82 c36badd1375076f39d69fafe252
struct mapping_example.student

name: "John" string

subject: "Chemistry" string


marks: 88 uint8
Example : The contract mapping_example defines a structure, mapping is created, values are added to the
mapping, and values are retrieved from the mapping
I/ Solidity program to count number of values in a mapping
pragma solidity ^0.8.2;
contract mapping_example {
I/ Defining structure
struct student {

/ Declaring different structure elements


string name;
string subject;
uint8 marks;

I/ Creating mapping
mapping (address => student) result;
address[] student result
Programming tor Blockchat
Blockchain (MU) 3-27

//Function adding values to the mapping


function adding values0 public(
var student
result[0xDEE7796 E89C82C36BAdd1375076f39D69FafE252];

student.name = "John";

student.subject = "Chemistry";

student.marks = 88;

studentresult.push(
OxDEE7796E89C82C36BAdd1375076139D69FafE252)-1;

// Function to retrieve values from the mapping


function get_student result(
view public returns (address[]) {
return student_result;

//Function to count number ofvalues in a mapping


function count udents(
) view public returns (uint) {
return studentresultlength;
}

3.6.10 Functions

Solidity supports all the important and necessary features modular code using functions. First, we have t
to write
define and then use the function In Solidity, funetion is defined by using the function keyword, followed by a uni*
he
function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces
function defined in the contract can be called by an EOA transaction or another contract. Following is the basicsynta
function function-name(parameter-list) scope returns) {
//statements

In following example, function getResult is used and that takes no


parameters.
Example
pragma solidity ^0.8.2;
contract Test{
function getResultO public view returns(uint){

uint a 1;// local variable


=

2174
"ublilall
Blockchain (MU) 3-28 Programming for Blockchain

uint b = 2;

uint result
= a + b;
return result;

3.6.11
Visibility and Activity Qualifiers

The following keywords specify the function visibility. Visibility to a function specifies how the function is visible to
either from internal or external.
the caller
Public The public is the default and these public functions are can be called by other contracts or EOA
transactions, or from within the contract. They are visible from internal and external contracts. It means, they can
be called inside a contract or outside contract. As this function is visible to public, security concern is there.
Private: private functions are visible inside the same contract are like internal functions. They can not be called by
derived contract.

External: External functions are similar to public functions. These functions cannot be called from within the
contract unless explicitly prefixed with the keyword this. External functions are visible to public functions and can
be called outside contract only.
Internal: Internal functions are similar to private functions and only accessible from within the contract These
functions cannot be called by another contract or EOA transaction. Internal functions are visible to contract
hierarchy. It means, they can be called inside a contract and Contracts that inherit from it

Function qualifiers

Modifiers or qualifiers permits to define the functions with behavior for changing the state of contract data.

1 Constant or view : If the view is used then it does not allow to modify any state. The term constant is an alias for
view that will be deprecated in a future release. View is expected to become an enforced keyword in vo.5 of

Solidity.The view functions display the data and do not modify the state variable If following statements are
present in the function then it is considered modifying the state and compiler will throw warning in such cases.
Getter method are by default view functions.

o Modifying state variables.

Emitting events.
o Creating other contracts.

oUsingselfdestruct.
Sending Ether via calls.
o
Calling any function which is not marked view or pure.

Using low-level calls.


OUsing inline assembly containing certain opcodes.

Example
pragma solidity ^0.8.2
contract Test (
Tecat i
tedi
n
Progranming 1o Blockcha
Cain
3-29

Blockchain (MU) returns(uint


product,
uint sum)}t
view
Tunction getResult0 public
variable
uinta 1;//local
uint b 2;
product=a *b;

sum =a+ b;

Output
0: uint256: product 2
1: uint256: sum 3 read or Write operations. Theyd
blockchain and also not permit
access data from and return data, without
functions do not work on arguments
2. pure: pure can only
transaction data. They reading the state ang
to state data or are
considered
not allow access function
statements existing in the
data. Following
reference to any stored

compiler will throw warning.


variables.
That reads state
<address> balance.
address(this).balance or
That accesses
can be read).
and msg.data
variable of block, tx msg (msg.sig
Those accesses any of the special
not marked pure.
That calls any function

inline assembly that


contains certain opcodes
Using occurs
functions to revert possible state changes if an error

can use the revert) and require)


Pure functions

Example:
pragma solidity ^0.8.2;

contract Test{
product, uint sum){
function getResult0 public pure returns(uint
uint a = 1;

uintb 2;
product= a "b;
sum = a+ b;

Output
0: uint256: product 2

1: uint256: sum 3

eknouledg
ubiiaT
Blockchain (MU) 3 30 Programming for Blockchain

Payable:A payable function accepts the incoming payments from caller. Those function which are not declared as
3.
payable rejects incoming payments. Hence, payable function can accept Ether sent to the contract. if it is not
specified, the function automatically rejects all Ether sent to it.

Example:

pragma solidity ^0.8.2;

contract Sample {
uint amount =0;

function payme0 payable(


amount+= msgvalue;

Above example shows that, payme function is marked with payable keyword, which translates to that you can send
ethers to payme function. As all the ethers sent to payable functions are owned by contract, Sample contract owns all of
the ethers.

Payable fallback functions:


A function having no name and marked with payable keyword is called payable fallback function. There could be

single such function in contract.

Example:
contract Sample {

function0 payable {
I/sample fallback

Address and Address Payable


Address and address payable difference introduced in Solidity version 0.5.0. The intention was to separate
for other purposes). Hence, an address payable can
addresses that receive money, and those who can't (used
can
receve Ether, while a plain address cannot. Hence, in Solidity, Ether can be sent to a variable defined as address payable
Out cannot be sent to a variable defined as address. Use the keyword payable before the variable name of an address

type to enable it to receive ether.


For Example
contract Vaults{
/ United States gold reserves (cannot receive ether)
address FortKnox;
I/ deposit ether here
address payable etherVault;

nclKneuedge
*ubI 4en
Blockchan (MU) 3 31
Programming tor locahas
The type returned by msg.sender is of address payable type. Therefore, the following methods become availh
an address defined as payable in Solidity: transfer). send), call), delegatecall) and staticcail e
3.6.12 Solidity Contracts and Constructors
Contract contains Constructor, state variables and functions. Constructor is a special function declared
w
constructor keyword which will be executed once per contract and is invoked when a contract is created. State variak
and functions are already explained. The visibility quantifiers which are public, private, internal and external
re
explained in above sections.

Example
pragma solidity ^0.8.2;
contract C
//private state variable uint private data;
//public state variable
uint public info;

//constructor
constructor0 public {
info = 10;

//private function
function increment(uint a) private pure returns(uint) ( return a+ 1;}
l/public function
function updateData(uint a) public{ data =
a; }
function getData() public view returns(uint) {return data; )
function compute(uint a, uint b) internal pure returns
(uint) { returna+ b; }

//External Contract
contract D
function readData() public returns(ulnt) {
Cc new CO:

cupdateData(7);
return c.getData():

//Derived Contract
contract Eis C{

Tech Ke
Programming for Blockchain
iockhaun (MU) 3-32
uint private result

Cprivate c

constructor0 public (

cnewCO0:

function getComputed Result0 public{


result= compute(3, 5):

functiongetResult0 public view returns(uint) {return result:}


function getData0 public view returns(uint) { return cinfo0:}

Output
0: uint256:8

Abstract Contract

This contract includes at least one function that is short of any implementation and is used as a base contract.
Generally, an abstract contract includes both implemented together with abstract functions. Derived contract will
implement the abstract function and use the existing functions as and when essential. If, a derived contract is not
implementing the abstract function then this derived contract will be marked as abstract

Example
pragma solidity ^0.8.2;
contract Calculator {
function getResultO public view returns(uint);

contract Test is Calculator {

function getResultO public view returns(uint) {


uint a 1;
uintb 2;
uint result = a + b;

return result;

Output
O: uint256:3

ec eotedge
Blockchain (MU) 3 33
Programming for Blockcha
Interfaces
Interfaces are just like as abstract contracts and are created using interface keyword. Interface are witho
function with implementation. Functions of an interface are only of type external. Interface is without constructo
hout
ctor and
state variables. Interface can have enum, structs that are accessed using interface name dot notation.

Example
pragma solidity ^0.8.2;
interface Calculator (
function getResult0 external view returns(uint);

contract Test is Calculator (


constructor(0 public 0
function getResult0 external view returns(uint){
uint a = 1;

uint b 2;
uint result = a + b;

return result;

Output
0: uint256:3

3.6.13 Inheritance in Solidity


Functionality of a contract can be extended with inheritance. In Solidity both single and multiple inheritance 5
supported. Following are the important highlights related to inheritance.
A derived contract can access all
non-private members together with internal methods and state
using this is not permissible.
variables.
Function overriding is permissible if function signature remains similar. he
If difference output parameters difter
compilation fails.
It is allowed to call a super contract's function using super keyword or using super contract name.
If multiple inheritance is used then function call using super gives
preference to most derived contract.
Example
pragma solidity ^0.8.2
contract C{
//private state variable
uint private data;

Pubuati
chain (MUJ 3-34
Programming for Blockchain
l/public state variable

uint pubic info;


//constructor

constructor0 pubiic{
info 10

I/private function

function increment(uint a) private pure returns(uint)


{ return a+1:}
/public function

function update Data (uint a) public { data a;} =

function getData0 public view returns(uint) {return data:)


function compute(uint a, uint b) internal pure returns (uint){return
a b:

I/Derived Contract
contractE is C{
uint private result;

Cprivate c;
constructor0 public{
c= new CO:

function getComputedResult0 public{


resut= compute(3, 5):

function getResultO public view returns(uint) { return result; }


function getData0 public view returns(uint) { return cinfo0:}

Output
uint256:8
3.6.14 Solidity Error Handling
Solidity offrs several functions for error handing. Usually, on occurring of an error, the state is reverted back to its

orginal state. Other verifications are to avoid unauthorized code access. Following important methods are used in error

handling of Solidity.
sert(bool condition): If condition fails to meet, this method call causes an invalid opcode and any altered state

ges reverted. This method is often used for internal errors.

Tech neuiedge
Blockchain (MU) 3 35 Programming for Blockcha
require(bool condition) : If condition fails to meet then this method call reverts to original state. This
his method is
used for errors in inputs or external components.
require(bool condition, string memory message): f condition fails to meet then this method call thod
call reve reverts
original state. This method is used for errors in inputs or external components. It oters an option to provi. to
vide a
custom message.
revert) This method aborts the execution and revert any alternations carried out to the state.

revert(string memory reason): This method aborts the execution and revert any alternations carried out
to the
state. It provides an option to offer a custom message.

Example of error handling in Solidity

pragma solidity ^0.8.2;


contract Vendor {
address public seller;

modifier onlySeller0{
require(
msg.sender == seller,

"Only seller can call this."

function selluint amount) public payable onlySeller{


if(amount>msg.value /2 ether)
revert("Not enough Ether provided.");

I/ Perform the sell operation.

Calling the revert return the hexadecimal data shown below.

Output
Ox08c379a0// Function selectorfor Error(string)
Ox00000000000000000o0000000000000000000000000000000000000000000020 //Data offset
Ox000000000000000000000000000000000000000000000000000000000000001a//String length
Oxte67420656e61756768204574686572207072676696465642e000000000000//Stringdata
3.7 Case Study: Voting Contract App
the
The main goal of an electronic voting systems is to reduce the cost of running an election, while ensuring
election integrity by fulfilling the security, privacy and compliance requirements. Blockchain based election sy
system

has the potential to limit fraud while making the voting process traceable and verifiable.
TechKnoule
PubliIatre
Programming for Blockchain

3 36
Blockchain (MU)
Electronic voting systems
Conventional votin ting methods incurs more expenditure and are more time onsuming.
and
flexible, simple to use,
the etficiency and the integrity of the election process. They are more
has enhanced
fordable costs compared to general elections.
tace tie

nat from these benefits


of e-voting systems, it is found that the, existing eiectronic voting metheds
Apart anonymity,
running over-authority and manipulated details, limiting basic fairness. privacy, confidentiality,
into
of the
nd transparency
and
in the voting process. E-voting procedures are not decentralized and approved by cntuca
Hence, there are more
measures, and monitors the process in an electronic voting system.
authority that controls,
auth
does not
that assurance in voting
chances of obstructing a transparent votin9 process. It is important to guarantee the
modern elections and make
diminish.
di
Blockchain a n overcome theshortcomings in the voting method used in
also strengthen the data
and accessible to stop illegal voting. Blockchain can
ooling process transparent and
blockchain is decentralized
protectionto guarantee a transparent outcome of the polling process. As
are witn
minimize the risks that
replicated ledger, a smart
contract-based electronic voting system will surely
electronic voting and permits for the process to be tamper-proof.
for Blockchain based Voting App
Design Considerations
an e-voting
In order to design any application, we design requirements. For implementing
have to first consider its
the existing e-voting
it is necessary to think about its design requirements. This can be done by evaluating
system, national election. Following
the requirements for such systems to be effectively used in a
systems and considering
are the general requirements
for blockchain based voting system.

Forced voting should be prevented.


method of secure authentication via an
shouid permit a
o The proposed blockchain based voting system
identity verification service.

votes to respective voters.


It should not permit traceability from
that their vote was counted,
form of a verifiable guarantee to each voter
It should offer transparency, in the

correctly,and without risking the voter's privacy.


o Tampering of vote given should be prevented.

not be centralized with single authority.


o Counting of votes should
election.
should be allowed to vote in
an
O
Only eligible voter
then following the essential
consider the election system in India,
are

Considering above requirements, if we

requirements.
to vote in election. This can be Aadhaar number or
Voter should have valid national ID to
be eligible
citizen of India.
Permanent account number (PAN) to recognize him/her as a

can vote in any election ifthey are already registered for voting.
All the citizens having age 18 and above
is not allowed.
More than one vote by single voter
onditions for Denying the Right to Vote
centre in constituency where they are registered. The voter-related
A Voter can vote at the recognized
only with the valid national ID number of the
code are associated
ormation such as age, state, and constituency
voter.

Tech lneuledgi
Blockchain (MU) 3-37 Programming for Blockch
Election commission's (EC) contract list should include the national ID number of the voter. If this ID does not
eist
in contract list of EC, then voter should not be allowed to cast the vote.

Election is ongoing in already declared constituency and voter's constituency code is not matching with
this
constituency code
If voter has already casted the vote in his/her constituency.

Process of Voting
Voter can login to the election commission website/portal by using national 1D. This will provide you one tin.

password (OTP).
If the national 1D registered does not exist in the contract (voter list) and the voter's constituency code match with
the constituency where election is ongoing then EC portal will show it. Otherwise, the voters are not permitted ta

vote. If the election process is still going on, it will prompt you with the option to vote in the following manner.

First click Vote and then Select Candidate. After that finish the voting by submitting the vote.
Voters are not permitted to cast vote or update vote to different candidates again.
Transparency is ensured by displaying the final candidates list with the vote count after the election voting

process is completed.

Smart Contract
As per defined assumptions, requirements, processes and constraints, following are the steps illustrating the

process of voting.

Voter logs in using website or portal of EC.


1
18 years then candidate list will be displayed based on
If voter is valid, already registered and having age >=

constituency code.

If voter is not valid then voting will be denied.

Valid voter initiates the voting process and will be allowed to vote if following conditions holds.
2.

lfage 18 years

If election is ongoing in declared constituency.

If voting is already not done with this ID, then will be allowed to cast the vote.

If all of the above conditions fuifil, vote will be casted to eligible/selected candidate in list.
3. If voting is yet not started in constituency, then reject the vote.

Entities in Voting Process

Following are the main participants in this voting process.

Voters who cast the vote.

Candidates to whom vote to be casted.

Election Commission (EC).


to
A contract named Ballot can be created to define key entities in this process. Solidity structure can be u

define own data types as per user's requirement. The election commission will be the creator of the contract.

Pubur
3-338 Programming for Blockchain

C t has a unique natona D number. Other details associated with the voter are name, age, state, ana

e n c y code Structiure with narme Voter can be created which includes the fields that define the nationa
etficaton number ot the voter, name of the voter, age, code of the state, constituency code, is alive and

andicateto whom vote is casted


the Election
andiate Contesting
Canicates belong to derent polítical parties or can be independent. They are the key entities in the process of

e e t o n Each political party has its symbol and also EC allocates symbol to independent candidate. Each
sicate contesting the election has to file for the election. Therefore, each candidate has a unique nomination

sutre with name Candidate can be created that defines the attributes related to candidate. These attributes are
ame of the candicete, name of the party, symbol of the party, nomination number, number of votes received,
ther independent or not, constituency code and state code.

Section Commission (EC

The eection commission is responsible to create the contracts and has authority to update the voters and
anscatesitEC wil also set the start and end times for the voting Instead of considering the several addresses
anage the entire election process, a single address with admin authorities is considered.

Ths address is a state variable which that contains the Ballot contract. The voter and candidate will be declared as
apping to maintain the list of records of voter and candidates as the key value pair, where the key is the national
Dumberand the value is the oter object. Hence, for each key value (national ID numben), only one voter record
il be there and the same goes for candidates with a unique nomination ID.

Folowing are the steps involved in interaction of voter with EC website/portal.


f
eiecton process is already completed the website displays the result. Voter can view the result
(step 8). If
alection process is ongoing and voter has to cast the vote then he/she will carry out login process by using
nis/her 1D number. In this case, result of election can not be accessed (step 7). If user is valid registered user,
hen step 2 is carried out Voter's ID number should be valid, age should be greater than or equal to 18 and
he must be alve. All these conditions should be met for voter to a valid voter.

The ID of the voter will be presented based on their constituency along with the list of candidates to vote for.
The voter now will select the candidate to whom the vote will be casted.
The vote is initiated by voter and validation of step 4 and step 5 is done. After validation of these steps, vote
gets registered against candidate and his/her vote count gets incremented.
Ihe contract verifies if voting lines for the election are open. If yes then flow moves to step 5 else it moves to
Step 6.
n this step, eligibility conditions for voting are verified for the voter. These conditions are: age is greater than

o equal to 18, this voting is first time, and does the candidate the voter has initiated the vote for belongs to

te same constituency as the voter. These verifications are carried out through a functional modifier.

Voting access to voter is denied.


cton is ongoing and resut cannot be accessed.
ecton process is over and anyone can access the result of election.

Tech newledge
Blockchain (MU) 3-39 Programming for Blockchain
Benefits of Blockchain based E-voting
Enhanced security.
Accurate and faster election process.
Incurs less expenditure in for election process.
Faster and accurate counting of votes.
As human intervention is less, fraud is prevented.
Limitations of Blockchain based E-voting
Voter should have internet facility available.
Voter should be aware about how to use and access the web.

Voters have to provide personal information.

3.8 Preparing for Smart Contract Development


Smart contracts are one of the most
capable and appealing ideas in blockchain technology. Their sef-enforcing
and event-driven features facilitates to
carry out online activities without the involvement of trusted third parties
The security, privacy, and efficiency are the
key problems for universal adoption of the smart contracts. To
develop
the smart contracts, a developer should be aware about the
following three types of information.
The state-of-the-art design paradigms, design tools, and alternative
systems available to create or execute
smart contracts securely.

The current challenges involved in efficient development of secure smart contracts and their
adoption by
various applications.
The methods and research to overcome these
challenges and limitations.
There various forms of smart contracts depending on the
are
platforms on which they are running. Therefore.
design schemes of smart contracts are platform dependent, especially the
language they support. Smart contracts
programmed in scripts are generally used to describe financial transactions. Whereas, smart
contracts written in
Turing-complete languages could theoretically describe any deterministic protocol as a
computer program.
1 Smart Contract Construction using Scripts

Script-based blockchains typicaly offer simple stack-based


opcodes to ease a more flexible circulation o
cryptocurrencies. For example, it is possible for payer to
specify a condition under which the payee receve
his payment. The key purpose of such script languages
is to facilitate
Hence, smart contracts written in simple financial affairs or demano>
script-based blockchains are relatively
those in Turing-complete blockchains. simple and limited compared ith
There are two
categories of contract constnuction
schemes. These are design paradigms
paradigms denotes the modular patterns in functionalities, and too's. DE
applicable to different scenarios and widely dered

secure. Such schemes facilitate to develop secure smart contracts


consioe
intended at assuring the security of smart efficiently. Design tools denotes the sou tions

contracts. Bitcoin is the


example of script-based Blockchain.
Because of difficulty in script
programming, many new languages for bitcoin relevant evelop
smart contracts are proposed to
improve the expressivity, blockchains to dev
These languages are further divided as readability, and verifiability of the Bitcoin s cripts

high-level languages and intermediate


representation lang
uages

based on their expressivity.

ecnowledg
Pubiia
Blockchain (MU) 3 40 Programming for Blockchain
High-level languages are more expressive and can be directly used by ordinary developers with ease. On the
other hand, intermediate representation languages are suitable during the compilation and security analysis.

Cmart Contract Construction using Turing-Complete Languages


2.
Bitcoin's script language supports limited operations. Ethereum extends it by introducing a new virtual
machine structure to support Turing-complete programming languages, significantly extending the
application scenarios of smart contracts.

The smart contracts run in Ethereum Virtual Machine in the form of EVM bytecode. In fact, to ease the
definition of the execution rules in smart contracts, several high-level programming languages are introduced,
which can be converted into
bytecode by compilers, such as Solidity, LLL (Lisp-Like Language), and Serpent.
These high-level languages provide high expressivity and can lessen the difficulty of contract construction. The
execution mechanisms of Ethereum derivatives are almost the same as EVM and support Turing complete
languages. These systems are Turing-complete blockchains.

To minimize the errors in contract programming, developers must refer contract design paradigms, which are

cautiously designed against common attacks and recognized as safe. These paradigms are for specitic
applications and general purposes.

To be a experienced blockchain technologist, you must have both a fundamental understanding of smart
contracts and the skills to build them on at least of the available blockchain
one
platforms.
Steps to Develop an Ethereum Smart Contract

Step 1:Create a walllet at meta-mask

Install MetaMask in Chrome browser and enable it. After installation, click on its icon on the top right of the
browser page. t wil open in
Now you
a new tab of the browser. Click on "Create Wallet" and click "1 agree" to proceed further.
are agreeing to the terms and conditions. Create a password and then it will send you a secret backup phrase
Used for backing up and restoring the account. It should not be disclosed or shared with anyone, as this phrase can
steal your Ethers. Ensure that you are in the "Main Ethereum Network." If you find a checkmark next to "Main Ethereum
Network, you are in the right place.

METAMASK
Tips
Secret Backup Phrase Store this phrase in a password
manager l1ke 1Password.
Your secret backup phrase makes it easy to back up
and restore
your account Write 1his phrase on a piece of paper
and store in a secure location. if you
wARNING: Never disclose your backup phrase. Anyone want even more security, write it
w h this phrase can take your Ether forever.
down on multiple pieces of paper
and store each in 2 3 difterent
locations
speed blade depart secret banner
Memorize this phrase
broccoli wheat able tilt diamond
circle another Download this Secret Backup
Phrase and keep it stored sately on
an external encrypied hard drive or
storage medium

BTech &neuledge
Programming for Blockch
Blockchain (MU) 3-41
Kchain
Step 2:Select any one test network
wallet. These
networks are only for the purpose ot
rOowing test networks can be seen in your MetaMask testing
and ethers involved in it have no value.

Robsten Test Network

Kovan Test Network

Rinkeby Test Network

Goerli Test Network

O NIES Taucet meiamasKo

METAMASK
Networks

OETH
Main Ethereum Network
Account1 Rap sten Yest Networ

Covan Test Netmo

e e b y Test Neheork

OETH e YestNetwr
Locattost 85
uto R

Step 3:Add some dummy Ethers to your wallet


To test the smart contract, your MetaMask wallet should
contain some dummy ethers. For example, if you testa
contract using the Robsten test network, select it and
you will find 0 ETH as the initial balance in
Click your account
on the "Deposit" and "Get Ether buttons under Test
Faucet in order to add
dummy ethers.
1aicet.meamask io

Deposit Ether

Directly Deposit Ether


"
yy alieacy ave some rthet.

Test Fauce
oA EUnr lnwm a lmmet tav the
Hapalea

To proceed, you need to click


add
"request one ether from the
as many Ethers you want to the test
network. faucet," and 1 ETH will
aded to
be added to your
yo wallet. You
Blockchain (MU)
3-42
O tpa Programming for Blockchain
aucet metamask.io
MotaMask Ether Faucot

faucet

transactions

Once the dummy ethers are added to the


wallet, you can start writing smart
the Solidity programming language. Following contracts on the Remix Browser IDE in
figure shows 1 ETH is added.

Account 1

1ETH
epase Ses

Step 4: Use editor remix to write the smart contract in Solidity


Use Remix Browser IDE to write
Solidity code. The remix is the best choice for writing smart contracts as it has a
our
nandful of features and offers a
comprehensive development experience. It is usually used for writing smaller-sized
contracts. Remix's features include:
Wamings like gas cost, unsafe code, checks for overlapping variable names, whether functions can be constant or
not

Syntax and error


highlighting
Functions with injected Web3 objects
Static analysis
Integrated debugger
ntegrated testing and deployment environment
Deploy directly to Mist or MetaMask

ech Kuledge
Blockchain (MU) 3-43 Programming for Blockchain
Step 5:Create a sol extension file
Open Remix Browser and click on the plus icon on the top left side, next to the broWser to create a .sol extene
file. ension
Step 6:A sample smart contract code to create ERC20 tokens
ERC20.sol is a standard template for ERC20 tokens.

Code
pragma solidity ^0.5.0;
import"/ERC20.sol";
contract myToken is ERC20(
mappingladdress =&gt;uint256) public amount;
uint256 totalAmount;
string tokenName;
string tokenSymbol;
uint256 decimal;
constructor0 public{
totalAmount =10000 10**18;
amount/msg.sender)=totalAmount;
tokenName="Mytoken";
tokenSymbol="Mytoken":
decimal=18;

function totalSupply0 public view returns(uint256){


return totalAmount;

function balanceOf(address to_who) public view


returns(uint256)}{
return amount[to_ who;
}
function transfer(address to a,uint256 _value) public
returns(bool){
require(value&lt;=amount[msg.sender|);
amount msg.sender]=amount[msg.sender)-_value;
amountftoal=amount[to al+_value;
return true;

B ETechKnoule
# b i i r i l i t "
Programming tor Blockchain
Blockchain (MU) 3 44

lect a version of the compiler from Remix to compile the solidity Ethereum smart contract code
Select

Step 7:Deploy
your contract
contract at the Ethereum test network. Use side
Deploy the smart deploy button at the Remix window's right-hand
transaction is complete.
and until the
Once the transaction commits successfully, the address of the smart contract would be visible at the right-hand

side of the remix window.


At first, all the ERC20 tokens will be stored in the wallet of a user who is deploying the smart contract.

To check the tokens in your wallet, go to the metamask window, click add tokens, enter the smart contract address
and click ok. You would be able to see the number of tokens there.

an Ethereum smart contract


Steps to test
.Executeallsmart contract methods like transfer, total supply, and balance. These methods appear at the right-hand
side of the remix window and you can run all the processes from there itself.
Transfer some tokens to other ethereum wallet addresses and then check the balance of that address by calling the
balance method.

Get total supply by running the total supply method.


Steps to deploy Ethereum Smart Contracts

T o make your smart contract live, switch to the main ethereum network at metamask

Add some real ethers.

Now again, deploy your smart contract using remix as mentioned in the above steps.

When a smart contract is deployed successfully, visit http://www.etherscan.io and search your smart contract
address there. Select your smart contract.

Now you need to verify your smart contract here, click "verify the contract
Copy your smart contract code and paste it at Etherscan. Select the same compiler version that you selected at
remix to compile your code.

Check "optimization" to Yes, if you had selected optimization at remix; otherwise, select No.

Click Verify.
takea few minutes and your smart contract will be live if no issue occurs.
*
You can now run your smart contract methods at Etherscan.

Review Questions
Q.1 Define the smart contract.
.2 What is smart contract? Explain in detail.
Q.3 What are benefits of smart contract? Explain
Q.4
Explain working of smart contract with example.
Q.5 Explain various
va characteristics of smart contract.

TeRneledje
Blockchain (MU) 3-45 Programming for Block
Q.6 Explain different types of smart contracts.
Q.7 Write note on smart legal contracts.
Q.8 Wite short note on decentralized applications (DApps).
Q. 9 we short note on Decentralized Autonomous Organizations (DAO).
Q. 10 Write short note on Smart Contracting Devices (SCD)
a.11 Explain basic structure of smart contract.
a.12 What is oracle? Explain its types.
a. 13 Explain various benefits of smart contracts.
a. 14 Explain limitations of smart contracts.
a. 15 Explain in short various data types supported in Solidity language.
Q. 16 What are the different types of variables in Solidity? Explain with example.
a. 17 Explain the various global variables in Solidity language.
a.18 Explain with example scope of the local and state variables in Solidity language.
Q. 19 What are the various operators supported in Solidity language?
a.20 Explain string data type in Solidity language.
a. 21 Explain with example different types of arrays supported in Solidity language.
Q. 22 Explain Enums and Struct data type in Solidity with example.
a. 22 What is mappings and how it is created in Solidity language?
a. 23 What are different function visibility in Solidity language?
a.24 Explain with example different function qualifiers in Solidity language.
a. 25 Write notes on Address and Address Payable in Solidity language.
Q. 26 What is constructor? Explain with example.
Q. 27 What is Abstract contract in Solidity language?
a.28 Explain with example how inheritance is
supported in Solidity language.
a. 29 Explain Error handling in Solidity language.
Q.30 Explain various steps to develop voting contract
application.
Q. 31 What arebenefits and limitations of blockchain
based electronic
voting application?
Q. 32 Explain various steps to develop an Ethereum smart
contract.
MODULE4
4 PUBLIC BLOCKCHAIN

Syllabus

dction to Public Blockchain, Ethereum and its


nt Components, Mining in Ethereum, Ethereum Virtual
achine(EVM), Transaction, Accounts, Architecture and workflow, Comparison between Bitcoin and Ethereum.
Mach
Tnes of test-networks used in Ethereum, Transferring Ethers using Metamask, Mist Wallet, Ethereum frameworks,
fase study of Ganache for Ethereum Blockchain, Exploring etherscan.io, and ether block structure.

4.1 Introductionto Public Blockchain


.In this module we will learn the Ethereum blockchain and discuss howit works. Ethereum is a public blockchain.

. t i s open to everyone, no matter your location, background, skin, education or age

Blockchain can be divided into two main categories according to accessing and managing permissions.

Public Blockchain Permissionless


o Private Blockchain - Permissioned

In a public blockchain anyone is able to join or leave the network at any time, meaning that any individual may
access the information, submit and receive transactions and also get involved in the process of verifying

transactions.
A private blockchain operates on the basis of access rules that limit the number of people who can join the

network. We will discuss private blockchain in detail in the next module.


The public blockchain model, which is used by Bitcoin, Ethereum, and Litecoin, is largely viewed as the original

distributed ledger structure.


and participate in this type of blockchain.
Because it is completely open, anyone may join
the globe and is auditable by everyone in the system.
from anywhere on
it can accept and send transactions
but also fully distributed, because each node connected to the network
Public blockchain is not only decentralized,
as all the others.
nas the same amount of transmission and power
by each of its constituent nodes via the
a transaction should be authorized
n order to be considered legitimate,
consensus process.
the chain.
record is authorized, it is recorded
When on
a
individuals to join the network and to
public blockchains to incentivize
ncentives are commonly used in
authenticate transactions.
changed or edited after it has been validated by
because it cannot be
ad
kept on a public blockchain is secure

the blockchain network.


FBlockchain (MU) 4-2 blic Blockchain
In the public blockchain, each network node possesses a complete copy of the ledger. Each user of the permision.
on-
less ledger keeps a copy of the ledger on their local nodes, and all users adopt a distributed consensus algoris
orithm
to decide on the ledger's final state.
One of the most significant drawbacks of a public blockchain is its complete transparency. This level
of
transparency implies minimal to no transaction privacy and supports a poor security paradigm.
Another disadvantage is the large amount of computational power required to keep the ledger up to date

4.2 Ethereum
Ethereum, founded in 2015 by Vitalik Buterin, is a unique blockchain with a unique token known as Ether.

While the ownership of digital currency is verified by Bitcoin via the blockchain, the Ethereum platform enables
developers to create fully distributed apps and does away with the "centralized" client-server internet architecture

The key feature of Ethereum is its programmability, which enables the development of applications.
Ethereum is a blockchain-based open software platform that allows developers to create and deploy decentralze

applications.
It is more than simply a platform for cryptocurrencies; it has the ability to perform tasks and develop distributed

applications.
Ethereum is a DIY platform for decentralized applications known as Dapps (decentralized apps). It is the global
infrastructure for operating Dapps.
The Ethereum network is completely decentralized since it is run by thousands of separate computers.
Once the program is deployed to the Ethereum network, these computers also identified as nodes will, be assured
that it execute as written.
It was the first technology to implement a smart contract. It permits participants to run decentralized blockchain
applications, which are called Dapps.
Ethereum blockchain is an immutable public database that stores a record of every transactions that has ever taken
place.
Ethereum is a Turing complete system.
In its virtual machine, Ethereum can run programmes and read and write data to memory. Any programme that a

Turing complete machine can compute may be done by this machine.


Ethereum's major point of differentiation is how it mixes blockchain technology and computing power. When the
programmability feature is paired with all of the blockchain's distinguishing characteristics, Ethereum becomes
practical technology.
It is referred to as ETH and has its own currency called Ether.

What is Ether?

Ether (ETH) is the native cryptocurrency of Ethereum.


It is the second largest cryptocurrency around.
The goal of ether is to create a market for computing.

The Ethereum network and smart contracts are powered by ether, which
is used as fuel (or gas).
The Ethereum network's users utilize ether to pay for services rendered by the network.
Ethereum allows us to send ether which is equivalent to Bitcoin.

Tech Koouledg
uBIILAue
Blockchain (MU 4-3 Public Blockchain

Fig. 4.2.1 : Ether Cryptocurrenc

4.3 Ethereum Components


Ethereum's components are as follows

Peer to
Peer
Network
State
Machine Nodes

Components
of Ethereum

Consensus
Ruies Transactions
Consensus
Aigonthim

Fig. 4.3.1: Components of Ethereum

Ethereum is a peer-to-peer network of computers named Ethereum nodes or clients, each of which runs a
compatible software. Anyone can run an Ethereum node and there are no special prerequisites or requirements.
At the moment, there are thousands of Ethereum nodes that communicate with each other. In Fig. 4.3.2 and 4.3.3
shows, statistics about the Ethereum mainnet.
C ezarc

The Ethereum Blockchain Explorer Earn 60% APY


while you sleep

AAN
r g tkre DeReen Emereum, the skbdscan biages
Layea 2 andother cnans liOnserougn t

PR

1 797 62 3 B 167014 4 22 Gwe

FFKLLY
$215.742 03 475 00 a 11.72007 TH 884 E80 44 GHIS Jul

Latest ransactons

From
X TO

e1:2 TZ5ielG211
tAne

From
t4n r

transaction
Fig. 4.3.2: Ethereum latest blocks and

Tech u bKneusledge
itttins
Blockchain (MU) 4-4
Public Blockchain

StatistiCS
Clients Countries Sync Status OS

Network Types History

NODE COUNT HISTORY

Fig.4.3.3: Ethereum Mainnet Statistics


There are more ways for a user or
application to communicate with the network. Web 3js is a collection of libraries
that allows web applications to interact with Ethereum node.
an
using HTTP , IPC or WebSocket. A normal website
cannot communicate with a Ethereum blockchain so we will need Web3.js

Now let us discuss components of Ethereum.

1) Peer-To-Peer (P2P) network: Every computer node


the Ethereum blockchain is linked to
or on
every other
node. Ethereum operates on the Ethereum main network, which is accessible through TCP port 30303, and
employs the EVp2p protocol
2) Consensus rules: The set of rules used to determine if a transaction is legitimate
3) Transactions : On a Ethereum network, transactions the messages that
are are sent and received. A value,
sender, a receiver, and a payload of data are all components of a transaction.
A) State machine The state machine known as the Ethereum Virtual
Machine, or EVM for short, processe
Ethereum transactions and state changes. The Ethereum virtual machine
executes the program in a
macniu
language (bytecodes). These programmes are created in a
high level and are
Solidity, language,
ME
such as
converted into bytecode via a compiler. The program written
in a high level language is
called a smart contra
5) Consensus algorithm: The distributed Ethereum network's consensus algorithm is the process used each
consensus on the longest chain. Proof of work and
to
proof of stake are the two consensus methods
Ethereum that are most often utilized
BTed Kneudedg"
Blockchain (MU) 4- 5 Public Blockchain
nata structures: The state of Ethereum is kept localy on each node in the form of a database, often Google's
6)
velDB, which keeps the system information and transactions in a serialized hashed data structure known as

Tree.
a
Merkle Patricia

4.4
Mining in Ethereum
no one owner of a distributed system, computers are free to join the Ethereum network and start
cre there is
transactions whenever they choose. This process is known as mining
verifying
which
ning nodes consult one another (consensus) to agree on the sequence of transactions across the system,
balances despite the fact that many transactions are going
ie required to instantly calculate everyone's account
through the network

Blockchain mining is a peer to peer procaess

Blockchain mining is used to verity transactions on the network

Transacticon details
Transaction initiated broadcasted to miners

Ethereum Mining Process

Mining is completed
and miner gets reward

Transacton in added
Transaction complete to the blockchain

Ethereum
Process Overview in
Fig. 4.4.1: Mining 5 ethers for each
expensive, miners
receive a reward of around
Because s process uses electricity, which is
an

block they mine.


functions much the
same way in both networks,
Ethereum, and it
d core component of both Bitcoin and
With
with a few
exceptions. publishing and
propagating blocks in the Blockchain.

Mining also the


Secures network by creating, verifying,
process
New blocks
resource-intensive
a
dre added to the blockchain through mining,

Tech
Blockchain (MU) 4 6 Public Blockchain
Blocks are made up of transactions that are added to the blockchain after being verified by the mining process hu
mining nodes.
Mining protects the network by ensuring that only legitimate blocks containing valid transactions are permitted
on
the Blockchain.
After a block is accepted into the chain, it cannot be modified, and miners safeguard the network by permitting

only legitimate transactions in their proposed block.


This method uses a lot of energy to make sure that miners have used all the resources necessary for a block to be
approved.
One new block is produced (mined) roughly every ten minutes.

The Ethereum Mining Algorithm


The Ethereum mining algorithm is no longer based on the proof of work that was employed in Bitcoin. Ethash is

the algorithm used in Proof-of-Work mining.


Instead, Ethereum employs the Casper proof of stake process, which consumes significantly less computational
power while producing the identical results as the more expensive proof of work approach.
Ethereum developers are working on a consensus algorithm known as "Casper
Casper is an economic consensus protocol based on security deposits.
Bonded validators put up a security deposit in order to contribute to consensus by proposing and creating blocks

A group of bonded validators exists. A validator is a user who helps with the mining process by verifying
transactions and producing blocks.
By staking a quantity of ether, a user can participate and become a validator in the set. The security deposit must
be a small amount of ether.
Bonding is the deposit of a stake. After the deposit, the user becomes a bound validator.
A list of validators is constructed from the set of bonded validators for each block.
The list is chosen pseudo-randomly., with the randomness weighted by the initial stake put by a validator.
Thus, if a validator deposits 10% of the total stake, he has a 10% chance of being picked to propose the next block.
The first validator is permitted to propose a block from this priority list. If the first validator does not react or does
not respond within a certain length of time, the next validator on the list may propose a block, and so on.

4.5 Ethereum Virtual Machine (EVM)


Before Ethereum, blockchain apps could only be created to do a small number of tasks.

The only purpose for which crypto currencies were intended was to function as peer-to-peer digital currencies.

This presented a challenge for programmers since they either had to increase the scope of operations that the
crypto currencies could do, which would be difficult and time-consuming, or they could create a new class
blockchain-based platform and programmes.

The EVM is a cutting-edge strategy created by the Ethereum creator.

The Ethereum virtual machine is the engine in which transaction code gets executed.

The Ethereum Virtual Machine (EVM) is a global computer that anybody may utilize for a nominal fee paia
cryptocurrency.
BTechkanouledge
Blockchain (MU) 4-7 Public Blockchain

Cshereum smart contracts are sets of computer instructions that are executed on all nodes that have a full
cehereum client installed. The portion of Ethereum that executes smart contract instructions is known as the EVM.
VM may simply be viewed as a system created to work as a runtime environment for smart contracts based on
EVM

cechereum. This is where all your smart contracts are executed.


Solidity Code

Ethereum Compiler

EVM Bytecode EVM Bylecode

Ethereum Virtual Machine

Block 1 Block 2 || Block 3 Block 4

Fig. 4.5.1

Every Ethereum node runs EVM.

. I t is a virtual machine similar to the JVM used by Java.


An Ethereum node runs EVM and runs applications based on a giobal consensus mechanism. This EVM has its
microkernel, stack, memory and storage.
Smart contracts are represented at a basic level by Ethereum Bytecode, which is read by the EVM.
The bytecode for Ethereum is an assembly language made up of several opcodes. On the Ethereum blockchain,
each opcode carries out a specific operation.
I t i s Turing-complete software that runs on the Ethereum network and enables anybody, given enough memory
and time, to run any program they choose, independent of the programming language it was created in.

The EVM streamlines and improves the process of developing blockchain-based apps.
The EVM makes it possible to construct hundreds of distinct apps on a single platform rather than having to create
a
unique blockchain for each application.
i s completely isolated and has no access to file systems or processes. So, each node in the system runs the EVM.

Ihat way it can maintain a consensus across the network.

When we install and launch the geth, parity, or any other client, the EVM is launched and begins synchronizing,
veriying, and executing transactions.

Transaction and Accounts


4.6.1 Transaction
What is a
Transaction?
OCKchain's basic building block is a transaction. Currency is transferred from one address to another during a

transaction.
A tran serialized,
instructions issued by an externally owned account,
dction is a piece of cryptographically signed
and then
uploaded to a blockchain.
g Tech aeuledge
Blockchain (MU) 4-8 Public Blockcha
On prvate key and contains
Ethereum, a transaction is a data packet that has been digitally signed using a
the
trdctions that, when followed, either lead to a message call or the establishment of a contract.

ased on the output they generate, transactions may be classified into two types

Message all transactions: Simply, this transaction creates a message call that may be used to transfer

messages across accounts.


Contract creation transactions: As the name implies, a new contract is made as a result of these transaction
This indicates that when this transaction is completed successfully, an account Is created with the

corresponding code.
The way the outside world interacts with the Ethereum network is through transactions. As a result, they alter and
update Ethereum state. For example, if Nishad sends Swara 2 ETH, Nishad's account must be debited and Swaras
must be credited. This change of state occurs within a transaction
State s State s 1

Fig. 4.6.1
Any activity. including transferring ether or invoking smart contract functionality, can be considered a transaction
Asa result, the state of the EVM is
updated.
Transactions that alter the EVM's state must be broadcast to everyone on the network. Any node may broadcast a
request to conduct a transaction on the EVM;
A miner will then carry out the transaction and communicate the
ensuing state change to the rest of the network
when this has occurred.
In order for transaction to be acceptable, it must be mined and cost a fee. A
a
gas limit and a gas charge are
applied to each transaction. For confirming (or mining) that transaction, miners are compensated with this fee.
Now we have a basic understanding of what a transaction is, what it is used for. Let's understand in detail the fields
that are included in these transactions.

Transaction Components

recipient
value

nonce

signature
data

AF gasLimit

. maxPriorityFeePerGas
maxFeePerGas

Fig. 4.6.2
Blockchain (MU)
4-9
Nonce:A nce
nond is a
unique number Public Blockchain
that is
required for every
single
re of a transaction. For an
externally owned account, this transaction. It is a number
unt, For number is the number of showing the
the a contract account, it is the number of transactions
contracts created by the sent from
message replay. account. It is used to
prevent
ent:The recipient
Reci of the transaction can either be an
tcontract. Whenever the externally owned
recipient is another externally owned account (individual human) or a
o r of value from one account to another
tra
account, then the transaction
is simply
account. When the a

going to trigger the code in the contract to


recipient is a contract account, that
run or execute. transaction is
cacPrice :
representing the fee the sender is willing to pay for gas (in wei)
GasLimit: The maximum amount of gas the sender is
willing to buy for this transaction
Signature: Digital signature. A signature identifying the sender
INIT: Init is used only in transactions that are intended to
create contracts. This is
defines the EVM code to be utilized in the account initialization
an unlimited byte array that
procedure.
The main "payload" of a transaction is contained in two fields: value and data.
Data and value can both be
present in a transaction, but they canalso be absent. A
payment is a single-value transaction. A data-only
transaction is referred to as an invocation. Both a payment and aninvocation are
includes value and data.
parts of a transaction that

Value : The amount of ether that you want to send to the recipient.(in ETH or in WE)
DATA:Data that can be sent. This field is optional and can be left blank.
4.6.2 Accounts

A crucial part of the Ethereum system is an account.


tis the primary component and has an ether (ETH) balance.
A user's account can transmit transactions through the Ethereum network
Iransactions are produced by the interactions between several accounts and are kept in the distributed database.

Sender, recipient, and contract accounts are all involved in every transaction.

An account the Ethereum


can be managed by a user or by a programme running on
network
Ethereum accounts are divided into two types:
0Externally owned accounts (EOA)
Contract accounts
Externally owned accounts (EOA):
and the contract accounts are controlled by their contract code.
sControlled via private keys from a user

EOA. This is the type of account that is owned by people on

Externally Owned Account" is referred to as

the Ethereum network.


The name or any
A once the user creates one on Ethereum.
account
private key pair is produced for an

account.
Personal information of the user does not identify the
Tech Knoutedga
Publitat iua
Blockchain (MU) 4-10 Public Blockchain
What is Externally Owned Account ?

Externally Owned
Accounts

nonce balance codeHash|| storageRoot

Fig.4.6.3: Externally Owned Account


Externally owned accounts do not contain code; it has balance in ether and can send messages by generating and
signing a transaction.
It is used for holding., sending and receiving ETH and for interacting with smart contracts like deployment and
calling functions etc.
Access and control over one's contracts and assets are provided through the EOA private key. The user maintains
security for the private key.
Although, as the name indicates, the account's public key is accessible. The identity of the account is represented
by this key. Through the use of a one-way cryptographic function, the public key is created from the private key.
f you register for an Ethereum account, you will keep the private key to yourself while sharing the public key.
Public keys are used for account-to-account transactions. An Ethereum account's public key is what creates the
account's address.
Other externally owned accounts and contract accounts can communicate with this kind of account.

Contract Accounts:
A contract account has a code for a smart contract.

This account doesn't have a public or private key; the public address of the contract account is used to identity it
Private keys are not owned by this account.
What is Contract Account ?

Contract account

<code
<code>
<Code>

nonce
balance l codeHash||storageRoot
Fig. 4.6.4: Contract Account
B Tech neuledr
Pu bIira""
Blockchain (MU) 4 11 Public Blockchain

to run and state variables are present in this code.


Functions

is managed by the smart con act's logic. The owner of the contract's account is the smart contract
Thisaccount on the Ethereum blockchain,
that is
implemented
The code for the contract is executed on the Ethereum virtual machine when an externally owned account begins a
with a contract account.
transaction
when a contract account receives a message. it activates its code. This might imply that it reads and writes to its
or generates
storage, transmits messages,
new contracts.

In addition to ether, the transaction also contains information on which functions should be executed and what
arquments should be sent to those functions
There are four fields in thee account state nonce, balance, storageroot, and code

o Nonce- The nonce senves as a counter, ensuring that each transaction is only completed once.
oThe current ether balance - The amount of ether the user presently holds. (in wei)

Codehash or Contract code If the account is EOA this field is empty. This field includes the code that will
be done when a message is sent to the account if the account is a contract account. This is immutable EVM
bytrecode.
Storage- The storage is initially empty, but it may be filled and read from through transactions and contract
codes. (only for contract account)

Externally Owned Account Contract Account


Owned by some external entity (person, corporation etc) Owned by contract
This account does not have a code. A code is assigned to each contract account.

A transaction
account with another
can be initiated by an externally owned But contract account cannot
initiate transactions.
externally owned account or aa
contract account.

ernaly owned accounts have a private key associated Contract accounts do not have a private key
with them

is free to open an externally owned account. It costs money to set up a contract account.
ne
only type of transaction that may occur between two Any type of transaction with a contract account is
EOAS is the transfer
of ether. permitted, including9 deploying or invoking the
functionality of other contracts.

47Architecture and Workflow


In the
decentralized wor
vorld, Ethereum is sometimes referred to as the world computer.
ADapr
a blockchain-based application or service that allows direct contact between users and suppliers, such as
king buyersand sellers in a
ADApp, like
decentralized marketplace
a centralized application, typically consists of a decentralized backend that operates on the blockchain

dd a
centralized frontend that allows end users to access their walets and perform transactions

ecmesk
puuos puayoee8
se ujeyoyoja
J L
Blockchain(MU) 4 13 Public Blockchain
a result, the community has devised methods (hosted blockchain servers, metamask etc.) that allow you to
wasting a lot of hard drive and RAM
4
avoid
downloading and operating a full copy of the blockchain while
the decentralized component.
maintaining
So, essence, the blockchain stores your data, stores the code, and executes the code in the EVM.

To create web-based Dapps, Ethereum has a useful JavaScript library called web3.js that connects to your
blockchain node.

Now. the next question is where the smart contract


actually fit into the Ethereum blockchain
architecture?
tf we are using Remix and writing some solidity contracts, and then we deploy those contracts to the blockchain.
Where do they actually go? Let's discuss this.
Workflow:

1 Write smart contract in solidity

2 Use Interactive Development Environment (1DE), Remix to create smart contract code.
3. This smart contract is going to get processed by miners included in a block and then distributed to the Ethereum
network.

4. In Ethereum, node has to do with mining, so miners execute proof-of-work in order to find a hash and miners are
also going to publish any new blocks.

5. Once a miner finds a new block, all those transactions get published and that's
going to be fed into the state
transition.

FULL NODDE
Remix
Ethereum Virtual Machine EVM Interactive Development
geth Environment Server
parity
IDE
Compute STATE
state Dbalance AWS
transition storage
sImart contract|

Veffsol
Smart Contract
Find a proof of work ethash
Publish new blocks -GPUs Metamask
Plagma solidity
contract left (
Wallet
balance it

Transactions from the network

Block CHAIN WEB

Fig. 4.7.3: Workflow of Ethereum


6. The
n i n g inside Ethereum is going to be called the state and the state just represents to date what is

7.
nappening on the Ethereum network.
nside the state
wehave a balance of all the user accounts and, storage.

E edKneuledga
Blockchain (MU) 4-14 Public Blockchain
8 Next is how we decide on what those contracts do, how do we decide on all of the state updates. So compute stay
state
transition.
9. So, at this stage, smart contract is in the state-transition and it will actually end up in storage.

10. The state inside of Ethereum gets a special name, Ethereum Virtual Machine.
11. So EVM processes the computation and then also needs to update the state which involves the storage.

12. Now Metamask come in. So, if we are interacting through remix with Metamask, then it a wallet to store
your
private keys.
13 So, both the contracts that are created and the transactions from any wallets come in and are processed by the

miners.

14. The last step is server, wallets are usually apps either on a smartphone or on the desktop. And the remix was also

hosted by somebody.

15. So you can see in the diagram, the server is hosting Remix and also hosting Metamask.
16 In the diagram, the full node from Ethereum is the blockchain part and then IDE, wallet, server. These are all on the
web. And the smart contract is both, ie. are going to be deployed on the web in order to get into the virtual
machine.
Summary of workflow

Use IDE to program a solidity smart contract.

Smart contract gets deployed and deployment gets picked up by miners.

Miners are using PoW in order to find a new block.

Once this happens, transactions get packaged into a new block and transactions get computed by the state
machine transition.

If necessary, the contract gets stored and the account balances get updated by the state.

Once all the transactions in the block have been processed, then we need to contact the miners and pick up any
AEw transactions from new blocks.

4.8 Comparison between Bitcoin and Ethereum


Bitcoin Ethereum
In Bitcoin SHA-256 is used in the algorithm of the | In Ethereum, Keccak-256 or Keccak-512 are used.
Blockchain Keccak is a variant of SHA3.

Assets Bitcoin Assets Ether

Bitcoin is exclusively used as an online currency. Ethereum is often used as an online currency, howevE
ed
its blockchain is also utilized for
decentra
applications such as voting systems, file storage, a
so on.

Data related to Bitcoin network transactions is frequently On the Ethereum network, for example, transactions
ns

utilized simply to keep track of transactions. may include executable code.


ed

TechKa
Putiit 4iT"
Blockchain (MU) 4-15 Public Blockchain

Bitcoin Ethereum
Simple a n d r o b u s t
Complex and feature-rich

ain Consumes much more energy than Ethereum. Ethereum is certainly consuming an increasing
Bitcoin

amount of energy, but this will likely decrease


Significantly after it has transitioned to Proof-of-Stake.

reak based primitive scripting language, not Turing-


Stack Turing-complete scripting language
complete

Key lengths Key lengths


Public key = 512 bits (compressed: 257 bits) Private key = Public key = 512 bits

256 bits Private key 256 bits


Address 160bits

Mining Proof-of-work Mining Proof-of-Work to Proof-of-Stake

Signature size 512 bits (64 bytes) Signature size 520 bits (65 bytes)

Energy consumption 3, 2 million households Energyconsumption 1, 1 million households

Transaction time Bitcoin is known for its slow and Transaction time Ethereum transaction takes only 12
expensive transactions. It takes around 10 mins to seconds.
complete a Bitcoin transactions.

Block time 10 minutess Block time 12 seconds

Mining reward 12,5 Bitcoin per block Mining reward 3 Ether plus some other rewards

Consensus time 1 hour Consensus time 3 minutes

4.9
ypes of test-networks used in Ethereum
A Version o f a p r o j e c t is d e p l o y e d t o a n Ethereum Test Network ("testnet"), which replicates Ethereum, b e f o r e it is

unched on the Ethereum blockchain (or before modifications are made to the blockchain itself).

allows developers and the communityto test the project before actual assets are engaged.

atestnet, ether and tokens are simple to get and have no real-world value
e are presently three testnets in use, and each performs identically to the main blockchain where you're real
Ether and tokens
reside.
Ropsten
OPSten test network is an Ethereum Proof-of-Work testnet. One can mine on the Ropsten network to obtain
ETH

TechP Knouledg
TG n
Blockchain (MU) 4 16 Public Blockchain
Kovan
h e Parity team created the Kovan test network as a Proof-of-Authority testnet for Ethereum.

Rinkeby
The Rinkeby test network is an Ethereum Proof-of-Authority testnet that was founded by the Geth team, At

Rinkeby, one may obtain ETH by requesting it through a faucet.

Making a connection to a testnet


Ethereum addresses and private keys that operate on Ethereum work on each testhet

Create a new wallet specifically for use on testnets.

Network V
Main Ethereu

Neto
acons is Mar
Man 2he

34356 ETH
KovantTestNerwork

O CustomRPC
tontracr teraCtON OETH

e118 1/t7/2019 at 23.12

Approve -0 ETH
$0 e0 uSOD

116 1/1/2019 at 20 49

Fig. 4.9.1 : Metamask Plugin

Using MetaMask to transmit Ether and tokens on a testnet is simple; simply choose an Ethereum network in te
top-left corner of MetaMask.

When you switch from the Main Ethereum Network to Rinkeby or another testnet, your balance and transacu
history should change to reflect the network you've chosen.

When you make a transaction in MetaMask, it will now be sent to the


network you specify.
Tec Knendedge
Pubiil
Blockchain (MU) 4 17 Public Hlockehain

10
1.10
Transferring Ethers using Metamask
lots are basically software that allows users to connect to the Ethereum.

AWallet is a lightweignt node that connects to a blockchain to conduct basic activities like transferring and

receiving bitcoin.

tet's discuss how to transfer ethers using Metamask

Download metamask first.

> Web Store -> Metamask


Go to chrome apps

**
M
4m r

Extension

aya
Metaas

METAMAS 1.437 m.aapy

MetaMank Fosk DEVELOPMENT BMLD

Aorn Etenun Mels'Maus

MetaMask
tp imetam ath 1 featured

PVacY practico Helalo

o
now Ethereum wallet is in your browser.

feh Kueuledg
Blockchain (MU) 4 18 Public Blockchain

Welcome to MetuMusk

C*e u te Ethe-eum and tha Docentlae

We can see Welcome to Metamask browser


on connecting us to Ethereum and the decentralized web. Lets go
ahead and get started

METAMASK

New to MetaMask?

We don't have one existing wallet yet, this is first time


our setting up so I am going to click Create a Wallet.
TA*K

Help us improve MetaMosk

Click on I Agree.

ETA ASK
Creote Password

Tec nouledge
Puti
Blockchain(MU 4-19 Public Blockchain

t to sset
to a password to protect your account. Click on Create.
you
Asking

2ETaRASv
Secure Your wallet
acae

Watch this video containing information about Secret Recovery Phrase, how to save secret recovery phrase. Click

on Next

PEIARASE
s bk

***
Secret Recovery
Phrase

s to,a, r:7-"2

account. Click Next.


makes it easy to back up and restore your
t explains Your Secret Recovery Phrase

METARASK

OETH
S

friend and family.


And this and send it to
done. We can see Account no. We
can copy

TecaPubKeeuledgi
atlen
Blockchain (MU) 4 20 Public Blockchain
MEAMASK

ral

OETH

If you click on Ethereum Mainnet, we can see that we are connected to the main Ethereum network. Ethereum
Mainnet is like the network, it's the actual Ethereum network where ether is worth real
our
money
Click on show networks and choose Rinkeby Test Network.

METARABK

****

OETH

wwmaanveneonaanono

Reason for choosing Rinkeby Test Network is, if we do test and deploy of smart contract on Mainnet, transaction
fees are pretty high in main network and its very expensive for the development so we are using the test network where
we will get ether free more or less.

If we switch between networks, our account no will be same across all the networks.
MetaMask| chuome extesion/fnkbihbeogaesoelefnkodbefgngknn/homehtmie

RETARASK

ORinkebyETH

e c a
Nneedled

P o b i l f d l l "
Blockchain (MU) 4-21

M n e e d to get some ether in our account to send transactions, deploy smat ontrnt arnt nd

0 ETH.
showing
2s

We will u
utilise a servicecalled faucets, which is an Ethereum faucet and a devekyer taw ota etw
Ain order to test and debug your decentralised application or protocol betore gong me on the ttheem n
must be used.
where
actual Ether

Nost faucets require social authentication (e.g. Twitter post or login confirming yu are a rnal Nman) ne I

wait for a testnet token through the faucet


n& Queue to
Go to Google and type rinkeby faucet and choose Faucets | Chainlink https//Mauets chas n
C w z dwlink

AR Hog sinetivn tor rCun 2002 thR

Request testnet LINK

Now we need account no, So click on Connect Wallet and choose Metamask

Connect your wallet

Stay updated on the latest fron


Click on
Next and will
get following screen
Blockchain (MU) 22 Public Blockchain
Request testnet LINK
Gel testet LINA for anm actant on one of the upported blockchain

e s e T SO o can rreare ond tevu ynu mn Dracda and 'hanlinke


a t cottact LAarr more

t e d te Qweun , ee pou are requeating hereum inhaby LNITH. I e d teefne tahens for a ehwe

**

Uncheck 20 test Link and click on Send request. It will take 10-15 seconds for Token transferred.

Request testnet LlNK

Requestcamplete

And we are getting message Request complete. Click on Close.

Now will go to Metamask account and we can see, I have 0.1 ETH in my account.

CMerdaki dheoee etesionilrbnhteogenoetetrkodbelgognwhomehunie


METAMASK

inkebyETH
ACTiWT

If we on click Activity tab, it will show our transaction history.

ecoaldpe
Pudin l n be hain

NETARAN
**p

0.1 RinkebyllTH

Ae

how to send ethers ?


Now
we will discuss
Send button.
Click on auaa
Mdafan etuuewtwIAWAtMRNNwwlenn@wfhwyhin htrdpit

NETANAN

Ap

ut sender public address and the amount of ether to transfer and click on Next

MkhibwKJhewdkaelbofopgntVIwer Iti¢On#
U MetaAas h t e eathn

YAMASR

Ara

will show
gas fee and click on Confirm.

loc neubedgs
Blockchain (MU) 4-24 Public Blockchain

TARASK

C.05 RinkebyETH

We can see 0.05 ETH transferred to the mentioned address.

4.11 Mist Wallet

Mist is sometimes known wallet,


as a a phrase derived from Bitcoin jargon.
The Ethereum Mist wallet is Ethereum's official blockchain wallet where we can hold our Ethereum assets.

The Ethereum mist wallet was launched in 2017.

This wallet was created by the team behind the Ethereum foundation so that it can run decentralized applications
and blockchain applications.

The mist is a blockchain-based browser that serves as a platform for operating blockchain networks and
decentralized applications.

Mist wallet is compatible with Linux, Windows, and macOS.

This wallet saves your private key on your computer and not on third party servers like some wallets.

The wallet can also be used to hold other tokens issued on the Ethereum platform. In addition, it supports over 16
languages. This makes it a go-to-wallet for users from non-English speaking places

Currently the Ethereum wallet is only available for desktop.

Unlike many other wallets, the Ethereum Mist Wallet can be a bit challenging to use. Users can choose from
alternatives such as Trust Wallet. These wallets are close competitors that are even available on mobile. Other
competitors include Metamask and MyCrypto.

This wallet has been discontinued from March 2019.

4.12 Ethereum Frameworks


Frameworks may be used to make the creation of Ethereum smart contracts easier.
The frameworks discussed in this section can automate some
processes and simplify development.
1. Truffle

For blockchains that use the Ethereum Virtual Machine (EVM), Truffle provides a top-tier development
environment, testing framework, and asset pipeline.
It's a platform for developing decentralized apps on the Ethereum blockchain.

Technewledg
Blockchain (MU) 4-25 Public Blockchain
It is the most well-known and innovative framework.
Due to its configuration being user-friendly for
new to DApp development.
beginners, Truffle is likely to be your first contact if you are

Themajority of other frameworks adopted Truffle's


approach.
Additionally, it is interoperable with other blockchains that
support earned value management and
compatible EVM blockchains, like Binance Smart Chain,
Hyperledger, Polygon, and others.
The languages Solidity and Vyper are also supported.
Website: https://truffleframework.com
O Documentation: https://truffleframework.com/docs
O npm package repository:
https://www.npmjs.com/package/truffle
Truffleinstallation:
Nodejs must be set up on your computer before you can start. Installing is simple; just enter the
command in your project:
following

s npm install-g truffle


Initialize Truffle in your project after that:

Struffle init

feverything goes well, you should observe the following:


Starting init...

Copying project files to


Users/Desktop/Projects/dapp-truffle
Init successful, sweet!

y our scaffold
commands to get started:
truffle create contr YourContractName #scaffold acontract
Strufle create test
YourTestName # scaffold a test

he project structure is as follows:


Sdapp-truffle Is-1
contracts
migrations
test

trufle-configjs Tec Leatedgi


Public Blockchain
Blockchain (MU) 4-26

The Truffle network


dddition to acting as a local development blockchain for testing, Truffle provides a development networkwhers

to be deployed to the mainnet.


DAPps may operate and be tested without having
advance network contigurations:
Tne
truttle-configjs file, the network object comes with development and

networks:{
development: {
host: "127.0.0.1
port:8545,
network id: "*",// match any network
websockets: true

live:{
host: "178.25.19.88", // Random 1IP for example purposes (do not use

port: 80,
network id: 1, //Ethereum public network

network where you the following command:


The development configuration is the default run

$ truffle migrate -network


To compile your smart contracts, use the command below

truffle compile
2. Embark

Another framework for the EVM blockchain, known as a full-stack framework, is Embark.

provides method for simultaneously developing the front end and back
This indicates that the framework a

end of a decentralized application.


Your frontend (HTML and JavaScript) code and Solidity smart contracts are monitored by Embark for updates
then redeployed to the blockchain network.
and they are
GitHub: https://github.com/embark-framework/embark/

Documentation: https://embark.status.im/docs/

npm package repository: https://www.npmjs.com/package/embark

Embark installation

Ensure that Nodejs is set up on your machine before installing Embark.

You must also have the following installed in order to use Embark:

The Ethereum Cient, which offers a blockchain network to test our application on, and

3ETechdnewledg
Blockchain (MU)
4-27
C
IPFS which enables decentralized file Public Blockchain
storage. Even if they are
It's really simple to install Embark: optional, installing them is still advised.
install embark
Snpm -g
Refore using Embark, we must first perform the aforementioned command:
Sembark demo

$cd embark_demo

Ry doing this, a scaffold application is created with


every
necessary folder
With that in mind, you launch the
programme to launch the 1PFS and Ethereum
Veeo in mind that Embark
nodes.
monitors your code for
$embark run
changes before redeploying:
3. OpenZeppelin
A toolkit called OpenZepplin has plugins that make the creation of smart
contracts faster.
o Website: https://openzeppelin.org/
Documentation: https://openzeppelin.org/api/docs/open-zeppelin.html
Any of the Open~eppelin smart contracts must be
imported into your own smart contract before you may utilize
them.

OpenZeppelin is an open framework for safe, reusable smart contracts written in the
Solidity programming
anguage.
Nodejs has to be installed first.
OpenZeppelin installation
To install OpenZeppelin, use the following command:

Snpm install@openzeppelin/cli
To set up OpenZeppelin project,
an use
the following:
Snpx openzeppelin init
We must build the following code using an example smart contract from OpenZeppelin's documentation, which is
shown below:
I/ contracts/Counter.sol
pragma solidity ^0.5.0;

contract Counter {
uint256 public value;

function increase) public {


value++;

TechPudtiratons
nouledgs
Blockchain (MU) 4-28 Public Blockchain
To compile, run the following :
$ oz compile
The OpenZeppelin network
Our smart contract's
deployment is as simple as their compilation,
Ganache is a network used by OpenZeppelin where a local blockchain may be created.
If you don't
already have it, you should instal
Ganache
S npm install ganache-cli
Run the following commands to launch a new process:
S npx ganache-cli --deterministic
Then, deploy the smart contracts:
S npx oz deploy
Compiled contracts with solc 0.5.9 (commit.e560f70d)
? Choose the kind of
deployment: upgradeable
? Pick a network:
development
? Pick a contract to instantiate: Counter
Added contract Counter
Contract Counter deployed
? Call a function to initialize the instance after creating it?: No
Setting everything up to create contract instances
Instance created at
OxCfEB869F69431e42cdB54A4F4f105C19C080A601
The best framework to choose for your DApp project is to understand what you want to build and what necessary
toolkit you need.
1. Brownie Python-based development environment and testing framework.
Documentation https://eth-brownie.readthedocs.io/en/latest/
4.13 Case study of Ganache for Ethereum Blockchain
GanacheA Local Test Blockchain

Ganache is a public Ethereum blockchain that you can use to perform tests, send orders, and check the
C
state while keeping complete control over it.

Ganache is a local test blockchain on which we may deploy contracts, create apps, and
It is offered for Windows, macOS, and Linux
perform tests.
as a
desktop programme (with a graphical user interface).
The ganache-cli command-line tool is another way to access it.
Ganache desktop application, see
https://truffleframework.com/ganache.
The ganache-cli code can be found at
https://github.com/trufflesuite/ganache-cli.
Tech Hnouled
Pubta
U !.!.. !... !.
i
Blockchain (MU) 4-30
Public Blockchain
The Pizza Store

There are following components in this application.


and
O
Smartcontract Provides immutable contracts that are secure strong
Customers Can orders pizza
o Pizza store deploys and owns the contract

There are several functions implemented.


o Send_order, Check_order, Send_Invoice, Order_delivered and the events triggered are Invoice_sent

Order_sent, Order_delivered
First and foremost, let us define variables and structs. Essentially, we need pizza store and customer addresses, as

well as order and invoice structs.


We require order and invoice lists, thus we utilise mapping in Solidity
Write the events are triggered for the activities.

Write the functions to provide order delivery, safe payment and get invoice.
After creating the project and launching ganache, which offers a local Ethereum blockchain network, smat
contract can be deployed using truffle with the following command:
truffle migrate -reset
truffle test

4.14 Exploring Etherscan.io, and Ether Block Structure

4.14.1 Etherscan.io
As we discovered in earlier lessons, blockchain transactions are transparent, anybody can view them and/or
confirm them, and everyone may check trade history.
But how does one really go about doing all of this?
Thanks to Etherscan, any Ethereum network users may quickly learn al of this information and more.

What is Etherscan and how does it work?

For Ethereum. a decentralised platform for smart contracts, Etherscan is the top Blockchain Explorer, Search, APL
and Analytics Platform.

ETHERSCAN
The Lthereum Btocktxplorer

It is built and launched in 2015

We may search through transactions, blocks, wallet addresses, smart contracts, and other on-chain data using the
etherscan.io website.

To identify and verify Ethereum blockchain transactions, it effectively serves as a search engine.
edknededgs
"" 4tioB *

P#D
Blockchain (MU)
4-31 Public Blockchain
Additionally, it can help in the
communication with smart contracts and the
conduct.
identification of any suspiCioUs

shohort, Etherscan.io monitors transactions on the Ethereum network, indexes


them, and makes them available on
the website
Several people came together to develop Etherscan.io as a totally free resource to help the general public learn
more about Ethereum.

tt is independent of the
Ethereum Foundation and is run
independently.
Our objective is to enable Blockchain transparency by indexing and making searchable all Ethereum Blockchain
transactions in the most transparent and accessible way possible," the team explains.
It's important to understand that Etherscan is a data source rather than a wallet.
One of the most well-liked tools for learning how to use the fundamental blockchain features is Etherscan. Most of
the features of this website can be used without registering or connecting to our wallet.

For instance, using a hash, we can confirm any activity associated with this transaction, whether it involves smart
contracts, tokens, or anything else.

We don't need to register for this, but it could be required to do so if a user wants to access certain further
features.

Then, how does it manage to do all of this ?

This tool has several functions.

1 Findinga transaction or wallet is one of Etherscan's primary purposes.


Think about sending 0.0315950222 ETH ($33.28) to the public address 0x3f1d77a0d99elea4f3c5330fd2ac
1449af27e132. Obviously, we have also paid a transaction charge of 0.0005132052 Ether ($0.54) in addition to
paying.
Once the transaction is done, our wallet will show us the hash Ox87c6085f4e4240701dcdebeb
741334049962828872b82ee7a63bf801da38dac3
Let's now say that we want to check how many confirmations our transaction has received in order to
determine whether it was completed successfully
To begin, navigate to the Etherscan homepage and use the search bar at the top of the screen.

Btherscan

The Ethereum Blockchain Explorer


Earn 60%APY
whie you sieep
Fer AAN
Featured Hde bersacsios a t n g takers tgged shaving

Tokan igmaro List


poor repion t h

$1.052 45 4
162531 7 e

we enter the transaction's hash there, which would be x87c6085f4e4240701dcdebeb741334049962828872b82

the search button.


E/a63bf801da 38dac3 and then dlick on

Tech4 Dnededgi
It atiea
Blockchain (MU) 4-32 Public Blocutan
e r completing these few steps, we will be able to see all the specifics of the transaction we just madde.

herscan

Trarsai n Delas

C s

Imye'v,:0rrta

We'll observe that there is a "see more" option available.

**

By choosing that button, we can view further information about the transaction, including its hash, status, bloc
timestamp, wallet from which it was produced, wallet to which it was sent, transaction value, commission paid. gas
price, and kind of TXN

Bi C arris

Piye

eudedgs

TecA
Blockchain (MU)
4-33 Public Blockchain
e ill be quite simple to confirm the transaction's status
with the use of this data.
1 we still want to look into
something more, the
connected to that address.
receiving ddress may be used to examine all transactions

How can 1 use Etherscan to look for smart contracts?

Knowing that Etherscan is a useful tool to


analyse smart contracts is
important if you are a user who often engages
with decentralised applications.
In this manner, you may ensure that your
money is sent to the
appropriate smart contract.
Suppose you need to transfer tokens to your wallet and you need to locate the token's contract address.

Token logic in smart contract addresses involves, among other things, how transfers are carried out.

Finding the address of the token in question is the first step. You may find this address at
https://etherscan.io/tokens or on the project's official website.
The token address should be copied and pasted into the search the Etherscan main page
area on as a first step.

The Eth m siockchain Expioror

**

**************

After clicking the search button, we will see the contract's specifics, such as the balance, as well as more basic facts,
including the value and the location of the original contract
wwwwwwwwww
w wwwwwwwwwwwwwwwwwwww.

Kes

The "see more" option is available as usual, and it includes the transactions, the smart contract, and a comments
aea. The "contract" option may be seen if we check up above.

here are choices for interacting with the contract and its regulations. The general details of the contract are

àvailable in the "see contract" box.

Tech Kemledgi
Blockchain (MU) 4-34 Public Blockchain

Bhercan

60% APY while you sleep


AAX Earn

we may access choices like checking the balance of particular wallets that enable us to utilize that token.

This is a highly comprehensive tool to analyze the Ethereum blockchain, as we can see.

In addition to theaforementioned features, the network allows us to search for airdrops, check gas prices, and do
countless other operations.
Also available is token
analytics, if that's what
you're looking for. Etherscan displays the most popular tokens for
each standard, since Ethereum supports both ERC-20 and ERC-721. In addition, all Ethereum
smart contracts with
validated source code are included in the Verified Contracts section.

4.14.2 Ether Block Structure

The Block is the basic


building block of a blockchain that stores transactions.
Every block in a blockchain will have a blog header and multiple transactions which we have already covered in
previous modules.
Ethereum is progressively switching from its current Proof-of-Work consensus process to
Proof-of-Stake.
Since Proof-of-Work consumes too much power, it is not
environmentally beneficial.
Proof-of-Stake is quicker than Proof-of-Work and may mine blocks
Each Ethereum block contains a number of
according to how much money the miner has.
significant pieces of
information, including the difficulty,
preceding block hash, and Merkle tree-based root hash. timestamg
What's In A Block ?

Ethereum Block header

parentHash|| nonce timestamp ommersHashj


number gasLimit gasUsed mixHash
beneficiary logsBloom dufficulty extraData

Timestamp: Timestamp represents the


time when block mining ends.
Block Number: counting how many blocks there
are. The
number increases in
Difficuty : The value of dificulty indicates how steps. A genesis block is zer
challenging
it is to locate a hash. The
effort required to mine tneblock
Teca Knouted
Public Blockchain
Blockchain (MU) 4 35

confirms that
unique identifier for that block./ A 256-bit hash that, when paired with the nonce,
niHash :a
work has been completed.
enough computational
hash stored in the previous block.
ParentHash: 8lock
reward and transaction fee destination address
Beneficiary: Block
data related to this block. Can be left empty
BxtraData:A 32-byte aray containing
the total quantity of gas utilized in all transactions in this block.
GasUsed: Indicates
that may be spent per block.
GasLimit: The current maximum amount of gas

Review Questions

Ethereum and components


of Ethereum.
a.1 Explain
Ethereum? Explain mining process in detail.
Q.2 What is mining in
Virtual Machine (EVM).
Short note on Ethereum
a.3
transactions.
Short note on Ethereum
a4
Ethereum and its types.
accounts in
Q.5 Explain
accounts.
EOA and Contract
Differentiate between
Q.6
architecture.
Ethereum
Q.7 Explain
and Ethereum.
Q.8 Compare Bitcoin
Ethereum.
networks in
Short note on test
Q9
Metamask.
Ethers using
a.10 Explain how to transfer

Q.11 Short note on Mist wallet.


frameworks
Ethereum
12 Explain ditferent
Ganache.
using
13 Explain any one application
l : 'ODU LE
5 -.:t PRIVATE BLOCKCHAIN

sta te Machine
Contract in a Private Environment,
Introduction, Key charact eristics, Need of Private Blockchain, Smart
and RAFT, Byzantine Faults: Byzantine Fault
Replication. Consen sus Algorithms for Private Blockchain - PAXOS
Tolerant( BFT) and Practical BFT
Fabric, Comparison between Hyperledger Fabric &
Introdu ction to Hyperfedger, Tools and Frameworks, Hyperledger
Other Techno logies
MSP, Chain Codes, Transaction Flow, Wor1cing
Hyperfedger Fabr ic Architecture, Components of Hyperledger Fabric:
Chain Manag ement using Hyperledger
of Hyperfedger Fabric, Creatin g Hyperfedger Network, Case Study of Supply

5~1 Introduction

• Private blodcchains are permiss ioned.


re the primar y d istinctio n between public
• Access control~ r more specifically, how you access the blockc hain-a
and private blodch ain.
central adm inistrat or must approv e access before a
• Bec.au.se private blockch ains are permissioned, a third party or
user can access the blockchain.
transactions to a limited numbe r of users or
• Private block.chains restrict read access and the ability to create new
nodes.
k and be able to control who can access
• In private blockchains, a single organization will be in charge of the networ
and join it

• It is, in essence, a partially decentralized system.


cu rren cies on public blockchains. It acts as a vital
• Bitcoin, Ethereum, or Utecoin are common examples of native
eir approval. Private blockchains, on the other hand,
compo nent of the system that reward s individu als for giving th
usua!fy do not.
second .
• In comparison to public block.ch ain, there are more tran sactions per

5.2 Key Characteristics

.
• Complete privacy Private blod«:hain concentrates on privacy issues

• Private 8£ockch ains tend to be more central ized .


on demand can be a huge benefit to the
• Improved Scalability - The flexibili ty to add nodes and services
organization.
M 9\ockcnam l 1•1 u J
,,_
S-2
ui.n h performance and quick tra
,... .., nsactio
' · · ating in the led ger the p ns - When th Priv ate Blockchain
particip ' rf e nodes are d" .. ·b
e ormance is quick
er. ,sln uted locally but there are
Private blockchai ns are easily scalable and fewer nodes
• can process th
Robust arc hite ctu re - In pra ousands of tran
• ctice, private .
net wor sact,ons per second .
are designed to wit hst and any ks currently h
pro blems. They theref . ave one of the most stable
. 1· . . .
preventing ma icious act ivit y. network structures. They
ore include a high I I f
eve o secunt. y mechanisms tha
t aid in
s.3 Need of Private Blockchain

Private Blockchains are inte


• through fine-grained permissio
nde d for business th
n control. es at want gre t
a er control over the ir data and
greater privacy
Furthermore, because the y are
• . .
des ign ed diff ere ntly th d
Businesses interested in these , ey o not have the concep
• . .
sol utio ns which w t of gas fees .
.
Blockchain on the ir ow n priv . ' e can
ate infrastructure. refer to as network participants, freq
uently agree to host
• st
If we want to e ablish channe
ls of communication betwee
need to verify one ano the r's n a few parties who do not trus
transactions, we need private t one another and who
blockchain concepts.
• When a lot of unt rus ted parties
need to work together to solv
e a problem, private blockchain
• Private blockchai ns are und oub is very helpful.
ted ly the technology for you
utmost imp orta nce. if you 're interested in a field where confidentia
lity is of
• It saves a lot of resources.A
private system actually require
s very little attention and is rela
As a result, the y onl y consum tively easy to mainta in.
e a small por tion of the reso
urces available on public bloc
therefore reduce the am oun kchain platforms. You can
t of resources (both financial
and human) required for these
• It empowers ent erp rise compan solutions.
ies .
• It offers very low tran sac tion
al fees.In most cases, a fee
may not even be necessary at
superb jus tific atio n for beg inn all. In actuality, this is a
ing wit h private blockchains.
Furthermore, in many cases, thes
have a native tok en for the net e blockchains do not
wo rk.
• It provides net wo rk reg ula
tion . Actually, without a
. regulatory system, enterpris_
Th f
funct 10n. ere ore, t h e companies _cannot
ere shou Id be a proper way to carry out specific tasks, and
negative effects. As a result, bre aking the rules will have
it guarantees the participants
greater security .
5•4 Smart Contract in a Private
Environment ~
• Wt1h
a smart contract, the term f the agreement between the parties are expressed directly in code or
s o
Programmable log ic using a se ·ng language rather than on pap
• . . genera I- pur po ' high-level programm1 er.
Similar to how bitc oin scr ipts d these types of contracts are ecuted more eas ily in a blockchain
are execute ' ex
system.
• . t
Nevertheless, the bitc oin script nde rstand in comparison o the smart contract scripts .
,r-~ was easy to u

~ tate Machine Replication


• B .
efore discussing state machi.ne . • understand why 1·tis neede?
replication,

We know single server archite
cture. lldl~
P U 111 1 1 I ;'I ( . II n"
• Blockchain (MU)

5-3 Private Blockch .
a1n

Cllen1 Server I(·)

reply l(x)

Fig. 5.5.1
• But there can be a single point failure .

• Here comes the need of state machine replication .

_____,,,.,..- request x

Client J

Fig. 5.5.2
• State machine replication gives safety and liveness by creating replicas of state of servers.

• It is an interactive protocol among servers.

• Replicas maintain the same state

o replicas start in the same state.

o Replicas execute operations in the same order.

• Replicas send replies to clients.

• Clients vote on rep lica replies.

• The replication of state machines assists us in reaching a consensus in a permission model.


• A smart contract does not have to be executed on each node.

• Instead, the chosen subset of the contract executor executes it and propagates it with further nodes to make sure
that all nodes in the network are informed of the contract's state consistently and in real time.

• Consensus is ensured in a permission blockchain context via the distributed state machine replication technique.

■:
Rop11ca~

Fig. 5.5.3
.----.::
~,r.1,c1•-~r.
- - - -- - - -- -- - - - - - - -- - - -- - - - - - - - - - - - - - --=.....
1
~ P 11 Dl • 1 •

Private Blockchain
tf__ BJockchain (MU) 5-4

_.. What is a state machine ?



A state machine executes a sequence of commands.
0

0
Transforms its state and may produce some output.
command s that it has
outputs of the state machines are solely determine d by the initial state and by sequence of

executed.

Server State Maet11oe

Consensus
Module
[ill9

~~wu
0

,_ : : 1 -....___/'
l , Log
: resu ll

•• State
: · Machine
Clients

Fig. 5.5.4

• Typically, replicated logs are used to create replicated state machines.


..
• Upon receiving command s from clients, the server's consensus module adds them to its log
them in log order.
• Whenever command s have been correctly replicated, the state machine on each server executes

• Let us look at a scenario of a replicated state machine.


degree is three .
• We have a number of clients, and services are replicated into three machines. So the replication
to one of the
• We have a consensus module, and when a client wants to issue a command , it sends a command
state machines. The Consensus Module makes an attempt to add these command s to a log .
.-,, .~ ~- ---~
···-·-~=:: r~! ~,-
._. , ;:1 I:=~

.
C 11 .I I .'II
1

Consensus State
Consensus Ma.ch.i ne
MOdule
Module

~~ Lo_
X +- 1

Fig. 5.5.5

• Replicated log ensures state machines execute the same commands in the same order.

• Consensus module guarantees agreemen t on command sequence in the replicated log.

Sun11nary:
a)
Implement service as a determin istic state mach ine

.,..........
b)
Replicate
C) p
rovide all repli cas with the same input
---- ---- ---- ---- ---- ---- ---- ---- --;:;ic;--;:~--:--:-T ll II b I I I J f I 11 11 '-
Priva te Block chain

5- 5 d RAFT
"V' Blockchain (MU)
. Bl kch ain -PA XOS an
5.6 Consensus Algo rith ms for Pravate oc

PAXOS Consensus Algo rithm


_/

S.6.1
989
algor ithm in 1 ·
L. Lamport introduced it as the first consensus ash roble ms. Paxos lets all node s ag ree
on the same
• P
The goal was to select a single value under
the netw ork or er
• and delays.
value desp ite node fa ilures, network failures I The acce ptan ce or rej ectio n of thos e value
s must
.
nodes offer va ues.
By delivering them to the other nodes, certain

be decided by each node. ts and inpu ts can be a prob lem
· · · d f
y of timin g, or er o even
• But concurrent processes and uncertaint
be a majo r concern .
processors, of com mun icatio n chan nels will
And also failure and recovery of machines or

Consensus Problem :
gu ish a fa iled process
s is impo ssibl e to solve in asynchronous systems means it is impo ssibl e to d istin
• Consensu
unsu re whe n it comes to
the rest of the alive processes may stay
from one that is j ust very very slow. Hence
decid ing.
lems . So can we solve the
many impo rtant d istrib uted com putin g prob
• But consensus is impo rtant since it maps to
consensus problem ?
rithm.
is the most popu lar consensus solv ing algo
• Paxos does solve the consensus problem. It
ent proto col know n .
• The only entirely safe and mostly live ag reem
to reach consensus .
• Paxos is a family of distri buted algorithm s used
that is the consensus. The
t. Once a majo rity ag rees on a prop osal,
• We lcnow consensus is agree ing on one resul
by every one.
reached consensus can be eventually know n

• Paxos provides safety and even tual liveness.


value that has b een pro pose d may be h A d I
0 Safety- consensus is not violated. On ly t he c osen . n a so no two
correct nodes choose diffe rent values.

in the f t h .
0
Event ual liveness - If things go well sometime u ure, t ere ,s a good cha nce cons ensu s w ill be reach
ed.
But there is no guarantee.

• Paxos Gene ral approach

o A node or more nodes select a leade r

o An idea is put out by the leade r, who then seek


s supp ort from others.
o Lead er eithe r decla res th
e outcome or tri es again.
Paxos : Types of nodes

• Paxos defines t hree roles .· prop osers, accep to r


s, and learners .
• Prop oser who
, pro pose s value s to reach
consensus.
>
! Blockchaln (MU) 5-6 Private BJockcha jn

Fig. 5.6.1

the consensus and accept the values. The


, Acceptors, who contribu te to reaching the consensus itself; they form
er they hear it from the propose r.
acceptors have the option of acceptin g or rejecting a proposal whenev
which value has been selected by each
, Learners, who learn the agreed upon value. This learner will identify
acceptor and agree to accept it as a group.

So a single node, a single server can send


• In practice, Paxos nodes can take multiple roles, even all of them.
and they learn the final agreed upon value so
proposals to other nodes, they can contribu te to reaching consensus,
that you can query them for it later.
out as a group. Pizzahut and Starbucks are
• Example, we are at the college, and followin g courses, we plan to hang
ing on the group vote, we can either go
our two options for meeting up with classmates after courses . So, depend
is no centralized leader in this situatio n.
to starbucks or pizza hut after classes, but everyone will go there. There
this situatio n, the maximu m number may be
The only method to make a group choice is for a couple of them; in
consensus will ultimate ly be determ ined by
the two students to present an alternat ive i.e Starbucks or Subway. The
e being determi ned by the final majority
how many people accept or reject that suggested choice, with the outcom
count.
must be persiste nt they can't forget what
• Paxos nodes must know how many acceptors a majority is. Paxos nodes
they accepted, even though the commu nication channel may be fau lty.
us is reached, it cannot progress to anothe r
• A Paxos run aims at reach ing a single consensus. Once a consens
must happen.
consensus. In order to reach another consensus, a differen t Paxos run

'••os Algorithm
• rs would be two. Each node ru ns as a
We have a Proposer and three acceptors, so the majority of the accepto
Propose r, acceptor, and learner.
• Paxos has rounds and each round has a unique ballot ID.
• message from round 2, abort everyth ing and
These round s are async h ronous. If any b o dy ,·s ,·n round 1' and hear a
90 to round 2 .
• Each r
ound has 3 phases
. )
Phase 1 .· A Iea d er .Is elected (electio n

Phase 2 : l eader proposes a value (bill), process es acknowledgements


)
Phas 3
e : leaders multicast final value (based on consensu s ,..., •.,.,i
JI ll b I I I ,\ I I un\

,(r Blockchain (MU) 5-7 Private Blockch .
a.in
Phase 1:
• Proposer proposes a value and solicits acceptance from acceptors. A specific value is what the proposer intends to
propose. It notifies all Acceptors of the proposal number n, which is PREPARE ID. The proposal number must be
unique.

• Acceptors respond to highest PREPARE Id. If an acceptor receives a prepare request with number n greater than
that of any prepare request it saw, it responses YES to that request with a promise not to accept any more
proposals numbered less than n and include the highest-numbered proposal (if any) that it has accepted.

<prepare ,n>

if n< np

reply prepare reject (as already saw a higher proposal number), where np is previous proposal

else

np = n

reply prepare accept, (this node will not accept any lower than n proposal.

• Acceptors record the PREPARE ID they got on disc as well. Node is the leader if the majority of responses are
positive. Start a new round if nobody has the majority.

Please elect--,,.me,-.-◊7-z--------+:

Phase 2:

• If the majority of the acceptors respond YES to the proposer's prepare requests, the proposer will issue accept
requests for each of those acceptors for proposals with numbers n and v, where v is the value of the proposal with
the largest number among the responses.

o:f
Value vok?

• Recipient log on disk and responds OK.

• Delay the procedure and restart Paxos if the leader is unable to get the support of the majority.

Phase 3:

• If leader hears OK from majority, it lets everyone know of the decision (learning) .

o send (decide, v) to all nodes

Plea~ elOO me' ◊z2 \:


Value v ok?

• Recipient receive decisions and log it o n disk .

• Delay th e procedure and restart Paxos if the leader is unable to get the support of the majority .
41_ stockchai n {MU) 5-8 Private Blockch a in

';'6.2 RAFT
Raft is a consensus algorithm that is designed to be easy to understand .

It is designed to be an alternative to Paxos. It is easier to implement

Raft need to run on 5 servers to tolerate the failure of two of them

Raft algorithm was developed by Diego Ongaro and John Ousterhout at Stanford University. Raft was designed to
have a better understanding about Consensus to be achieved considering that its predecessor, the Paxes
Algorithm, developed by Lesli Lamport is very tough to understand and implement. The RAFT algorithm is similar
to pBFT but in RAFT only leader node can establish communication with other nodes and takes decision about the
state of the transaction. Raft algorithm divides time into small terms of random length. Each term is identified by a
monotonically increasing number, called term number. Each node exists in one of the three states: leader, follower
and candidate. Raft divides consensus into three phases :

0 Leader Election : If existing leader fails then a new leader needs to be elected.

o Log replication : The leader replicates log to other nodes so that all the copies will be up-to- date.

o Safety : If one of the nodes has committed a log entry at a particular index, no other node can apply a
different log entry for that index.

• Initially, there is j ust one leader and all of the other nodes are followers. Followers are passive and only reply to
requests from leaders and cand idates. The leader handles all client requests. If a client communi cates w ith fol lower,
the follower redirects it to the leader. Candidate state is used to elect a new leader.

• Randomized t imer is used to elect the leader in each term. If leader is not elected in a term, candidates will t ime
out and initiates the election for the next term. Leader, candidates log should be most up-to- date compared to log
at followers. If cand idate's log is less up-to-date compared to potential follower, then fo llower rej ects the
candidate.

• Node begins as a follower and if it does not receive heartbeat message from leader within election time then it
assumes that the leader is dead. It then takes candidate state to send out a HRequestVote". If candidate node gets
majority approvals from follower nodes, then it becomes leader.

• Only leader can append log entries as per client requests. After receiving request from client, leader appends entry
to its log. This new entry then leader sends to all the follower nodes. When majority of followers confirms this
message, leader commits the message and sends heartbeat message to client and followers. This consensus
mechanism is used in Quorum for consortium setting.

How RAFT works 7

• A RAFT cluster has one and only one elected leader


0 which communicates with client directly
0 which responsible for managing log repl ication on the other servers of the cluster.
0 which leads until it fails or disconnects, in which case a new leader is elected.
• Blockchain (MU) 5-9 Private Blockcha.io

Consensus State
module machine

f"ag. 5.6.2 : A Raft Ouster


o One leader and several followers and all client requests go through the leader.

o A client sends a request

~ State State
.l.!!J:_W '--m-ach
_ ,n_e _, machine

Fig. 5.6.3
o Leader stores requests on its log and forwards it to its followers.

o Followers store the request on their logs and acknowledge its receipt.

o Leader Election

1. Leader sends "heartbeats" to other nodes saying that it is online : they update their state machines

• State
macnme

Fig. 5.6.4
2. If other nodes no longer receive 'heartbeat', they start an electjon cycle.
3. Followers decide to elect a new leader.
4. First candidate to timeout becomes new leader.
o Log Replication

1. Leader accepts client requests and appends them to its log.


2. Leader ensures all other nodes have followed that request i.e leader replicates its log to other servers.

Byzantine Faults : Byzantine Fault Tolerant (BFT) and Practical BFT


'7
5.7.1 Byzantine Fault Tolerant (BFT)

• Consensus achievement is the process by which network participants regularly agree on the current state of a
specific blockchain.

.Ttdll ..~
p II lJ 1 1 t .t 11 d
·
hain (MU) 5 10 Private Blockch ain
if 01ockc •
.
. .
~ d I"stribut ed networ ks, it is possib le to reach consensus, but It 1s not an easy task Th is issue gave nse to the
over ·
' ept of Byzantine fau lt toleran ce.
cone .
Pease, and Shosta k propos
rt, ed the Byzan f G 1982 to guaran tee that malfun ctionin g
ine enerals Proble m in
, t.arnP 0 . . . .
a system .
components provid ing conflic t inform ation are manag ed inside

wt,at is the ByDn tine Fault Probl em / Byzan tine Generals Proble m?
an unrelia ble link.
This problem repres ents an issue of compu ter networ king over
• m illustrates how several Byzant ine genera ls m ight
A theoretical proble m known as The Byzant ine Generals' Proble
• find it difficul t to comm unicat e while decidin g on their next
course of action.

blockchains and explains why they are import ant. It will


The Byzantine Generals proble m demon strates the value of

aid in unders tanding why a b lockch ain operat es as it does.
Follow ing that, we'll expand on that to the Byzant ine
, First we will discuss the unsolv able Two Generals Proble m.
in distribu ted and decent ralized systems.
Generals' Proble m and talk about Byzant ine Fault Tolerance

Two Generals Proble m

This problem was first publish ed in 1975 .



this situatio n the generals in their armies have come
• In this proble m we will call these two nodes as generals. In
upon a city that they wish to attack.
enemy's army successfully, thus they need to coope rate
• Each general's army on its own is not enoug h to defeat the
two generals are separated by a signific ant distanc e.
with an attack at the same time the proble m arises because
.
• So think of th is as if they are like on oppos ite sides of the city
red the Follow er. In order for them to commu nicate
• General 1 is consid ered as a Leader and the other is conside
nger across the enemy 's camp that will del iver the
and decide on a t ime of attack, General 1 has to send a messe
time of attack to Genera l 2.
and the message would be lost foreve r.
• But this could mean that the messe nger could get capture d
army hold their ground s assum ing the first messa ge
• This will resu lt in Genera l 1 attacki ng while Genera l 2 and his
goes throug h.

• e so he sends a messenger back.


General 2 must still acknow ledge that he received a messag

• can get caught.


Thus repeating the previo us scenar io where the messe nger
g acknow ledgem ents back and forth with neithe r
• This opens up an infinite loop where both parties are sendin
General knowin g whethe r or not the messa ge was received .
t an additio nal
• .
If Gener 1 1 receive h G eral 2 will know that the message was received withou
a s a messa ge ow en
acknowledgem ent message.
• General 1 . bl b se General 's proble m is curren tly unsolv able.
presents a repeat ing pro em ecau
• And sfl1l . ff f th' O ne' wh ich is Byzantine Generals Problem.
a newer proble m was iterate d o o 1s

8~nti
ne Generals Proble m

We have already learned about th is proble m in Modul e l.
....
~l"I~...~_,.~
--- --- --- --- --- - - - - - - - - - - - - - - - - - -1. .. Ill b I I f I I I fl 11 ._
,., Blockcha in (MU ) Private Bloct.-'- .
5 - 11 ""1laJn

t nd
• Th is problem was introduced in 1982 in a paper written by Leslie Lamport. Robert ShoS ak a Marshall Pease

which were a group of researchers.

• It's a speci al case of the Two Generals Problem that has been generalized .

• Similar to the Two Generals problem, the Byzantine Generals problem deals with rel iable computer systerns
handling malfunctioning components that give confl icting information to different parts of th e sySt em to ensure
consensus within the distributed computing system.

• The difference now is that more than two generals need to agree on a t ime to attack their common enemy.

• The same situation is described, but this time, more than two generals are required to agree on when to launch an
attack against their common enemies.

• One or more of the generals may be a traitor in this situation, which would allow them to lie about their decision,
adding another layer of complexity (e.g. they say that they agree to attack at 08.00 but instead they do not).

• An arrangement of commander and lieutenant replaces the leader-follower parad igm described in the Two
Generals Problem.

• The commander and each lieutenant must reach consensus here in order for the action to be taken.

• The issues that could develop when communicating a decision from one general to another are while conveying
the message, the messenger could be arrested; What if the message was altered by a forger? ; How can a general
be certain that he received the message from the expecting general? ; What if other generals turn traitor and tell
their troops to strike but then they flee?

• How can the system be confident that every general will launch a simultaneous attack from their predetermined
location? Is there any other option but to have complete trust in one another?

• With its Byzantine fault tolerance (BFTI consensus method, blockchain appears to solve this issue.

Byzantine Fault Tolerance (BFT) Algorithm

• BFT algorithm is based on state machine repl ication.

• In distributed systems, ensuring that computers can establish consensus on specific facts in a reliable manner is a
very rea l difficulty that byzantine fault tolerance seeks to address.

• An method that resists a system to enter the Byzantine Generals' problem is known as Byzantine Fault Tolerance
(BFTI.

• BFT system is able to continue operating even if some of the nodes fails communicate who acts maliciously.

• The general 's team needs an algorithm that can follow the following guidelines in order to guarantee the success
of the generals' team: The next action of the plan must be approved by all troop generals ; the generals must be
dependable and comm itted to the establishment ; the impact of network traitors on generals must be avoided :
they must adhere to the system's algorithm ; no matter what the traitors do, the generals must agree on
someth ing or make a choice ; at no point during the action, the system or network should result in a 51 percent
attack.

• The basic operation of a BFT algorithm is :

o Phase 1 : Client sends a request to th e prima ry. The primary can then val idate the message and propose a
seq uence number for it.
5 - 12 Private Blo ckc hain
hain (MU )
f eJockC
ds pre -pre par e messa t allows the bac kup nod es to
..a.ase 2 ; Primary nod e sen . ge O all backup nodes. This
d
o "" eive the sequence num ber.
validate the message an rec
ws replicas
ase 3: All fun ctio nin g bac kup nod es sends Pre pare message to all oth er backup nodes. This allo
Ph d .
0
to agree on a tota l or enn g.
:-uesi-
~nt=Req
,-Clie = -- -,
pare
--
Prep
.-
are
-- r- -- -- -.
t Pre -pre Com mit

01 - - ,~ ~~ E /2 ri ~A H {j _--
B2 -- -t -~ ~ ~~:::::::::....~~~--¥-- _ _
83 - -- r - -~ -- -=:::s_-t---=::::k_..j.._

Fig. 5.7 .1: Working of BFT


have ack now led ged
a com mit . The rep licas hav e agreed on an ord erin g and
Phase 4 : All replicas mu ltic
ast
0
the receipt of the req ues t.
case whe re the
sen ds a rep ly dire ctly to the client. This bypasses the
replica
0 Phase 5 : Each fun ctio nin g
ues t and reply.
primary fails bet wee n the req the
consensus me tho d gro ws as
com mu nic atio ns am ong participants in the BFT-based
The amount of net wo rk eve ry
• requires par tici pat ion from
rise s. This is so bec aus e each transaction's processing
number of par ticip ant s cess itse lf is ma de up of a
con sen sus me tho d as sho wn in Fig. 5. 7.1.1, and the pro
participant in the BFT -based s dow n as mo re par tici pan ts
fac t tha t the com ple tion of the consensus process slow
variety of steps. Due to the es.
performance and scalability issu
fea ture of the BFT - bas ed consensus me tho d may cause
join, this

• Limitations of BFT :
t the system state.
essary access, the y may cor rup
o If malicious cl ien ts hav e the nec
fau lt-to lera nt privacy.
o No consideration is giv en to

5.7.2 Practical BFT


Fault Tolerance or PBFT.
orit hm is Practical Byzantine
• Another famous consensus alg solu tion to the Byzantine Gen
eral
uel Cas tro and Bar bar a Liskov in 199 9, which is the
• It was published by Mig
problems. like BFT -Paxos,
Byz ant ine fau lt tole ran t, tho ugh there are variants of the m
t
• Paxos and Raft are not by def aul blockchain nod e in
hi.ch ·s wid ely use d pre sently, but the con fide nce of
• • consensus me ch arn•sm w
It is a block cham
1
s in the process of reaching
· larg e am oun t of com mu nication resource
PBFT cann ot b e gua ran teed . 1t req uire 5
consensus. k dire ctio ns from the
al nod es are at equal level and gets the ir wor
.
BYlantine general pro ble m In this case, a11 gen er ondary or backup nod es.

. . d nd all oth er nodes are considered . as sec .
leader n d The lea der nod · ary no e a ues t to leader nod e. This
e 1s prim ds tran sac tion req
o e. . d b' nne r Client nod e sen
Selecti f . ly 1n rou n -re in ma ·
on o lead er 1s ran dom es.
adc ast ed by lea der nod e to all the secondary/backup nod
received req ues t is the n bro

j

( , Blockchain (MU) 5 - 13 Private Blockchain
.

• Both leader and secondary nodes use the request message with their interna l state to run computation a:
broadcast the decision result to all client nodes. Majority of nodes agreed upon decision is now considered as final
decision.

• Suppose fare maximum number of fau lty nodes. Practical Byzantine Fault Tolerance consensus algorithm rel ies on
minimum number of back up nodes which are (f + 1). Therefore, high hash rate is not requ ired . This ensures less
computation leading to less energy consumption.

The PBFT consensus algorithm works as follows :

• To the leader node, a cl ient submits a request. Following that, the leader node broadcasts requests to all backup
nodes.

• The request is processed by each node, which then responds to the client. The client watches for responses with
the same outcome from all nodes in the amount of (f + 1). Here, f equals the number of potential defective nodes.

• The main PBFT algorithm consists of 3 phases


o pre-prepare
o prepare
o commit

• Pre-prepare phase : The leader node notifies each backup node by sending a pre-written message.

• Prepare phase : The backup nodes the prepared message as a reply to all other nodes, including the leader, after
receiving the message that has been pre-prepared from the leader. Only after receiving the leader's pre-
prepared messages and viewing (2f + 1) number of other nodes' prepared messages can a node be said to b
e prepared

• Commit phase : The nodes send a comm it message if they are ready. A node executes the client's request if it
receives (f + 1) commit messages.

Client

Node 1
(primary node)
Node 2

Node 3

Node 4
Request Pre-Prepare Prepare Commit Reply

Fig. 5.7.2: PBFT Algorithm's Operation

Limitations of PBFT Consensus Mechanism :

• PBFT mechanism has complex commu nication and poor scalability. When the number of consensus nodes in th e
Blockchain network is large enough, the functional ity will be deg raded . When there 's a great deal of network
partition, consensus efficiency will be compromised which leads to a huge delay.

• Better response time can be ach ieved only with small group sizes,

• Single party can man ipulate the network by assu ming several identities or nodes.
>
5 - 14 Privat e Block chain
if, B(ockchain (MU)
~ Introduction to Hyp erfe dger

nd u st ry blockchain technology, the LF produced the open source initiative known as


• In order to impro ve cross -i
Hyperledger.
r based
commun ities to benefit an ecosystem of Hype rledge
·Hyperledger is an open sourced comm unity of
• •
. work across a va ri.ety of indus
· re Iated use cases that will
·
trial
lution providers and users focused on blockchain
so
ledger
sectors.M- Brian Behlendorf, Executive Director of Hyper
· ·
· a cryptocurrency. It ·1s a piece
· 1t
a Blockchain nor a com pany, nor 1s of software used to build
HYPe rledger is neithe r

one's own custom blockchain service.
blockchain
t called Hyperledger was developed to advance
• A cross-industry open source collaborative projec
technologies.
n with
, IOT, and finance are participating in the collab oratio
• Global leaders in banking, suppl y chains, techn ology
Linux Foundation.
Linux Foundation, which is also being hosted by the
the world .
private chains will manage multiple markets aroun d
• According to the Hype rledg er philosophy, multip le
d using
ations that cater to these businesses should be create
• Since each business is distin ct in its own right, applic
individualized rules.
s to create their applications using generic proto cols.
• Unlike Ethereum, which frequ ently forces programmer
the Hyperledger project.
• In late 2015, a small group of developers launched
and they
including data science, manufacturing, banking, etc.,
• These developers were from a range of industries,
more usable to developers and enterprises.
shared the objec tive of makin g blockchain technology

Why is Hype rtedg er necessary ?


ential transactions .
• Public blockchains do not suppo rt private and confid

• Public blockchain is havin g issues with scalability.


rks, where each peer must
• The developers d iscovered durin g extensive testing that blockchain netwo
every transaction, suffer greatly in terms of scalability.
simultaneously run consensus and validate each and
ctions with a
are taken to ensure a transaction's integrity, transa
• On top of that, due to the extensive measures that
cannot be executed on public blockchains .
degree of confid ential ity and privacy attached to them

5.9 Tools and Fram ewo rks


~ .
5.9.1 Hyperledger Frameworks

There are five blockchain frameworks .


ts and
, Iroha was developed for mobil e devel opme nt projec
1. Hyperledger lroha : Based on Hyperledger Fabric
tolera nt
Colu . Both a novel chain-based Byzantine fault
contributed by Soramitsu, Hitachi, NTT Data, and
, domain -driven C+ + arch itecture are featured in it.
consensus metho d called Sumeragi and cuttin g -edge

• Blockchain (MU)
5 -15 Private Blockch .
a1n
2.
Hyper1edger Fabric (HLF) : Developed by IBM, Hyperledger Fabric is intended to serve as a base for the creat~
of I' . ion
app ications or other solutions with a modular architecture. It supports plug -and -play components like
consensus and membersh ip services and uses containers to host smart contracts known as chain code, which
represent the system's appl ication logic.
3. Hypertedger Burrow : Originally developed as a client-bu ilt modular blockchain to the specificati ons of the
Ethereum Virtual Machine, Hyperledger Burrow was first made available by Monax and Intel (EVM).
4. Indy Hyperledger : Indy is a Hyperledger project created to provide independent identification on distributed
ledgers and was first contributed by the Sovrin Foundation. In order to create digital identities based on
blockchains or other distributed ledgers, Hyperledger Indy offers the following tools, libraries, and reusable
components:

5. Hyperledger Sawtooth : Sawtooth was developed by Intel and incorporates a revolutionary consensus
mechanism known as Proof of Elapsed Time that Intel developed (PoED. The distributed consensus goal of PoET is
to be attained as quickly as feasible. With support for both permissioned and permissionless deployments and
acknowledgement of varied requ irements, Hyperledger Sawtooth offers a lot of potential in a lot of domains.
Sawtooth is made to be adaptable.

5.9.2 Hyperledger Tools

Currently, the Hyperledger project includes five tools, all of which are hosted by the Linux Foundation.

1. Hyperledger Composer : is a collection of collaborative tools for constructing blockchain business networks that
accelerates the creation of smart contracts and blockchain applications as wel l as their deployment over a
distributed ledger. Hyperledger composer wa s developed by IBM and Oxchains.

2. Hyperledger Caliper : Currently under incubation, caliper is a blockchain benchmarking tool that enables users to
assess the effectiveness of a particular implementation using specified use cases. Th is one was developed by
engineers from various organ izations.

3. Hyper1edger Cell,o : Hyperledger Cello was first provided by IBM and sponsored by Intel, Huawei, and Soramitsu.
For the blockchain_€!~osystem, it is a widely used blockchain module kit. The effort required to create, maintain, and
terminate blockchains is greatly reduced by Cello. Furthermore, because it provides a mu lti -tenant chain service,
t his tool can work on top of a variety of infrastructures like virtual machines, bare metal, and container platforms.

4. Hypertedger Explorer : Hyperledger Explorer was created to help programmers create interactive web
applications. It was first made available by Intel, IBM, and DTCC. Using the tool, users can view, deploy, invoke, and
query blocks, transaction data, chaincodes, and other data that is kept on a Blockchain ledger.

5. Hyperledger Quilt : A blockchain tool for businesses called Hyperledger Quilt was first made available by NTT
Data and Ripple. Ledger system interoperability is made possible by Qu ilt. The Interledger Protocol ([LP), a
payment protocol for transferring va lue between distributed and non -distributed ledgers, enables it to accomplish
this .

..::5.::
.1:.:0:..__:...::
HLy~ p-=
er:..le
:.=-:d=.ig~e:.:r_:F-=a:.::b:.:.:
ri:.:c_ __ _ _ _ _ _ _ _ __ _ _ _ __ _ _ _ __ ____

• Hyper ledger fabric is a private and permissioned blockchain.

~
--------------------------------------.i♦
llw'"ir-iii
., ,~
p
Private Blockch ai n
S · 16
"-- 131ockchain (MU)

~ · a framework to crea te, deploy and maintain bl ockchalns for businesses that ensure accountability,
• It IS
arency and trust among bu siness partners as a re sult
tran Sp ·
It n.Jns smart contracts called "chaincode" w ith in Docker containers .

The members of Hyperledger fabric network enroll through a trusted MSP .

Hyper ledger fabric also offers the ability to create channels, allowing a group of participants to create a separate
• ledger of transmissions.

Shared ledger : HF has a ledger subsystem comprising two components,



The world state and transaction log.
world state component describes the state of the ledger at a given point in time. It is a database of ledgers ..

Transaction log component records all transactions which have resulted in current value of the world state .

Acfvantages of Hypertedger Fabric

Identity management via PKI (public key infrastructure)



Efficient processing through segregation of consensus and chaincode execution

Privacy and confidentiality via 'channels'

</> .
\ 7

Decentralized Safe Pluggable Easily


Network Transactions Architecture Programmable

Fig. 5.10.1

5.11 Comparison between Hyperledger Fabric & Other Technologies

Platforms Hyperledger Fabric R3 Corda Ripple Quorum


Ethereum

Publie/Private/ Private Blockchain- Private Public Both Public,


Public Blockchain-
Permissioned Network is limited to Blockchain- Blockchain- Private
No permission is
people with permission. Permission is Permissionless permissioned
needed to access
network content. needed to access network content network content
network content.

Smart Contract Solidity Galang programming Katlin C++ Solidity and

language programming programming Vyper


programming

-
Governance
language

Carried out by Linux founda tion


language

R3 company in
language

Ripple Labs Etherum

developers (DAO) incharge charge developers and


JP Morgan

- - -- - - -- - - - - - - - - - - - - - - - - - - - -----=- --
. ,,di.........
Chase

~ II h I I f I I 1 .. n '-
,., Blockcha in (MU) 5 - 17 Priva te Blockchain
---..;_

Platforms
Consensus
Ethereum

Relies on Proof of
Stake for decision
Hypertedger Fabric

The consensus process


does not require
Rl Corda

Making
decisions is
RJpple

Participating
nodes verify the
Quorum

-
Multiple voting
based
making participation from every limited to those authenticity of a consensus
node in a network. parties engaged transaction by mechanisms
in a transaction. conducting a which do away
poll. with the current
proof of work
consensus
mechanism used
today by the
public Ethereum
blockchain
among many
others

Consensus PoW/ PoS Puggable Notary-based Probabilistic Pluggable


Protocol voting

Currency Ether No native currency No native XRP ETH


cryptocurrency

Use Case Popular with the preferred platform Run s on a Runs on a Popular with
generalized for B2B operations, specialized specialized generalized
applications and mainly used in distributed dist ributed applications and
mostly used for P2P enterprise. platform for the platform for the mostly used for
and B2C operations. financial industry financial industry P2P and B2C
needs. needs. operations.

5.12 Hyperledger Fabric Architecture

E1c1e1nal•CA
optio~ I * Momborst1Jp
PA! rYl(.OS
opUonat.

Client SOK
f;Morser )
Appllcation (HFC)

,/
Comrn irter )
DEHJ
Ladger

Cha Inc ode ~


Events CD -- .... .
Orclonno·S&rvice HyperledQer Fabric Network

Fig. 5.12.1 : Architecture of Hyperfedger Fabric

• The organizations that contribute to the developmen t of the Hype rl edger Fabric network are referred to as
"members."

if_ sJockchai n (MU) 5 - 11:1 Private Blockchain

,r ponents of Hyperledg er Fabric


• com

Nodes

0
Client

0
Peer
ordering Service
0

Fabric CA

channel

Membership Service Provider (MSP)

Chaincode

Client

• Represents the end user or client applications which trigger blockchain events .

• Clients are software programmes that propose transactions on a network on behalf of a person .

• Clients communicate w ith both peers and the ordering service .

• The client interacts with the network using a Fabric SDK.

• When reading or w riting data from a Fabric blockchain the client interacts with the SDK. To ensure that a legitimate
client has started the network transaction, the CA authority issues a certificate to the client as we ll.

Peer

• nodes participating in the network

• Peer is the place where the ledger and the blockchain data is stored .

• You must have more than one peer in production

• One peer may be part of many channels

• Every single channel is inside the peer


• It endorse any update of the ledger
• You can create a backup of the ledger from the peer.
• All nodes and peers within the blockchain network are eq ual in public networks like Ethereum .

• All nodes/peers in the Blockchain network are not equal in Hyperledger Fabric.

• The role, behaviour, and tasks carried out by the peers may differ even though the underlying binary used for each
peer may be the same (version differences are acceptable).
• The following list includes the typical categories of "roles" that peers are given :

End0 rsing peer, anchor peer, and Orde ring peer

.,.........
El\dors1 ng Peers:

~ e r s have t he capability t o act as an endorsing peer, and will va lidate transactions.


If II h I I I .l I 1, 111 '-

• Blockchain (MU) 5 • 19 Private Blockchaln

• A unique category of committing peers called endorsing peers has the additional responsibility of endorsing a
transaction.

• They give their approval to the client's request for a transaction .

• Each endorsing peer has a ledger and a copy of the smart contract installed .

• The transaction simulation is the primary purpose of the endorser .

• It is carried out in accordance with the smart contract on the client's personal copy of the ledger, and it produces
the Read/Write sets that are sent to the client.

• Although the transaction is not recorded in the ledger during simulation .

Anchor Peers :

• We requ ire some peers in order to have communication across an organization because the Fabric network can
span multiple ones.

• Not all peers have this ability, but there are some unique peers-the Anchor peer-who are the on ly ones with this
permission.

• Anchor peers are well-known outside of the organization.

• The anchor peers for the participating organizations are encoded in the genesis block at the t ime the network is
first created.

• As a result, let's say Organization-A peers will have access to Organization-8 anchor peers' gossip.

• However, because regular peers are unknown to those outside the organization, the non-anchor peer in
Organization-8 cannot connect with the peer in Organization-A.

• Through peer update transactions, anchor peers can be added to a Live network.

Ordering Peers:

• It approves the inclusion of transaction blocks into the ledger and communicates with other peer nodes.

• It does not hold smart contracts.

• It does not hold a ledger.

Organization 1 Organization 2 Organization 3

Docker Virtual Network Docker Virtual Network Docker Virtual Network

OSN Nol HII 0rlJ9 Nol all o,g,


,w, un
11ov11 lo 111ri ,m
OSN CA riavc 10
OSN

; aw-a; .,uu ⇒ AW ■ d

Fig. 5.12.2

----------- ------------ ------------ -----=-:-.:-;:::;;


~.~~ - •
S 20 Priva te Blockcha in
ff... a1ockchal0· (MU) . •
locally.
~ Nodes in the netwo rk run in Docke r Containers on Virtual Machines in the Cloud or
• Each organization will join 1 or more channels .
• Each organization will design ate 1 or more peers as 'Ancho
r Peers' .

·ng service Node s
ordert
Responsible for maint aining consensus amon g peers .
• th thm and the heart of Hyper ledger fabric .
Ordering service is actual ly e heart of consensus algori

Main role is to provid e the order of opera tions .

throug h the orderi ng service .
Before comm itting anyth ing to the ledger it must pass

ation etc.
It is responsible for verific ation, securi ty, policy , verific

t4yperledger Fabric CA
for Hyper ledger Fabric.
The Hyperledger fabric CA is a Certifi cate Autho rity (CA)

It provides issuance of Enroll ment Certificates

• It does certificate renewal and revoca tion

• It consists of both server and client compo nents .


the user registry.
• It provides regist ration of identi ties or connects to LDAP as

Channels
two or more specific netwo rk memb ers.
• Channel is a private 'subne t' of comm unicat ion between
code
, anchor peers per memb er, the shared ledger , chain
• A channel is define d by memb ers of the organization
application, and the orderi ng service nodes.
by a memb ership service provid er(MS P) .
• Each peer that joins a channel, has its own identi ty given
nt
isolated instances of hyper ledge r fabric. They have differe
• Channels are compl etely isolate d. They are compl etely
ledgers, differe nt heigh t of blocks , policies, rules.
channel and who can make an opera tion .
• We can make a policy about who can see the data in the

• MSP (Membership Service Provider) :


er
• is the responsibil ity of the memb ership service provid
Making digital IDs for team peers and organ ization users
(MSP) .

• d before a new entity may join the channel.


An existing netwo rk must have its peers' identities define
• d for enrolli ng users from a netwo rk partic ipant and
An MSP implem entati on called Fabric CA offers a metho
granting them with digita l IDs (X.509 certificates) .
that
• CA. Each Fabric CA is set up w ith a backe nd databa se
Typically, a Docker conta iner is used to execu te Fabric
ates. The defau lt is SQLite, but there are additi onal
holds the registered identi ties and their X.509 certific
keys are not stored by Fabric CA.
alternatives, includ ing PostgreSQL or MySQL. Users' private
• Blockchain (MU)
5 - 21 Private Blockchain

• Identity is going to be a digital certificate and users are going to be using this digital certificate to signed th:
transactions and submit them to the blockchain and the advantage of sign ing is that they authenticate with the
blockchain that they are a legitimate user and it also ensure that they get the right access privileges on the
blockchain for the transactions they are performing.
Chaincodes

• A chaincode typically handles business logic agreed to by members of the network, so it is similar to a smart
contract.

• all our business logic is inside the chaincode.

• It is written in Go. Implementation of Java and javascript are on the way.

• Chaincode may be installed in every peer and channel.

Transaction Flows

• Consensus is achieved using the following transaction flow :

Validate

Endorsement :

• The client application is going to submit the transaction to a few peers and these peers are going to execute these
transactions and agree that the output is the same across all of them.

• So they are all going to find the output of the transaction and they will add their signature to it.

• The client application has to collect endorsement from multiple peers in the networks to say that this transaction is
a valid transaction and all outputs are the same.

• Once you have collected sufficient signatures, we will ta lk then you can submit the transactions for ordering.

Order:

• Multiple applications might be submitting, multiple users might be submitting these transactions to order.

• So now the ordering service will ensure that all of them are fully ordered and totally ordered across all the nodes.

• In the ordering service, you order the transactions and once you determine the order of al l the transactions then
t he resolution of validation.

Validate:

• For instance you should not be performing two transactions simultaneously that modify the same state.

• So this is equivalent to t he double spend ing problem that we would have seen in bitcoin. If you have just a 20
rupees balance in a bank account, you should not be transferring 20 rupees to two different people trying to
double spend that money.

• So validation is if two t ransactions are goi ng simultaneously only one of them can succeed and which one
succeeds will depend on t he ordering service.

• The first transactions that modify t he data element succeed, every other transaction in the same block that is trying
to modify the same transaction wil l get in validated, that is the validation step.
"':a:in;(M~lfJ::;j~~~;;;;~;;;;--.;:_5.;_-;.22~----------
f 810' fH I d
worki:.:. n~g=o==y=p=e=r=e=g=e=r=a=ri=c= = = = ==
~ --..!~:!;
- - - - - - - - - - = = ~~=~
F b

-=-- - ~~~==-====- -==-==========


Pri vat e Blockchain

~
~ Endorser p
eer Hyper1 edger Fab nc Work
F.: w
:7o
-=:
~ Prter J
Anchor Pe «
_J

~ Peer } Gen eral P~ r


ti
Compi:m y . B 1

t.;.~. . . . _Pee--.Jr1 ~ \ CIWlnt App \


ti
Company - A ~...._
~ __P_ee r I r} PeP.r l~
~ Peer
(I )
l~P•~ 1·
· ~I
---===::==::.-
(5\

:'.it Qederiog Peer

Hyperlw ~r F,;ibrk WQildlo


w

Fig. 5.1 4.1 : Hy pe rle dg


er Fabric Wo
rkF low
Step 1: Through the clie nt
ap pli ca tio n, a pa rtic ipa
nt in the me mb er Organiz
ation initiate s a transaction request.

•·'Fabr'Jc Hyperledger
Clien\ · Fabnc SD K

Org1 Em plQyee

I l
Fig. 5.1 4.2
Sttp 2: The transaction inv
oc ati on request is broad
cast to the Endorser pee
r by the client applicatio
n.

~ -- Q
® f ~brtQ '
c1;im1
t-{yp 0rl edg er
Faodc SO K - --- @ - -• ~ ~

Step . Fig. 5.1 4.3


- ~ - ~~
3 Th t
e ran ·t·
ck . saction is validated by the Endorser peer reviewing the Cert, ,ca te details and others . Then it runs the
naincode (i.e., Smart Co
ntract) and gives the C1. t th Endorsement respons es• As part of the endorsement
,en e
response, the endorser . or re·ecting the transa .
peer sends a message ap ction.
-- -- -- proving ~

,., !~ ,~~·~~-
, ; Blockchain (MU) 5 . 23 Private Blockcb ain
---
CA Approvos Signatures
% ~ 0[@-

® -LI...
- Hypertedger
Faonc SDK ~CiJ 0@-
I I ~
-. -

Fig. 5.14.4
Step 4 : The transaction is now sent by the cl ient to the Orderer peer to be properly ordered and added to a block.

Ordering
Service
Node

I I

Fig. 5.14.5

Step 5 : The transaction is added to a block by the orderer node, which then sends the block on to the anchor nodes of
various organizations that are members of the Hyperledger Fabric network.

Step 6 : The block was then broadcast by the anchor nodes to the peers within their own organization. The most recent
block is then added to the local ledger by each of these peers. Thus, the ledger is updated across the entire
network.

Ordering
Service
Node

Fig. 5.14.6

5.15 Creating Hyperledger Network

• Jnstalling Hyperledger Fabric and Composer is a good way to create a Hyperledger network.

1. Prerequisites
You should check the Hyperledger Fabric prerequisites page at

https://hyperledger.github.io/composer/v0.19/installing/installing-prereqs.html
,......--
s . 24 Priva te Block cha in
fl eJockchain (MU)
may hav e changed.
~• because the versions and spec ifications
llation
0
Docker Engine and Docker Compose insta

0
Nodejs and NPM installation

0
Go insta llatio n

0
Git insta llatio n

0
CURL insta llatio n

0
Python 2.7.x insta llatio n
simp le.
ntu users to make this operation incredibly
Hyperledger prov ides a bash script for Ubu

2. installing tool s to ease dev elop men t
Term inal.
executing the following instructions in your
Make sure you are NOT using sudo when
• parts will eventually prove
r-cli. Although not essential, the remaining
The only necessary package is compose

to be quite help ful.

curt Installation
sudo apt-get inst all curl
After inst.allatlon
mr1 -Yf!rsion
Node Js Installation >••·:•• Eb·•h
•·<+' 'ii i;;i

<];sµ g,9 d ·• as -
·.••·· •• ·•···•·· • • , . ,i

curl -BL https·//deb nodesource,comtsetcip .J0;)


• Then run the fo llow ing com man d

sudo:apt-get upd ate


t ion for NodeJs
• Run below com man d to start the inS allat

sudo apt-:get install n ode js not run th is command


f II or
• To check NodeJs is installed success u Y

node -version
Git Installation

sudo apt- get insta11 git


glt--verslon

Python Inst alla tion

sudo apt-g et insta ll pyth on


PYthon ··ve rsio n
tion
Docker CE(Community Edition) Installa

____________ -cV9.'i"~~.~'o'"~ ..-.~,•~~.~~.~


.~~
n-st_a_ll _ __ _ _ _ _ _ _ _
rs~t~d:o:w:n:lo:a:d~a~n~d~ th~e~n~i-
- - - -~Fi~
Private Blockchain
• Blockchain (MU) 5 - 25

ce l8.06.3 -ce- 3-
https: / / down]oad.dock er.com /linux/ ubun tu/ dists/x eniaJ/p ooJ/stable/amd64 / docker-
0-u buntu amd64.deb
sudo dpkg-i docker-ce 18.06.3 - ce-3-0 - ubu ntu amd64.deb

docker -versio n

Docker Composer Installation

Run below commands to setup Docker compose.


sudo apt-J~l>t install python-pip

pip --versio n

sudo pip install docker-compose


Verify the installation and check the version fro m below command.
docker-compose version:

Hyperl edger Installation

Step 1 : Run below command to download and setup Fabric.

• curl -sSL https://bit.ly/2ysbOFE I bash -s

When we run the command above, we can run into the following problem.
trying to connect to the Docker
failed to get default reg istry endpoint from daemon (Got permission denied while
daemon socket at unix:///var/run/docker.sock:

Run the command below to solve this.


sudo -C:hmod 666 /var/run/docker.sock
Now Hyperledger is installed in our system.

To create test networ k

Step 1 : Go to fabric-samples fo lder by using below command.

cd fabric-samples
Step 2: Go to test-network folder by us ing below command.

cd test-network
Step 3 : Ru n below command to start your test-network
sudo ./ networ k.sh up

This st art the network, you can run below command to check docker containers.
sudo docker ps
• This shows you three docker containers
Blockchain (MU)

5-26
One for Orgl peer node
1. Private Blockchain
One for Org2 peer node
2
One for Orderer
3
at the
When we start network, we will also not
get any channel
command.
by default. We can check the channel
by using below
sudo
cker exec peer0.org1.exam
xample.com peer channel list
This command showsthat, we don't have
any channel created.
Userguser-Virt
channel virtualBox:ffabrtc-gonpes/test-
11st network$ sudo docker exec
peer9.org1.exanple.com pee
tions initialized

channels peers has joined:


Endorser and or derer connec
uSer
User@ -VirtualBox 3Dric-saples/test-networks
Cheo4:Create new channel by using below command.

Sudo./network.sh createChannel -ctestchannel


This will create a new channel with the name testchannel

To verify this channel creation, run below command on both the peers.
sudo docker exec peer0.org1.example.com peer channel list
sudo docker exec peer0.org2.example.com peer channel list

sudo docker exec peero.org1.example.com pee


userauser-virtualBox/fabric samples/test-ne twork$
channel list i.l Endorser and orderer connec

t afeia FÍ agto
ttons inittallzed
Channels peers has joined:
testchannel
peer6.org2.example.com pee
sudo docker exec
u s e r @ u s e r - V i r t u a l B o x : / f a b r i c - s a r m p l e s / t e s t - n e
tworks
connec

channel ltst F Endorser and orderer

tions initialized
Channels peers has jotned:
testchannel
command.
to run below
Step
P: lo stop the network, you need

sudo ,/network.sh down

CouchDB Installation (State Database)


below commana.
e p 1:Go to fabric-samples folder by using

cd fabric-samples
command.
below
Step 2 test-network folder by using
0 0 to
as well.
containers
cd test-network create
couchDB

network
and
Step 3 Run below com
eOW
Command to start the Techneuledge

udo /network.sh up -s couchdd


DIOCchdin

5-27
Blockchain (MU)
create couchdb
container for edc
and
mmand
starts your network
Step 4: Create new channel by using below command.

Sudo /network.sh createChannel -c testchannell

This will create a new channel with the name testchannell.

Step 5:To stop the network, you need to run below command.

sudo /network.sh down

Write Smart Contract and Deploy it (WritingEirst Application


We will take smart contract code from

https://hyperledger-fabric.readthedocs.io/en/release-2.2/write first app.n


:
C
ibhype: edger-taric.readtheckoesiorenieon-.weae firvt se . . .. . aii

Application
Writing Your First
HYPERLEDGER
FABRIC f youre not yet familiar
with the fundamental

the y t s sectton prlor to


architecture

contimuing.
of a Fabric
network. yau may

want to visit
and
introduction to Fabric applications
as a n
s also worth noting that this tutorial serves more in-depth look at Fabric
applications
For a
uses simple smart contracts and applications. t.imieicia
Davzag A#iatin s section or the
Introduction
and sinart contracts, check out our
.: ..
What's new in Hyperkedger Fabrit

knteract with deployed


This tutorial provides an introdut tion to how Fabric applicatlons
Rcicase tois
programs built using the Fabric SDKs-
blockchain networks. The tutorlal uses sample
Kkey Cencepts topic to invoke a smart contract which queries and
described in detail in the Arplicatieri
-

described in detall in Srmtt Cuntr


Getting 5tarted
updates the ledger with the smart contract API and a depiloyed Certificate Authority to
hevepine Applicatiens haessin. We will also use our sample programs
an application needs to interact wlth a permissioned
generate the X.509 certificates that
Tutonia blockchain.
12g tiz Fabit izstratoth
About Asset Transter

Writing Your Flrst Applkcation Tnis Asset Transfer (basic) sample demonstrates how to Initiallze a ledger with assets. query
those assets, create a new asset, querya single asset based on an asset 1D. update an exlsting
asset, and transfer an asset to a new owner. It involves the following two components:
release 22
Read the Dots

instructions given on website for creating smart contract.


And follow step by step

5.16 Case Study ofSupply Chain Management using Hyperledger


qualities offered by blockchain technology, various projects have been launched in the
To utilize the effective
administration of permissioned networks are both tasks that Hyperledger is suitable
recent years. The building and
for in the enterprise. Performance, trust levels,
and scaling are all improved by the permissioned network.
Fabric.
Most of the supply chain projects are implemented using Hyperledger frameworks, especially Hyperledger

B E TechKnewledge
UDTIItiuo*
Blockchain (MU) 5 28
Private Blockchain
Chain Management- Before Blockchain
Supp.
Delivery boy
Hi john, here is
Costomor
your order Thank you!

wwwnnim

Costomer
Delivery boy- These apples are
Hi
rotten!i wat my
john, here is money back
your order

JL
Costomer
Delivery boy These apples are
roten!i want my
cant help you
john, im just money back
delivery boy

Fig. 5.16.1
Arent issues in supply chain and logistic industries are:
Risk of using centralized
database
Good frauds

Traceability
ncompatible database with various supply chain entities.
DIockchain Technology can be used to track all types of transactions in a very secured and transparent
manner.
Tech Knouladge
Blockchain (MU) 5-29 Private Blockchain
What Blockchain offers?

Decentralized, high security


Immune or tampering

Traceability exists
Streamline transaction process
Here we will discuss the most famous application and case study of food product supply chain industry that wa

which Walmart also adopted. With the use of a Hyperledger Fabric-based


developed using Hyperledger Fabric
vendors.
system, Walmart can now track the origin of over 25 items from 5 different
in the nation are dealing with
the blockchain. Farmers
Building and maintaining user trust is the primary goal of
the fair market
chain's corruption, which prevents them from receiving
serious problems as a result of the supply in the system
farmers would improve, and corruption
value for the items they produce. The financial status of the
and payment systems automatic.
will be decreased, if we use the Blockchain to make contracts transparent
sector. Numerous
parties are
impact on the farmers in India's agriculture
Less product margin prices have an
merchants, distributors, grocery stores,
involved in the food chain, including farmers, shipping firms, wholesalers,
and ultimately consumers.

that are made and delivered


from farmers to consumers. Using
Currently, it is quite difficult to trace the products
increase supply chain transparency
and improve the efficiency
Hyperledger Fabric, a technology like Blockchain can
transactions.
of a system that involves many
Fabric network (MSP). In
Service Provider in order to join a Hyperledger
One must enroll via the Membership
which aids in constructing a fairly generic
chaincode, the use of a framework
contrast to Hyperledger Composer,
because it makes it easier to develop
proves to be a wise decision
like Hyperledger Fabric for the proposed system
Fabric offers improved
chaincode for based architecture. In comparison to Composer,
protection
a full-fledged
Transport Layer Security (TLS).
authorized personnel are able to upload the records for a certain shipment, after
Using Hyperledger fabric, only
which they are checked and released.

and guarantees that the facts are shared only among


This protects against tampering with the material released a
the participants, which in turn helps to safeguard the confidentiality
of agreement secrets. In order to achieve
in their
would have access to a specific consignment's data
transparent supply chain, only network participants
individual ledgers.
Actors like Farmers, Logistics, Price Authority, and Enterprises - a corporate for buying food products c
represent most supply chains.
Although the client is a component of the supply chain, it is not a full participant in the system because it just use

what the supply chain has to offer.


When designing this application, we will make the assumption that any company can connect directly witn a
at
begin
other organization, enabling a circular economy. In the traditional supply chain, the flow of goods would
the producer and finish at the customer.
and
Farmer's organization creates a blockchain network and creates user credentials, such as a username

password, for the registered entities.


TechKnelelg
Blockchain (MU) 5-30 Private Blockchain

ent
satering a usename and password to access the website, Price Authority publishes the price information for a

the blockchain network.


pecific product onto:
mers Organization enters user information for the website, such as a username and password, and tne
. Farm
formation about the shipment it is sending is validated and posted on the blockchain network.
nf

eina user credentials such a username and password, the logistics organization checks on to the website. Ine
Using
information about the consignment is then verified and posted to the blockchain network.

Farmer Consumer

Decides the
price

Grows

Price Aulhority

Decides the
price

Ships

Enterprises
Logistics
Fig. 5.16.2

to the website, and the information about the shipment from


Enterprises enters in with a username and password
blockchain network.
Enterprises is validated and published on the
increased due to various reasons, then Price Authority will update on distributed
f the product price is reduced or
will also come to know about the actual price he is getting
and famers
ledger which will be verified by other actors
for his goods.

Prerequisites
We need to install the following third-party tools:
https://www.virtualbox.org/wiki/Downloads
or native Linux (Ubuntu)
Virtual box available at

Git (https://git-scm.com/)
G o Language (https://golang.org/dl/) ce/ubuntu/ (version +17.03)
https://docs.docker.com/instal/linux/docker-
Docker engine available at
https://docs.docker.com/compose/install/

Docker Compose available

o (version +1.8)

Curl (https://curl.haxx.sep <9) NPM (version 5.x)


Node available at https://nodejs.org/en/
(version 8.x
Python 2.7.x and Pip TechFuDTTAI1Gn
Kaouledgd
Blockchain (MU) 5 31 Private Blockchain
Installing Hyperledger Fabric
he next step is to build a local Hyperledger Fabric runtime to deploy your business networks to.

Make sureyou have installed all the endencies required for us to make the
Fabric environment run.
Then, create a
rolder with the name
food-supply-chain, which will host our Fabric project and network configurations files,
Enterthe project's directory and install the platform-specific binaries
curl-sSL
Eps/raw.githubusercontent.com/hyperledger/fabric/release-1.2/scripts/bo otstrap.sh | bash
AS a result you'lpreloadall of the requisite Docker images for Hyperledger Fabric1.2in one shot.
Fabric's Chaincode

Now need to write smart contracts.

The smart contract that


manages the business logic chosen by network participants is called Chaincode. It
is a
piece of code that executes the
logic operation within the blockchain network and may be created in any
common
programming language and run inside a container.
Next, we need to build local
a
Hyperledger network to deploy the Chaincode and start tracking the food
supply chain. along the

Review Questions
Q. 1 What is private blockchain with its characteristics?
Q.2 What is the need of private blockchain?
Q. 3 Explain state machine replication?
Q. 4 Explain PAXOS consensus algorithm
Q.5 Explain RAFT consensus algorithm.
Q.6 Explain Byzantine Fault Tolerant algorithm.
a.7 What is the need of Practical BFT?7
a. 8 Short note on Hyperledger frameworks.
Q.9 Short note on Hyperledger tools.
Q. 10 Explain Hyperledger tabric with advantages.
a.11 Ditferentiate between Hyperledger fabric and other
a. 12
technologies.
Explain Hyperledger fabric architecture.
a. 13 Explain woking of Hyperledger tabric.
Q.14 How to create Hyperledger network.
o.15 What are the issues in current supply chain
management system?
can help to overcome these issues. Explain how blockchain with Hyperledge fabic
TOOLS AND APPLICATIONS
MODULE vI
6 IN BLOCKCHAIN

Syllabus

rda, Ripple, Quorum and other Emerging Blockchain Platforms, Blockchain


Corda in DeFi : Case Study on any of the
Blockchain Platforms.

Cnterorise blockchains include Quorum, Hyperledger Fabric, and Corda, respectively. These are private networks
th functions created for business enterprises, such as knowing the identities of network participants, and access to
with

restricted to certain parties.


them is

6.1 Corda
. It is a blockchain platform that is open-source and uses smart contracts to let companies deal privately and
directly
Corda is a distributed ledger technology (DLT) that R3 created specifically for enterprise use, with privacy as the
guiding principle.

Corda Regulatory Body

Smart
Contract Observer Body

B
Smart
Contract

Legal Body

Blockchain Nodes

Fig. 6.1.1

Drda protocol is buit on a strong identity model, where every node's identity must be proven to have been
pery on boarded by using an x.509 certificate with a validated trust chain.

d s Custom-designed for the financial industry.


Ren ecord-keeping expenses and offers development services like Corda App Consulting, User Interfaces,
Regulated Tokens, and others.
The distributed apps
created with Corda are known as CorDapps.
Blockchain (MU) 6-2
Tools and Applications in Blockch
chain

Public/Private/Permissioned - Public Permissioned, Private, Permissionied

Verslon: Corda OS 4.4

Consensus: Single Notary. Raft. BFT-SMaR


Transaction Privacy : Yes
Transactlon Visibility: Private transactions between participants are hidden trom all other participants.

Smart Contract Language: Java, Kotlin

Signing identities are only available on Corda nodes.


Corda enables the creation of immutable financial event records. However, unlike other blockehains, transactions in
Corda are private.

And, most importantly, Corda is not bound to any particular consensus algorithm or cryptocurrency.

It makes use of the Notary infrastructure for transaction sequencing and validation. A corda network may contain
multiple notaries who use different algorithms to validate transactions.
Features of R3 Corda

Node Permissions- On each node, a trusted network map service is supPplemented by


file-based configurations. Corda networks are divided into compatibility zones, each of
which is governed by a different Certificate Authority.

Identity Individual and organizational identities are based on PKI

Privacy It enables businesses to build permissioned networks that prioritize privacy.

Flexibility Corda facilitates agile development, which gets to meet the needs of the
business. Businesses can get started immediately and customize it to their specific needs.

Open Design It facilitates a collaborative environment, which leads to the enhancement


of the platform and the advancement of blockchain technology integration in businesses.

Advantages of Corda

No mining, cryptocurrency or token- no dependence on miners.

Disadvantage of Corda

Because the Corda framework is tailored to the financial sector, the project's target audience is limited to financia
institutions.

Enterprise Use Cases


Corda has seen widespread industry adoption, particularly among financial and insurance firms.
B3 reinsurance network
Marco Polo global trade finance network

BErdLnowledg

"

PDt
Blockchain (MU)
6-3
6.2 Ripple
Tools and Applications in
Blockchain
hain
A blockchain
platform called Ripple
concentrates on the
al.time technology
This real-time
enables banks and financial aspect of the
the globe in real time. other digital
financial institutions revolution.
to
transmit payment
Chris Larsen and.Jed
McCaleb co-founded
it, and
transactions across
it was first
tnle is an open source released in 2012.
anyone else for free. person-to-person payment network
that allows
anyone in the world to send money
Cor
hanks and payment processors, Ripple Labs to

make it aims to
There
The is big problem when you want
a simple and affordable to send
to send money abroad.
days and it is usually
expensive, and in some money from one
country
countries you even have
to another
country. Sometimes it takes
Ripple Lab is trying to solve a to do
illegal things to make it happen.
big problem.
that makes up half of all
international wires
Nowadays, most
international transfers use Swift,
and moves which is a
takes a lot of fees. around six trillion
dollars each day, but it's protocol
very slow and
Ripple's primary goal is to
eliminate the need for older
systems such as Western Union or
Ripple is a distributed payment
protocol.
Swift.
Ripple is a financial technology that
functions as both a
It also comes with cryptocurrency and a digital payment network.
solutions for minimizing liquidity expenses and sending
Currently, more than 300
rapid payments.
companies are using the platform to create and
businesses can create global payments or build their own custom deploy financial assets. With
financial solutions.
Ripple,
Ripple is
emerging as the next promising virtual currency.
XRP is
Ripple's token
Ripple's XRP can settle a payment in 3.5 seconds.
ARP IS a
fast, direct, and secure way to send payments on the web.
In
essence, through its RippleNet Internet of Value, Ripple provides businesses with an alternative
system. to the banking
Co
Lompanies provided with Ripple products
are like xRapid, xVia, and xCurrent in order to
methods of international improve their current
money transters.
Ripple
E
Operates on an
open-source, peer-to-peer decentralized plattorm that enables the seamless transfer of
Oney in
any currency, including dollars, yen, euros, and cryptocurrencies such as litecoin and bitcoin.
Rathe than
ner using blockchain mining, Ripple confirms transactions using a consensus mechanism via a group of
bank-owned servers.
It ais
decentralized system using a consensus model called the Unique Node List

Tech Knouledgi
R
ig6.2.1 Ripgderet
Heed of Ripple

Rapple is a derernrskzed tat unhed ysen


We can trenster money from one syten to ancther, a we can keep things sirmgie in Rippje.
s aso impe to transter furds into ard out of Rigpie

Bncotn Vs Ripple

Rapple s coernus orierted. ippie's toker, unlike Bncoin, Ethereun, and many oter csyptoourrerce, n ta
mined
Bncoin can handie 3-6 transactions per seand, wherees Ripple can hande 1500 1ransactione per second

Features of Ripple

Consersus and Validaticn The cnder arnd validity cf the 1RP transactions are agreed
upon by independert validator nodes. There s no mining process involved here
because the validators have aready been chosen and the total XRPs already exist As
a rewt, no tirne, efort, or money is espended on mining

tis an open source protocoi that allows for quick and inexpensive transactions. t sa
currency as weli as a platform.

sa trusted platform with increased visibility, hich elininates paynent failures


t chers digtal seurity to protect against counterfeit coins
Ripple allous for the eschange of any currency or valuable asset with a low unifie

ommission
Advamtages of Ripphe

Transactions are less enpensive and faster than with Bitcoin

ts primary purpose is to be used by banks.

Teleas
Blockchain (MU) 6-5 Tools and Applications in Blockchain

Ripple is capable of being converted into any currency.

People must wait days for cross- border payments to be completed. RippleNet assists in resolving such concerns, as
well as improving transaction speed and lowering associated costs.

on the Ripple network, transactions are settled in seconds. in contrast, banks may take days or weeks to complete
a wire transfer.

Use less computing.

Disadvantages of Ripple

Ripple is primarily expected to target larger players in the financial market. As a resut, it is only of limited use to
retail users.

The Ripple Company owns the majority of the XRPs. This indicates that the company may have control over the
network's operations.

6.3 Quorum
What is Quorum?

A distributed ledger protocol called Quorum is based on Ethereum.


As Quorum only modifies Ethereum's core slightly, it is intended to grow and change alongside Ethereum.

I t is a JP Morgan's Enterprise focused blockchain which is open source (LGPL -3.0 License).
Quorum is a free and open source blockchain protocol designed specifically for use in a private blockchain
network, in which only one member owns all nodes, or a consortium blockchain network, in which multiple
members each own a portion of the network.

It is a soft-fork of the very well-known public Ethereum blockchain.

Quorum is an Ethereum blockchain aimed specifically at the finance sector.

It is created solely to provide privacy for private transactions between nodes.

The main feature of Quorum is privacy. Transactions and smart contracts on the blockchain can be private.

Quorum features multiple voting based consensus mechanisms that do away with the current proof- of- work
consensus mechanism used today by the public Ethereum blockchain.

Public/Private/Permissioned Private. Permissioned

Version Peer:2.7.0, Transaction manager:Tessera 0.10.6


Consensus IBFT, Raft

Transaction Privacy- Yes

Transaction Visiblity - Private transactions between participants are hidden trom all others.

Solidity, Vyper
Smart Contract Language

Tech inewledge
O'l.*t"ns
Tools and
Blockchain (MU) 6-6 Applications in Blockchain
O d m can be run with two different privacy options, Tessara and Constellation, whicn are used by Quorum

encrypt and share data among nodes.


rdnsactions on the Quorum network don't cost Ether. Voting is the primary method ot transaction verification
a

mechanism for agreement.

Need for Quorum


Even there are several organizations handling the information in the banking industry at the moment, there is

still a lack of transparency, information management, and


security
Even it standard blockchain technology offers traceability and immutability, it nevertheless falls short of meetina

the criteria of the banking industry.


A solution that offers private control on the blockchain through automation and is adaptabie to demands is

required.
Public Ethereum had some challenges in adoption with an enterprise environment that quorum addresses, which
includes privacy, speed, and throughput.
Features of Quorum

Privacy Transactions and smart contracts on the blockchain can be private,


allowing access only to participants that are involved in a specific transaction or
access to entities such as regulatory bodies.

Secure I t uses advanced encryption techniques and ensures only authorised


entities can access the network.

- Voting based consensus mechanisms (Flexible consensus) Quorum features


multiple voting based consensus mechanisms which do away with the current proof
of work consensus mechanism used today by the public Ethereum blockchain,
among many others. It utilizes raft-based and Istanbul Byzantine Fault Tolerance
(BTF) consensus mechanisms.

Peer permissioning using smart contracts Quorum allows peer or node


permissioning using smart contracts, which ensures that only known parties can join
the network.

Increased scalability and network performance.

Community -
It leverages the world's largest pool of blockchain developers.

Performance There is a high TPS due to the private and permissioned


environments of known peers only.

Finality The pluggable consensus prevents chain forking and transaction reversal .

B TechUnewtedge
P u bilatu"
6 7
B l o c k c h a i n( M U
Tools and Applications in Blockchain
o u o r u mA r c h i t e c t u r e

Quorum

Consteilation

Ouorum
Node

Transaction
Enclave
G0 Manager
Ethereu

Fig. 6.3.1:Quorum Architecture


Inarchitecture, there isa Quorum node, which is the Go Ethereum client.

They have a notion of constellation, which is really a general purpose peer to peer encrypted message exchange
system. This allows peers to exchange messages in a privacy persevering manner.

This constellation is also responsible for transaction execution.

Transaction manager is responsible for transaction privacy and it doesn't hold any secret information.

Enclave is a secure processing environment that acts as a black box for processing commands and data. All
Cyptographic work is separated out into an enclave. Enclave ensures that the key remains private and encryption,
decryption all happens within this secure enclave.
Advantages of Quorum
Quorum offers faster transaction speeds because private contracts are typically used, and private contracts
perform better than public contracts.
dnsaction-level privacy : Quorum is the very first distributed ledger platform to include a security layer with zero
knov
OWedge (ZSL). This feature is intended to protect users' privacy by using shielded transactions.
Sm smat contract that has been
art contracts can be private
set to
or public, and they are programmed using Solidity. A
Oprivate cannot be converted to public. Accordingly, public smart contracts cannot be converted to private
mart
contracts, making them more seCure.
Disadvantages of Quorum
Quorum does not
im does not require a buit-in cryptocurency because consensus is not achievecd through mining. With

Quorum, it is not possible to create a native currency or a digital token.

calability : As use cases become more complex, Quorum's channel-based approach to privacy poses privacy and
Scalability challenges.
nterprise Use- Cas ucks, Louis Vuitton, JPM Coin, Microsoft
& EY

Tech Kneuwledge
Blockchain (MU) 6-8 Tools and Applications in Blockchain
6.4
Emerging Blockchain Platforms
Blockchain platforms are new platforms that are nearly indistinguishable from core blockchain technology in some

cases
Blockchain platforms are increasingly being used to improve financial transactions, trade, traceability, and supply
chain efficiency.

A significant portion of this interest is due to the cyclical upswing surrounding Bitcoin, which is based on an old
blockchain platform that has issues with speed and energy consumption.
To help with these issues and offer useful value for other enterprise applications and uses,
contemporary
blockchain platforms have been developed.
Here are the emerging blockchain platforms to consider other than Ripple, R3 Corda, and Quorum

Ethereum
1BM Blockchain

Hyperledger Fabric
IOTA

Microsoft Azure Blockchain


Oracle Biockchain Cloud Service

ConsenSys Quorum
Stellar

Ethereum

Ethereum is the most secure block chain-based crypto currency platform. It contributes to the develapment of
secure and transparent crypto currency solutions for customers. Its primary strength is that it supports true
decentralization via smart contracts. It has its own cryptocurrency, ether, in addition to its role as a blockchain
platform that forms the basis for enterprise applications.

Hyperledger Fabric

HYPERLEDGER

FABRIC Tec Kneuledge


6-9
Blockchain (MU) Tools and Applications in Blockchain

Linux dation
Foundatic hosts the Hyperledger Fabric platform,
which is an open source blockchain
framework. One
The
permissio
rmissioned blockchains is Hyperledger Fabric. Smart Contract (Chaincode) and Pluggable Consensus
most
the
of
functiona is porovided.
is r o v i d e d . It makes it easy to enable digital records without central authorities approval and

n u m e r o u
opportunities to extend the functionality.
rovides

1BMB l o c k c h a i n

BLOCKCHAIN
is the company's blockchain division that offers enterprise blockchain services. In contrast to public
TRM Blockchain
1BM develops private and permissioned blockchains.1BM has invested in
hlockchains such as Bitcoin and Ethereum,
smart
make critical tasks like configuring, testing, and rapidly deploying
developing a user-friendly interface to
with Stellar, a
has launched the USD Anchor cryptocurrency in collaboration
contracts easier. IBM Corp. (TBM)
and Stronghold, a startup. USD Anchor coins are backed by an
blockchain that shares technology with Ripple,
equivalent amount of US dollars.

1OTA

IOTA
1OTA is one of the most exciting
offerings on the market today,
Despite being one of the younger blockchain the Internet of
distributed ledger created specifically for
plattorms. IOTA is a cryptocurrency and open-source potential for
which is encouraged by the
ings. It stores transactions on its using a directed acyclic graph,
ledger blocks and is instead
IOTA does not use any chains or
blockchain-based distributed ledgers.
yearer
scalability over
powered by its own unique technology.

Microsoft Azure Blockchain


Azure
Blockchain

ConsenSys Quorum
coNSENs
uoru

Tech Kaeuledyo
Blockchain (MU) 6 10 Tools and Applications in Blockchainin
LOnsensys acquired JPMorgan's intellectual assets for the Quorum plattorm in late
property 2021 and
ncorporated them into its own work to build the source
protocol layer. Enterprise
ConsenSys Quorum open
Customers such as
JPMorgan and the South African Reserve Bank use the firm's development senvices for
the
combined platform.
Stellar

Stellar
Stellar is decentralized, open network that connects the world's financial infrastructure. stellar is used for
a
asset
tokenization, holding and diversifying value, and
sending and exchanging assets. Stellar is a newly developed
blockchain platform that has been
optimized for a variety of DeFi applications. It implements the Stellar Consensus
Protocol, which is said to shorten the time it takes to
process and finalize transactions on a public blockchain
network.

Difference between popular and


emerging blockchain platforms
Platforms Ethereum Hyperledger R3 Corda Ripple Quorum
Fabric

Public/Private
/Permissioned Public Private Private Public Both Public, Private
Blockchain- No Blockchain- Blockchain Blockchain permissioned
permission is Network is Permission is Permissionless network content
needed to access limited to people needed to access network
network content. with permission. network content. content

Smart Solidity Golang Kotlin C++ Solidity and Vyper


Contract programming programming programming programming
language language language language
Governance Caried out by Linux foundation R3 company in Ripple Labs Etherum developers
developers (DAO) incharge charge and JP Morgan Chase

Consensus Relies on Proof of The consensus Making decisions Participating Multiple voting based
Stake for decision process does not is limited to those nodes verify consensus mechanisms
making require parties engagedthe which do away with the
participation in a transaction. authenticity of Current proof of work
from every node à transaction Consensus mechanism
in a network. used today by the
by conducting
a poll. public Ethereum
blockchain among
many others

Tech Kneuledge
in Blockchain
Blockcha1n (MU) 6-11 Tools and Applicatons

Platforms Ethereum Hyperledger R3 Corda Ripple Quorumn


Fabric

Consensus PoW/ PoS Puggable Notary-based Probabilistic Pluggable

Protocol voting

Currency Ether No native No native XRP ETH

urrency cryptocurrency
with
Use Case Popular with the preferred Runs on a Runs on a Popular
generalized
generalized platform for B28 specialized specialized

distributed applications and


applications and operations, distributed
P2P
mosty used for mainly used in platform for the platform for mostly used for
financial industry the financial and B2C operations.
P2P and B2C enterprise.
operations. needs. industry
needs.

6.5 Blockchain in DeFi : Case Study on any of the Blockchain Platforms


DeFi is a term used to describe major global corporations that incorporate Decentralized Finance (DeFi)
Enterprise
technology into their services, products, and operations.
lending markets based on blockchain-powered financial
It enables institutional investors to easily access new

infrastructure, which was previously impossible.

The financial sector is trying to take lead in blockchain adoption by investing heavily in the technology.

existing legacy technologies, workflows,


and regulatory systems.
We need advanced solutions that incorporate

There are three types of networks : public, private, and federated


to the ledger and can be
be joined and used by anyone. Everyone has access
A public blockchain network can

mechanism.
involved in the consensus

In other words, the authorities decide who can

In blockchain, only one organization has authority.


a private network.
"centralized-decentralized"
the network. Consider
it a
participate in and access
environment.Federated
will gain access to a decentralized private
When you use a federated blockchain, you
financial services, insurance payments,
multi -

party
blockchain. It is used in
blockchain is central to private
industries.
aggression, supply chains, and many other
establish federated networks, with over a dozen
enormous efforts have been made to
Over the last three years,
which use R3 Corda or Hyperledger.
projects, the majority of
have
to use blockchain
without going public. These authority nodes
businesses who want
This is appropriate for block is validated by this
connected by the network. A
from among all the organizations
already been chosen
selected nodes have access to information and areas
Furthermore, this suggests that the
selected group of nodes.
that are restricted.
Tech Kaeuledge
Tools and Applications in Blockchain
6-12
Blockchain (MU)
R3 Corda
A Case Study of the Trade Finance System using is known as trade financing"
of goods
ensure the exchange
credit to trade has increased.
n e method bywhich financial firms qrant of international
as the volume
with little change
it has existed for hundreds of years referred
international trade are
dnd
domestic and
companies to promote
The financial services and equipment used by

to as "trade finance".
transactions are
carried out using third-party
environment is not ideal right now. For instance, at present,
he

applications. multiple copies and the


documentation, including
significant amount of
Furthermore, it may necessitate a

involvement of multiple parties.

Ultimately, simple tasks can take weeks to complete.


financial institutions, trade finance
finance include importers,
exporters,
h e players in the environment of trade

entities, export credit companies, and insurers. Customs Transport


Handling Fim
Good Producers Transport Customs Shipping Bonded Fim and Container Firm
Firm B Bonded Fim
Handling Firm and Warehoise
Warehouse

Container Firm

Distribution
Port Port
Production Center

Transport
Transport Firm D
Firm A

Raw materials
and Buyer
Seller of
components Container Yard Container Yardi
manufacturer. * * ***** w* * *"**** --- Goods
Trade Lifecycle

Advising of LC LC issuance Application for L/C

Export docs Export docs Export docs


presented presented presented

Funds paid Exporter's Funds paid Importers Funds paid


Bank Bank
Exporter Importer
Fig.6.5.1
Current trade finance issues are

oEvery good in the supply chain must be checked for quality on a regular basis.

Throughout the supply chain journe each good must interact with a variety of players and people.
o A product can take up to 30-35 days to travel from farm to retailer. Furthermore, the documents may take up
to ten days to complete.

This leads to incorrect party tracking and fraud, such as fake deliveries.

o Costly throughout, especially when it comes to writing the letter of credit, the process involves banks and
clients. Additionally, disputes are managed improperly and take a long time to settle.

They face a significant regulatory burden because they must manage things, including fraud prevention, KYC
protocols, geopolitical risks, etc.
Tech Kaeuledge
6-13
Blockchain (MU) Tools and Applications in Blockchain
B
Furt
t h e seller finds it difficult to maintain product conditions, introducing product risks.
icks arise as a result of fluctuations in foreign exchange currency rates.
Currencyrisks.

The t r a n s p o
at risk, on the other hand, arises as a result of cargo insurance, which raises the overall cost of the
t r a n s a c t i o n .

be used in Trade Finance?


lockchain (R3 Corda)
H o wC a n B l o c k

B l o c k c h a
has the ential to completely transform trade finance
ensure that
there are no duplicate records.
t cca
ann

additionally, it eliminates any chance of fraud or alteration.

itionally, it ensures a
constant level of trust while increasing visibility.

Shipment of goods
importer Exporter mporter Exporter
Trade contract Freight Inspection
carrier company
Shipment of goods

Blockchain
TF Platform

ic Issue
Documents Payment
Payment
Importers Exporters importer's Exporterrs
Bank Bank Bank Bank

Fig. 6.5.2:Trade Finance System Players and Workflow


How?

wOrthy trading partner can be found by buyers and sellers using blockchain.
a r e then agreed upon by both parties, and the smart contracts are initiated. The order is then initiated
after the smart
contract is created.
avent that the smart contract requirements are satisfied, the buyer bank assumes control at the following
Ocation and will
automatically settle the amount.
To
expedite the settlem
lement process, the seller could request financing from his bank.
The now shipping the goods. Both parties are keeping an eye on the package.
The buyer COnirms the trade, indicating that the condition on the smart contract has been met.
inaly, the seller is
The pro compensated.
ure is straightforward, and as you can see, the majority of the steps are automated in order to maintain

Transparency and trust.


Techu DKaeuledge
4tin
Blockchain (MU) 6 14 Tools and Applications in Blockchain

1 Importer orders goods


3. Importer
arranges LC
with its bank
2. Exporter agrees to fill order.

Exporter Importer
6. Exporter ships goods to importer.

11 Bank x 12.Bank obtains


pays Exporter presents importer's note
13. Importer
draft and documents to pays
Oxporter its bank. Bank X.
and releases
ts bank
shipment
8. Bank X presents draft
and documents to Bank I.
Bank X Bank

9.Bank accepts draft, promising


to pay in 60 days, and returns
accepted draft to Bank X.
5. Bank XX
advises 4. BankI sends
exporter LC to Bank X.
of LIC.
Public
10. Bank X sells Investor
14. Investor presents acceptance
acceptance to investor. and is paid by BankI.
www

Formal documents: Letters of credit (LIC), Bill of


lading (L/C), Drafts

Fig.6.5.3: Trade Process Workflow using Blockchain R3 Corda


The Advantages of Blockchain for Trade Finance
The blockchain trade finance
platform's documents can be checked for
authenticity at any time! It
time for all parties involved. This also helps to save
implies
that fraudulent activities take place.
no

Transparency is also provided by blockchain in trade finance.


There are no middlemen, which improves the overall system by reducing fraud. This increases the banks'
do trade financing without risk or dispute. ability to

Blockchain in trade finance can prevent double spending.


Smart contracts could indeed
help to automate and eliminate time
spent on paperwork. Before smart contracts can
beexecuted on the network, they must be finalized.
Before the smart contract
must meet and finalize the agreement is drafted, both partners
details
Furthermore, the smart contract is only executed when a
predefined condition or set of rules is met.
Blockchain enables buyers and sellers to have proof of
ownership, ensuring transparency and
of the shipment. tracking the location

Requlations could be
managed in a single location. KYC/AML
trade between nations by allowing solutions are included.
for the managementof regulatory differences Additionally, it facilitates
Besides this basic between them.
use case, blockchain is used in tons of trade
Credit, Maritime Trade, etc.
finance use cases
like, international trade-Letter o

Tech Knowledge
Fuhtir 3liGus
Blockchain (MU)
6-15
real-wo. use-cases are TMX, and Tools
R3
Corda
Payments Canada, Maersk, Applications in Blockchain
NatWest,
Blockchain advantages for the CrowellMoring, and Swift.
trade finance

Real timne
previewing and
Transparent No
factoring No double
reviewing9 intermediates
spending

Smart contract Proot of Regulations


execution Ownership

Fig. 6.5.4

Review Questlons
1Explain R3 Corda blockchain platform with advantages and disadvantages.
.2
Explain Ripple blockchain platform.
*Which are the different emerging blockchain platforms are available? Differentiate all the platforms?

How blockchain can be used in decentralized financial application?


Q5
Explain Quorum blockchain platform with advantages and disadvantages.
OO0

You might also like