BCT Techknowledge
BCT Techknowledge
Module
.1-12
************************************************************ ****.
************°° °*°*°*°°°°°7****°°9****
"1-13
.1-16
*******************************
1.8.5 Comparison between Public, Private and Consortium Blockchain. o****** *********************************** 17
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
Tech Kuouled
L t i e
Blockchain (MU) Table of Contents
2.5.1 Altcoins.. **************************************************************** *************************
**********************************
-7
2.14/Life of a Miner..
*****.eo*****eeeeco**ee*s****o*e***ee*****eee****. *******************ee***oeesnoeaesosseasass***esansoosacoosenesseaaaaeeaseeseessaaaasesae.2-29
Module ll
Tech Kaouledge
4 Table of Contents
Blockchain (MU)
3.3 Structure of a Smart Contract.
********************e***************************°*********** **°° °o°
*******************s*
.3-5
***
*3-10
********°***°°****°***°******°°**°°***°°**
*******so*****************************************e..
..*******************************************e.3-11
3.6.1 Basics ****
** -13
Variables..
** *********************************************
3.6.3
************ ******
-16
3.6.4
************************
22
Special Arrays: Bytes and Strings.
********
3.6.6 *************"******"******
3.6.8 Structs...
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * .
**************"**** .3-23
.3-24
3.69 Mapping ***********
*************************
*****************************.
Module IVV
*****************************.***********a * n* ******************* .
********************************* 4-30)
Module V
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
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.6 onsensus Algorithms for Private Blockchain -PAXOS and RAFT. 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-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
Module VI
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
Syllabus
Introduction to Smart Contracts, Types of Smart Contracts, Structure of a Smart Contract, Smas
3.1
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
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.
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.
o Real-time updates are supported and they are simple and faster.
o As they execute automatically, there is no delay in producing expected and agreed outcome.
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
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.
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.
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
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
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
organizations.
Autonomous The DAO code after deployment, cannot be controlled by its creator or any outsiders.
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.
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 .
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.
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
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
BE Technowledge
Blockchain (MU)
3-7 Programming for Blocke.
kchain
pragma solidity ^0.8.2;
contract myContract(
varlable unsigned integer type//.
uint myData://State
-
contract Customer {
string id = 34;
Function getID) is a getter function, as it creates a call that returns the value of the state variable.
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 {
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.
Enum Types: Enum is used to create custom types and it has fixed the set of values
import "browser/ERC20.sol";
contract MyFirstToken is ERC20 {
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;
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
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
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
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
the contract needs the mutual consent of the involved parties. There is no scope of manipulation or non
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
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.
Boolean (bool)
Boolean value is either true or false. Following are the logical operators used.
&8& and
or
equal
not equal
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
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
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
constructorO public
uint b = 2;
uint result = a + b;
return result;
State Variable
constructorO public {
stored Data = 10; // Using State variable
Local Varlable
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
.
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.gas: The amount of gas left in the gas supply of this execution environment. This was deprecated in Solidity
msg.sig(bytes4) : The first four bytes of the data payload, which is the function selector.
Transaction context
Pubiltalie
Programming for B i c n a a
Blockchain (MU) 3-16
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.
Address Object
metno0s
object, has number of attributes and
Any address, either passed as an input or cast from a contract a
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
Example
pragma solidity ^0.8.2;
Tec eie
contract C {
Progra ing for Blodkc
3-17
Blockchain (MU)
uint public data = 30;
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) {
uint a =
1:// local variable
uintb 2;
uint resut = a + b;
Arithmetic Operators
Operator Meaning
Addition
Subtraction
Multiplication
Division
TechNinaes
Pattnr
Programming for Blockchain
Blockchain (MU) 3- 18
Operator Meaning
% Modulus
Increment
Decrement
Comparison Operators
Operator Meaning
Greater than
Less than
Bitwise Operators
Operator Meaning9
& Boolean AND
Boolean OR
Boolean exclusive OR
Bitwise NOT
Left Shift
Right Shift
Assignment Operators
Operator Meaning
Simple Assignment
+ Add 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.
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.
90];
datal [uint(10), 20, 30, 40, 50, 60:
return (data, data1);
Output
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": "
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):
assertla.length == 7);
assert(b.length == len):
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:
ContractSampleBytesArray
1/ as a state variable
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:
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 {
FreshJuiceSize choice;
FreshjuiceSize constant defaultChoice FreshjuiceSize.MEDIUM;
function setLarge0 public{
choice FreshJuiceSize.LARGE;
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
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
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
*
:******:
:
uint8 marks; *
.
**
1/ Creating a mapping
mapping (
address=> 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
=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
I/ Creating mapping
mapping (address => student) result;
address[] student result
Programming tor Blockchat
Blockchain (MU) 3-27
student.name = "John";
student.subject = "Chemistry";
student.marks = 88;
studentresult.push(
OxDEE7796E89C82C36BAdd1375076139D69FafE252)-1;
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
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.
Emitting events.
o Creating other contracts.
oUsingselfdestruct.
Sending Ether via calls.
o
Calling any function which is not marked view or pure.
Example
pragma solidity ^0.8.2
contract Test (
Tecat i
tedi
n
Progranming 1o Blockcha
Cain
3-29
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
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:
contract Sample {
uint amount =0;
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.
Example:
contract Sample {
function0 payable {
I/sample fallback
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:
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);
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);
uint b 2;
uint result = a + b;
return result;
Output
0: uint256:3
Pubuati
chain (MUJ 3-34
Programming for Blockchain
l/public state variable
constructor0 pubiic{
info 10
I/private function
I/Derived Contract
contractE is C{
uint private result;
Cprivate c;
constructor0 public{
c= new CO:
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
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.
modifier onlySeller0{
require(
msg.sender == seller,
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
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.
constituency code.
Valid voter initiates the voting process and will be allowed to vote if following conditions holds.
2.
lfage 18 years
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.
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
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.
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.
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.
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.
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
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.
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
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.
METAMASK
Networks
OETH
Main Ethereum Network
Account1 Rap sten Yest Networ
e e b y Test Neheork
OETH e YestNetwr
Locattost 85
uto R
Deposit Ether
Test Fauce
oA EUnr lnwm a lmmet tav the
Hapalea
faucet
transactions
Account 1
1ETH
epase Ses
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 =>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;
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
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.
T o make your smart contract live, switch to the main ethereum network at metamask
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
Blockchain can be divided into two main categories according to accessing and managing permissions.
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
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
What is Ether?
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
Peer to
Peer
Network
State
Machine Nodes
Components
of Ethereum
Consensus
Ruies Transactions
Consensus
Aigonthim
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
AAN
r g tkre DeReen Emereum, the skbdscan biages
Layea 2 andother cnans liOnserougn t
PR
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
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
Transacticon details
Transaction initiated broadcasted to miners
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
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
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.
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 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
Ethereum Compiler
Fig. 4.5.1
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.
When we install and launch the geth, parity, or any other client, the EVM is launched and begins synchronizing,
veriying, and executing transactions.
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
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
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
Sender, recipient, and contract accounts are all involved in every transaction.
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
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
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)
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.
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.
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
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
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.
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
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
Signature size 512 bits (64 bytes) Signature size 520 bits (65 bytes)
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.
Mining reward 12,5 Bitcoin per block Mining reward 3 Ether plus some other rewards
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
Network V
Main Ethereu
Neto
acons is Mar
Man 2he
34356 ETH
KovantTestNerwork
O CustomRPC
tontracr teraCtON OETH
Approve -0 ETH
$0 e0 uSOD
116 1/1/2019 at 20 49
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.
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.
**
M
4m r
Extension
aya
Metaas
MetaMask
tp imetam ath 1 featured
o
now Ethereum wallet is in your browser.
feh Kueuledg
Blockchain (MU) 4 18 Public Blockchain
Welcome to MetuMusk
METAMASK
New to MetaMask?
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
METARASK
OETH
S
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
Now we need account no, So click on Connect Wallet and choose Metamask
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.
Requestcamplete
Now will go to Metamask account and we can see, I have 0.1 ETH in my account.
inkebyETH
ACTiWT
ecoaldpe
Pudin l n be hain
NETARAN
**p
0.1 RinkebyllTH
Ae
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
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.
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
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.
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
Struffle init
y our scaffold
commands to get started:
truffle create contr YourContractName #scaffold acontract
Strufle create test
YourTestName # scaffold a test
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
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
Documentation: https://embark.status.im/docs/
Embark installation
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
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;
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
Order_sent, Order_delivered
First and foremost, let us define variables and structs. Essentially, we need pizza store and customer addresses, as
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.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.
For Ethereum. a decentralised platform for smart contracts, Etherscan is the top Blockchain Explorer, Search, APL
and Analytics Platform.
ETHERSCAN
The Lthereum Btocktxplorer
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
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.
Btherscan
$1.052 45 4
162531 7 e
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
**
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
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.
**
**************
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
Tech Kemledgi
Blockchain (MU) 4-34 Public Blockchain
Bhercan
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.
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
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
.
• Complete privacy Private blod«:hain concentrates on privacy issues
reply l(x)
Fig. 5.5.1
• But there can be a single point failure .
_____,,,.,..- request x
Client J
Fig. 5.5.2
• State machine replication gives safety and liveness by creating replicas of state of servers.
• 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
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.
Consensus
Module
[ill9
~~wu
0
,_ : : 1 -....___/'
l , Log
: resu ll
•• State
: · Machine
Clients
Fig. 5.5.4
.
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.
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
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
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.
Fig. 5.6.1
'••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
• 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?
• 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) .
• 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.
Consensus State
module machine
~ 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
• 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.
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
• 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.
• 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.
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.._
• 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
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.
• 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.
• 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
• 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
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.
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_ __ _ _ _ _ _ _ _ __ _ _ _ __ _ _ _ __ ____
~
--------------------------------------.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.
</> .
\ 7
Fig. 5.10.1
-
Governance
language
R3 company in
language
- - -- - - -- - - - - - - - - - - - - - - - - - - - -----=- --
. ,,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
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
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.
E1c1e1nal•CA
optio~ I * Momborst1Jp
PA! rYl(.OS
opUonat.
Client SOK
f;Morser )
Appllcation (HFC)
,/
Comrn irter )
DEHJ
Ladger
• 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
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 .
• 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
• Peer is the place where the ledger and the blockchain data is stored .
• 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 :
.,.........
El\dors1 ng Peers:
• A unique category of committing peers called endorsing peers has the additional responsibility of endorsing a
transaction.
• Each endorsing peer has a ledger and a copy of the smart contract installed .
• 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.
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.
• 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.
; aw-a; .,uu ⇒ AW ■ d
Fig. 5.12.2
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
• 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.
Transaction Flows
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
~
~ Endorser p
eer Hyper1 edger Fab nc Work
F.: w
:7o
-=:
~ Prter J
Anchor Pe «
_J
•·'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 - --- @ - -• ~ ~
,., !~ ,~~·~~-
, ; 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
• 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
node -version
Git Installation
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
pip --versio n
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:
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
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
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
tions initialized
Channels peers has jotned:
testchannel
command.
to run below
Step
P: lo stop the network, you need
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
5-27
Blockchain (MU)
create couchdb
container for edc
and
mmand
starts your network
Step 4: Create new channel by using below command.
Step 5:To stop the network, you need to run below command.
Application
Writing Your First
HYPERLEDGER
FABRIC f youre not yet familiar
with the fundamental
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
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
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?
Traceability exists
Streamline transaction process
Here we will discuss the most famous application and case study of food product supply chain industry that wa
ent
satering a usename and password to access the website, Price Authority publishes the price information for a
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
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/
o (version +1.8)
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
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
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
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.
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.
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
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.
Advantages of Corda
Disadvantage of Corda
Because the Corda framework is tailored to the financial sector, the project's target audience is limited to financia
institutions.
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
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.
ommission
Advamtages of Ripphe
Teleas
Blockchain (MU) 6-5 Tools and Applications in Blockchain
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.
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?
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.
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.
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
required.
Public Ethereum had some challenges in adoption with an enterprise environment that quorum addresses, which
includes privacy, speed, and throughput.
Features of Quorum
Community -
It leverages the world's largest pool of blockchain developers.
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
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.
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
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
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
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.
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.
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
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
Protocol voting
urrency cryptocurrency
with
Use Case Popular with the preferred Runs on a Runs on a Popular
generalized
generalized platform for B28 specialized specialized
The financial sector is trying to take lead in blockchain adoption by investing heavily in the technology.
mechanism.
involved in the consensus
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
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
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 .
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
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
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
Exporter Importer
6. Exporter ships goods to importer.
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
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?