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

Blockchain Merged

Uploaded by

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

Blockchain Merged

Uploaded by

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

Blockchain and its applications

Prof. Sandip Chakraborty


Department of Computer Science & Engineering

Lecture 01: The Model of Decentralization


• The Blockchain Myths
• Decentralization – A Use-case
• Cryptocurrency
• Blockchain
• Supply Chain Management
• Decentralization
The Blockchain Myth

• Blockchain ≠ Bitcoin (or any other cryptocurrencies)


• If you want to take this course to trade cryptocurrencies, this
course is not for you !!
• We do not want to argue on the legal issues of
cryptocurrencies -- We want to learn the technology and its
applications
The Blockchain Myth

• Anything and everything in the world cannot be solved using a


blockchain
• Blockchain is good but it cannot change the society in a week or
a month or a year
• "Want to prevent fraud and corruption? Use Blockchain" --
Unfortunately, you are wrong! There can be a better
technology to solve your problem ...
The Blockchain Myth

• You cannot replace a database with a blockchain


• Blockchain is not a distributed database
• Blockchain is not designed to securely store ANY data
Why this course ...

• To avoid all the hypes and apply Blockchain as a solution at the right
place ...
Why this course ...

• To avoid all the hypes and apply Blockchain as a solution at the right
place ...

So, what is the


right place?
Decentralization – When Do you Need It?
Supply Chain Management -- A Use Case
Supply Chain in Petroleum Industry

Crude
Purchase
Supply Chain in Petroleum Industry

Crude Crude
Purchase Transportation
Supply Chain in Petroleum Industry

Crude Crude Crude


Purchase Transportation Storage
Supply Chain in Petroleum Industry

Crude Crude Crude


Purchase Transportation Storage

Refining
Supply Chain in Petroleum Industry

Crude Crude Crude


Purchase Transportation Storage

Distribution Refining
Supply Chain in Petroleum Industry

Crude Crude Crude


Purchase Transportation Storage

Retail Distribution Refining


Petroleum Supply Chain in India
Ministry of Petroleum and Natural Gas

Upstream Downstream
Exploration and Industry Refining and
Production Marketing
Bodies
Petroleum Supply Chain in India

ONGC
Upstream OVL
Exploration and
Production
Oil India Ltd
Pvt E&P Co
Petroleum Supply Chain in India

Indian Oil Bharat Petr.


Downstream CPCL, BRPL NRL
Refining and
Marketing Hindustan
Reliance
Ind. Ltd Petr.
MRPL
Petroleum Supply Chain in India

• Petroleum Planning and Analysis


Cell
Industry • Center for High Technology
Bodies • PRCA
• PetroFed
• Oil industry Safety Directorate
• Petroleum India International
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production shortfall from other players
• Objective of each production unit would be to maximize the
throughput and its margin
• Procurement would purchase the feedstock with not the
best yields at lowest cost
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production shortfall from other players
Needs Strong Coordination among the Players
• Objective of each production unit would be to maximize the
throughput and its margin
• Procurement would purchase the feedstock with not the
best yields at lowest cost
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production
How do weshortfall
obtain from other players
Real-time Information from the
• Objective of each production
Stakeholders?
unit would be to maximize the
throughput and its margin
• Procurement would purchase the feedstock with not the
best yields at lowest cost
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production shortfall from other players
How do we obtain Real-time Information from the
• Objective of each production unit would be to maximize the
throughput and its Stakeholders?
margin
A web-based
• Procurement would portal?
purchase the feedstock with not the
best yields at lowest cost
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production
How shortfallReal-time
do we obtain from other players
Information from the
• Objective of each production
Stakeholders?
unit would be to maximize the
throughput
What is theandguarantee
its margin that the information
• Procurement would purchase
submitted the feedstock with not the
is correct?
best yields at lowest cost
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production
How shortfallReal-time
do we obtain from other players
Information from the
• Objective of each production unit would be to maximize the
Stakeholders?
throughput and its margin
What is the guarantee that the information
• Procurement would purchase the feedstock with not the
submitted is correct?
best yields at lowest cost
What if someone denies the information later on?
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production
How shortfallReal-time
do we obtain from other players
Information from the
• Objective of each production unit would be to maximize the
Stakeholders?
throughput and its margin
• Procurement would purchase the feedstock with not the
We need a decentralized solution – Noone trust
best yields at lowest cost
each other, but they should cooperate
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production shortfall from other players
• Objective of each production unit would be to maximize the
throughput and its margin
Blockchain is the answer !!
• Procurement would purchase the feedstock with not the
best yields at lowest cost
Conclusion – Decentralization and Blockchain

• You have a network of different players (businesses, enterprises,


commercial establishments, Government or Private bodies, or even
the individuals)
• Everyone has their own interest – they want to fulfill their goal
• They do not trust each other
• If they cooperate, the society gets benefited
• Trustless Decentralization = Blockchain
Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering

Lecture 02: What is Blockchain


• Decentralization with a Blockchain

• Fundamental Properties of Blockchain

• Formal Definition of a Blockchain


• Decentralization
• Properties
• Definition
Requirements for a Successful Supply Chain
• Minimization of material procurement
• Maximization of manufacturing capacity and sales
• Meet demand numbers
• Respond quickly to market opportunity by purchasing the
production shortfall from other players
Needs Strong Coordination among the Players
• Objective of each production unit would be to maximize the
throughput and its margin
• Procurement would purchase the feedstock with not the
best yields at lowest cost
Moving towards Decentralization ...
Moving towards Decentralization ...
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
from Mumbai High to HPCL
Refinery on Dec 26, 2020 at
2:30 pm
Moving towards Decentralization ...

- 120432 barrels produced


The board has at Mumbai High on Dec 26,
infinite space, 2020

you do not - 16467 barrels transported


from Mumbai High to HPCL
need to erase Refinery on Dec 26, 2020 at
anything! 2:30 pm
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
Everyone - 16467 barrels transported
can see all from Mumbai High to HPCL
Refinery on Dec 26, 2020 at
the logs 2:30 pm
and verify
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
Any change - 16467 barrels transported
in information from Mumbai High to HPCL
Refinery on Dec 26, 2020 at
is visible 2:30 pm
to everyone
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020

The board is not - 16467 barrels transported


from Mumbai High to HPCL
erasable, no Refinery on Dec 26, 2020 at
one can deny 2:30 pm

later
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
from Mumbai High to HPCL
Simple one-step Refinery on Dec 26, 2020 at
auditing 2:30 pm
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
Who will maintain
from MumbaithisHigh to bulletin
HPCL board?
Refinery on Dec 26, 2020 at
2:30 pm
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020

Who will maintain this bulletin board?


- 16467 barrels transported
from Mumbai High to HPCL

- Buy Refinery
Cloud
2:30 pm
on Dec 26, 2020 at
from amazon
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020

Who will maintain this bulletin board?


- 16467 barrels transported
from Mumbai High to HPCL

- Buy Refinery
Cloud
2:30 pm
on Dec 26, 2020 at
from amazon
Who will manage it and provide the cost?
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
from Mumbai High to HPCL
Who will maintain this bulletin board?
Refinery on Dec 26, 2020 at
2:30 pm
- One of the enterprises maintain a private cloud
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
Who will maintain
from Mumbai this
High tobulletin
HPCL board?
Refinery on Dec 26, 2020 at
- One of the enterprises maintain a private cloud
2:30 pm

What is the guarantee that it is not a fraud?


Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
Who will maintain this
- 16467 barrels bulletin board?
transported
from Mumbai High to HPCL
Let everyone maintain
Refinery the
2:30 pm
on Dec same
26, 2020 atcopy of the board

individually and independently


Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
Who will maintain this
- 16467 barrels bulletin board?
transported
from Mumbai High to HPCL
Refinery on Dec 26, 2020 at
2:30 pm
Let everyone maintain the same copy of the
board individually and independently
BUT HOW?
Moving towards Decentralization ...

- 120432 barrels produced


at Mumbai High on Dec 26,
2020
- 16467 barrels transported
from Mumbai High to HPCL
Refinery on Dec 26, 2020 at
2:30 pm
Moving towards Decentralization ...
Moving towards Decentralization ...
No one is the sole-
owner of the data,
but everyone has a
copy of the data -
there is no central
database
Moving towards Decentralization ...
Everyone
holds exactly the
same copy of the
data at the same
instance of the time
What is a Blockchain?
An immutable append-only
ever-growing chain of data.
Data once added cannot
be deleted or modified later
What is a Blockchain?
There is no central database to
store the chain – everyone keeps a
copy of the chain and process data
locally
What is a Blockchain?
New information is added to
the chain in the form of new
blocks
What is a Blockchain?
Blockchain ensures that every
party has the same view of the
blockchain always
What is a Blockchain?
The Information is transparent to
everyone – so everyone can verify
and validate
Conclusion: Formally Defining a Blockchain

A decentralized immutable append-


only public ledger
Conclusion

• We got a broad idea of a blockchain and its possible use


cases (beyond cryptocurrencies)

• We next learn some fundamental cryptographic


techniques used in the design of a blockchain ...
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 03: Basic Cryptographic Primitives - I


• Cryptographic Primitives useful for Blockchain
• Hash Functions
• Hash Function
• SHA-256
• Puzzle Friendly
What You’ll Learn
• Basic cryptographic primitives behind blockchain
technology
– Cryptographically Secure Hash Functions
– Digital Signature
• Hash Function: Used to connect the “blocks” in a
“chain” in a tamper-proof way
• Digital Signature: Digitally sign the data so that no
one can “deny” about their own activities. Also,
others can check whether it is authentic.
Cryptographic Hash Functions

• Takes any arbitrarily sized string as input


Input M: The message

• Fixed size output (We typically use 256 bits in


Blockchain)
Output H(M): We call this as the message digest

• Efficiently computable
Cryptographic Hash Functions: Properties

• Deterministic
Always yields identical hash value for identical input data
• Collision-Free
If two messages are different, then their digests also differ
• Hiding
Hide the original message; remember about the avalanche
effect
• Puzzle-friendly
Given X and Y, find out k such that 𝑌 = 𝐻(𝑋| 𝑘 - used to
solve the mining puzzle in Bitcoin Proof of Work
Collision Free
• Hash functions are one-way; Given an 𝑥, it is easy to find
𝐻(𝑥). However, given an 𝐻(𝑥), one cannot find 𝑥

• It is difficult to find 𝑥 and 𝑦, where 𝑥 ≠ 𝑦, but 𝐻 𝑥 = 𝐻(𝑦)

• Note the phrase difficult to find, collision is not impossible

• Try with randomly chosen inputs to find out a collision – but it


takes too long
Collision Free – How Do We Guarantee
• It may be relatively easy to find collision for some hash
functions
• Birthday Paradox: Find the probability that in a set of 𝑛
randomly chosen persons, some of them will have the same
birthday
• By Pigeonhole Principle, the probability reaches 1 when
number of people reaches 366 (not a leap year) or 367 (a leap
year)
• 0.999 probability is reached with just ~70 people, and 0.5
probability is reached with only ~23 people
Collision Free – How Do We Guarantee

• Birthday paradox places an upper bound on collision


resistance
• If a hash function produces 𝑁 bits of output, an attacker
𝑁
needs to compute only 2 hash operations on a random
2

input to find two matching outputs with probability > 0.98


• For a 256 bit hash function, the attacker needs to compute
2128 hash operations – this is significantly time consuming
• If every hash computation takes only 1 microsecond, it will
need ~1025 years
Hash as a Message Digest

• If we observe 𝐻 𝑥 = 𝐻(𝑦), it is safe to assume 𝑥 = 𝑦

• We need to remember just the hash value rather than the


entire message – we call this as the message digest

• To check if two messages 𝑥 and 𝑦 are same, i. e. , whether 𝑥 =


y, simply check if 𝐻 𝑥 = 𝐻(𝑦)

• This is efficient because the size of the digest is significantly


less than the size of the original messages
Hashing - Illustration

http://www.blockchain-basics.com/HashFunctions.html

Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher


Information Hiding through Hashing

• Given an 𝐻(𝑥), it is “computationally difficult” to find 𝑥

• The difficulty depends on the size of the message digests

• Hiding helps to commit a value and then check it later

• Compute the message digest and store it in a digest store –


commit

• To check whether a message has been committed, match the


message digest at the digest store
Message Commitment through Multiple Parties

Alice Bob Jane

H(M,KA),M,KA H(M,KA),M,KA

Commit Verify Verify

KA is the public key of Alice – A public identity that only Alice can have
Puzzle Friendly

• Say 𝑀 is chosen from a widely spread distribution; it is


computationally difficult to find a 𝑘, such that 𝑍 = 𝐻(𝑀||𝑘),
where 𝑀 and 𝑍 are known a priori.
• A Search Puzzle (Used in Bitcoin Mining)
𝑀 and 𝑍 are given, 𝑘 is the search solution
Note: It might be not exactly a particular value Z, but some
properties that Z satisfies, i.e., Z could be a set of possible
values
• Puzzle friendly property implies that random searching is the
best strategy to solve the above puzzle
• Discussed what a cryptographic hash function is
• Properties of hash functions
• Uses of hash functions
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 04: Basic Cryptographic Primitives - II


• Cryptographic Hash Functions
• SHA-256
• Types of Hashing
• Hash Function
• Secure Hash Algorithm
• Patterns of Hashing Data
Hash Function – SHA256

• SHA256 is used in Bitcoin mining – to construct the Bitcoin


blockchain

• Secure Hash Algorithm (SHA) that generates 256 bit message


digest

• A part of SHA-2, a set of cryptographic hash functions


designed by United States National Security Agency (NSA)
SHA256 Algorithm - Preprocessing
• Pad the message such that the message size is a multiple of 512
• Suppose that the length of the message M is 𝑙; and 𝑙 𝑚𝑜𝑑
512≠0
• Append the bit “1” at the end of the message
• Append 𝑘 zero bits, where 𝑘 is the smallest non-negative
solution to the equation 𝑙+1+𝑘≡448 𝑚𝑜𝑑 512
• Append the 64-bit block which is equal to the number 𝑙
written in binary
• The total length gets divisible by 512
• Partition the message into 𝑵 512-bit blocks 𝑴(𝟏) , 𝑴(𝟐) ,…, 𝑴(𝑵)
(𝒊)
• Every 512 bit block is further divided into 32 bit sub-blocks 𝑴𝟎 ,
(𝒊) (𝒊)
𝑴𝟏 ,…, 𝑴𝟏𝟓
SHA-256 Algorithm

• The message blocks are processed one at a time

• Start with a fix initial hash value 𝐻(0)

• Sequentially compute 𝐻 (𝑖) = 𝐻(𝑖−1) + 𝐶𝑀 𝑖 (𝐻 𝑖−1 ); 𝐶 is


the SHA-256 compression function and + means mod 232
addition. 𝐻(𝑁) is the hash of 𝑀.
SHA-256 Algorithm

M(0) M(1) M(N)

Message
Digest
256 bit
Initialization
Vector
C C C
Patterns of Hashing Data
• Independent hashing
• Repeated hashing
• Combined hashing
• Sequential hashing
• Hierarchical hashing
Types of Hashing

• Independent hashing

• Repeated hashing
Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher
Types of Hashing

Combined hashing

Sequential hashing

Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher


Types of Hashing

Hierarchical hashing

Illustration
http://www.blockchain-basics.com/HashFunctions.html

Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher


• Discussed implementation of hash functions
• Types of hashing
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 05: Basic Cryptographic Primitives - III


• Cryptographic Hash Functions
• Hash Pointers
• Hashchain
• Construction of Chain of Blocks
• Hash Function
• Hash Pointer
• Merkle Tree
• Blocks
Hash Pointer
• A Cryptographic Hash Pointer (Often called Hash Reference)
is a pointer to a location where
• Some information is stored
• Hash of the information is stored

• With the hash pointer, we can


• Retrieve the information
• Check that the information has not been modified (by
computing the message digest and then matching the
digest with the stored hash value)
Hash Pointer
H(DATA)

DATA
Hash Pointer

Reminds you of a linked list??

Reference: Coursera course on Bitcoin and Cryptocurrency Technologies


Tamper Detection using Hash Pointer

Analogies in real life??


Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher
Making Tampering a Hash Chain Computationally Challenging

Illustration
http://www.blockchain-basics.com/HashFunctions.html

Courtesy: Blockchain Basics: A Non-Technical Introduction in 25 Steps by Daniel Drescher


Detect Tampering from Hash Pointers - Hashchain

H(D(i-1)) H(D(i)) H(D(i+1))

D(i) D(i+1) D(i+2)


Merkle Tree – Organization of Hash Pointers in a Tree
Root Hash
Merkle Root
Hroot=Hash(H0+H1)

L1 Hash L1 Hash
H0= Hash(H00+H01) H1=Hash(H10+H11)

L2 Hash L2 Hash L2 Hash L2 Hash


H00=Hash(T1) H01=Hash(T2) H10=Hash(T3) H11=Hash(T4)

T1 T2 T3 T4
Blockchain as a Hashchain

Block Header Block Header Block Header

Previous Previous Previous


Hash
Nonce Hash
Nonce Hash
Nonce

Merkle Block Merkle Block Merkle Block


Root Hash Root Hash Root Hash
• We have discussed the basic concepts of hash pointers
• Seen how it makes data tamperproof
• Construction of hashchain
• Merkle Tree definition
• Formation of a chain of blocks
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 06: Basic Cryptographic Primitives - IV


• Basic Concepts of Cryptography
• Public Key Cryptography
• Encryption and Decryption using Public Key Cryptography
• Digital Signature
• Public Key Cryptography
• RSA
What we have learnt so far
• Cryptographically Secure Hash Function
• Collision Free
• Information Hiding
• Puzzle Friendly

• Hash Pointers and Data Structures


• Hashchain
• Hash Tree – Merkle Tree
Basic Concepts of Cryptography
• Symmetric Key Cryptography
• Same key used for encryption and decryption
• How to share the key securely
• Cannot address certain requirements

• Public Key Cryptography


• One key for encryption, one for decryption
• Handles several requirements like those in blockchain
Digital Signature
• A digital code, which can be included with an electronically
transmitted document to verify
• The content of the document is authenticated
• The identity of the sender
• Prevent non-repudiation – sender will not be able to
deny about the origin of the document
Purpose of Digital Signature
• Only the signing authority can sign a document, but everyone
can verify the signature

• Signature is associated with the particular document


• Signature of one document cannot be transferred to
another document
Public Key Cryptography
• Also known as asymmetrical cryptography or asymmetric
key cryptography

• Key: A parameter that determines the functional output of a


cryptography algorithm
• Encryption: The key is used to convert a plain-text to a
cypher-text; 𝑀′ = 𝐸 𝑀, 𝑘
• Decryption: The key is used to convert the cypher-text
to the original plain text; 𝑀 = 𝐷 𝑀′, 𝑘
Public Key Cryptography
• Properties of a cryptographic key (you need to prevent it
from being guessed)
• Generate the key truly randomly so that the attacker
cannot guess it
• The key should be of sufficient length – increasing the
length makes the key difficult to guess
• The key should contain sufficient entropy, all the bits in
the key should be equally random
Public Key Cryptography
• Two keys are used
• Private key: Only Alice has her private key
• Public key: “Public” to everyone – everyone knows
Alice’s public key
Encrypt the message Decrypt the
with Bob’s public key message with his
𝑴′ = 𝑬(𝑴, 𝑲𝑩 𝒑𝒖𝒃 )
private key
𝑴 = 𝑫(𝑴′, 𝑲𝑩 𝒑𝒓𝒊 )

M’
Public Key Encryption - RSA
• Named over (Ron) Rivest – (Adi) Shamir – (Leonard) Adleman
– inventors of the public key cryptosystem

• The encryption key is public and decryption key is kept secret


(private key)
• Anyone can encrypt the data
• Only the intended receiver can decrypt the data
RSA Algorithm
• Four phases
• Key generation
• Key distribution
• Encryption
• Decryption

Image source: https://commons.wikimedia.org/


Public and Private Keys in RSA
• It is feasible to find three very large positive integers 𝑒, 𝑑
and 𝑛; such that modular exponentiation for integers 𝑚 (0 ≤
𝑚 < 𝑛):
𝑚𝑒 𝑑 ≡ 𝑚 (𝑚𝑜𝑑 𝑛)
• Even if you know 𝑒, 𝑛 and 𝑚; it is extremely difficult to find 𝑑
• Note that
𝑒
𝑚𝑒 𝑑 ≡ 𝑚 𝑚𝑜𝑑 𝑛 = 𝑚𝑑 ≡ 𝑚 (𝑚𝑜𝑑 𝑛)
• (𝑒, 𝑛) is used as the public key and (𝑑, 𝑛) is used as the
private key. 𝑚 is the message that needs to be encrypted.
RSA Key Generation and Distribution
• Chose two distinct prime integers 𝑝 and 𝑞
• 𝑝 and 𝑞 should be chosen at random to ensure tight
security
• Compute 𝑛 = 𝑝𝑞; 𝑛 is used as the modulus, the length of 𝑛 is
called the key length
• Compute 𝜙 𝑛 = (𝑝 − 1)(𝑞 − 1) (Euler totient function)
• Choose an integer 𝑒 such that 1 < 𝑒 < 𝜙(𝑛) and
gcd 𝑒, 𝜙 𝑛 = 1; 𝑒 and 𝜙(𝑛) are co-prime
• Determine 𝑑 ≡ 𝑒 −1 (𝑚𝑜𝑑 𝜙 𝑛 ) : 𝑑 is the modular
multiplicative inverse of 𝑒(𝑚𝑜𝑑 𝜙 𝑛 )
[Note 𝑑. 𝑒 ≡ 1(𝑚𝑜𝑑 𝜙 𝑛 )]
• We have discussed the basic concepts of public key
cryptography
• How to generate keys in RSA
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 07: Basic Cryptographic Primitives - V


• RSA Encryption and Decryption
• Digital Signature
• Hashing and Digital Signature
• RSA
• Digital Signature
RSA Encryption and Decryption
• Let 𝑚 be the integer representation of a message 𝑀.

• Encryption with public key (𝒆, 𝒏)


• 𝑐 ≡ 𝑚𝑒 (𝑚𝑜𝑑 𝑛)

• Decryption with private key (𝒅, 𝒏)


• 𝑚 ≡ 𝑐 𝑑 𝑚𝑜𝑑 𝑛 ≡ 𝑚𝑒 𝑑 (𝑚𝑜𝑑 𝑛)
RSA Encryption and Decryption - Example
Key Selection
• Select 2 prime numbers: p=17, q=11
• Calculate n=pq=17×11=187
• Calculate f(n)=(p-1)(q-1)=16×10=160
• Select e such that e is relatively prime to f(n)=160 and
less than f(n); Let e=7
• Determine d such that d.e ≡ 1 mod 160 and d<160; Can
determine d = 23 since 23×7 = 161 = 1×160+1
RSA Encryption and Decryption - Example
Encryption of Plaintext M = 88
• C=887 mod 187
• = [(884 mod 187)×(882 mod 187)×(881 mod 187)] mod
187 = (88×77×132) mod 187 = 11
Decryption of Ciphertext C = 11
• M=1123 mod 187
• =[(111 mod 187)×(112 mod 187) ×(114 mod 187) ×(118
mod 187) ×(118 mod 187)] mod 187
• =(11×121×55×33×33) mod 187 = (79720245) mod 187 =
88
RSA Encryption and Decryption - Illustration
https://www.devglan.com/online-tools/rsa-encryption-decryption
Digital Signature using Public Key Cryptography
• Sign the message using the Private key
• Only Alice can know her private key
• Verify the signature using the Public key
• Everyone has Alice’s public key and they can verify the
signature
Sign the message Verify the
with her private key signature using
𝑴′ = 𝑬(𝑴, 𝑲𝑨𝒑𝒓𝒊 ) Alice’s public key
𝑴 = 𝑬(𝑴′, 𝑲𝑨𝒑𝒖𝒃)

M, M’
Reduce the Signature Size
• Use the message digest to sign, instead of the original
message

M, S

Sign the message with Verify the signature using


her private key Alice’s public key
𝑺 = 𝑬(𝑯(𝑴), 𝑲𝑨𝒑𝒓𝒊 ) 𝑯(𝑴) = 𝑬(𝑺, 𝑲𝑨𝒑𝒖𝒃 )
Digital Signature - Illustration
https://www.devglan.com/online-tools/rsa-encryption-decryption

http://www.blockchain-basics.com/HashFunctions.html
Digital Signature in Blockchain
• Used to validate the origin of a transaction
• Prevent non-repudiation
• Alice cannot deny her own transactions
• No one else can claim Alice’s transaction as his/her
own transaction

• Bitcoin uses Elliptic Curve Digital Signature Algorithm (ECDSA)


• Based on elliptic curve cryptography
• Supports good randomness in key generation
A Cryptocurrency using Hashchain and Digital Signatures

A:10, Sig(A)

• Alice generates 10 coins


• Sign the transaction A:10 using Alice’s private key and put
that in the blockchain
A Cryptocurrency using Hashchain and Digital Signatures

H(0) H(1)
A:10, Sig(A) A->B:5, Sig(A)

• Alice transfers 5 coins to Bob


• Sign the transaction A-B:5 using Alice’s private key and put
that in the blockchain
• We have shown how to encrypt and decrypt using public
key cryptography
• Application in digital signature
• Use of digital signature in blockchain
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering

Lecture 08: Distributed Systems for Decentralization –


The Beginning
• Distributed Systems

• Blockchain as a Distributed System

• Distributed Consensus – A History


• Distributed System

• Consensus
The Three Pillars

Distributed Economic
Crypto Models
Systems
Our Core Problem
4 9
1

10
2 5
7

3
6
8 11
Our Core Problem
4 9
1

10
2 5
7

3
6
8 11
Our Core Problem
4 9
1

10
2 5
7

3
6
8 11
Our Core Problem
4 9
1
Other nodes in the network need to
agree on this new block 10
2 5
7

3
6
8 11
Our Core Problem
4 9
1 Other nodes in the network need to
agree on this new block
10
2 5
The Classical Distributed
Consensus Problem7
3
6
8 11
Distributed Consensus
Distributed Consensus
Distributed Consensus
Distributed Consensus

How can we make this decision


in a distributed way?
Distributed Consensus
Distributed Consensus
Distributed Consensus
Distributed Consensus

Take a majority voting and


decide
Distributed Consensus
Distributed Consensus
Distributed Consensus
Distributed Consensus

The Byzantine Behavior


Distributed Consensus – The Literature

• 1985: FLP Impossibility Theorem – Fischer, Lynch, Paterson


• Consensus is impossible in a fully asynchronous system
even with a single crash fault
Distributed Consensus – The Literature

• 1985: FLP Impossibility Theorem – Fischer, Lynch, Paterson


• Consensus is impossible in a fully asynchronous system
even with a single crash fault
• Cannot ensure "Safety" and "Liveness" together
Distributed Consensus – The Literature

• 1985: FLP Impossibility Theorem – Fischer, Lynch, Paterson


• Consensus is impossible in a fully asynchronous system
even with a single crash fault
• Cannot ensure "Safety" and "Liveness" together

Correct processes will The output will be produced


yield the correct output within a finite amount of
time (eventual termination)
Distributed Consensus – The Literature

• 1985: FLP Impossibility Theorem – Fischer, Lynch, Paterson


• Consensus is impossible in a fully asynchronous system
even with a single crash fault
• Cannot ensure "Safety" and "Liveness" together

• 1989: Lamport started talking about "Paxos"


• Supports safety but not the liveness
Distributed Consensus – The Literature
• 1985: FLP Impossibility Theorem – Fischer, Lynch, Paterson
• Consensus is impossible in a fully asynchronous system
even with a single crash fault
• Cannot ensure "Safety" and "Liveness" together

• 1989: Lamport started talking about "Paxos"


• Supports safety but not the liveness

• 1990's: Everyone were confused about the correctness


of Paxos
Distributed Consensus – The Literature
• 1998: Paxos got published in ACM Transactions on
Computer Systems

• 2001: FLP Impossibility paper wins Dijkstra Prize


• People starts talking about Distributed Systems

• 2009: Zookeeper released


• Service for managing distributed applications
Distributed Consensus – The Literature
• 2010's onward: Different types of consensus algorithms
released
• Multi-Paxos
• Raft
• Byzantine Fault Tolerance
• PBFT
• ...
Conclusion

• Blockchain needs consensus at its back

• There is a vast literature on distributed consensus

• Can we use them for blockchain?


Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering

Lecture 09: The Evolution of Cryptocurrencies


• Cryptocurrencies – Requirements

• The evolution of cryptocurrencies

• Design Goals for Cryptocurrency Development


• Cryptocurrency

• eCash, b-money, bit gold


Issues with Physical Currencies
Issues with Physical Currencies
Cryptocurrency
• An automated payment system having the
properties

• Inability of the third parties to determine


payee, time, or the amount of
payments made by individuals

• Ability to show the proof of payment

• Ability to stop the use of payment media


reported stolen
Digital Money: The Evolution of Cryptocurrencies

• 1983: eCash by David Chaum


• Money is stored in the computer – digitally signed by the
bank
• Use a concept "blind signature" to make the payment
anonymous – the content of a message is "blinded"
(disguised) before it is signed
Blind Signature
Blind Signature

• Wants to get your


credentials verified

• But do not want to reveal


the text of the letter to the
person who is verifying the
credentials
Blind Signature

• Wants to get your


credentials verified

• But do not want to reveal


the text of the letter to the
person who is verifying the
credentials
Blind Signature

• Wants to get your


credentials verified

• But do not want to reveal


the text of the letter to the
person who is verifying the
credentials
Blind Signature

• Wants to get your


credentials verified

• But do not want to reveal


the text of the letter to the
person who is verifying the
credentials
Blind Signature
• The official has verified
the credentials of the person
who has written it, but have
not seen the main message

• The official does not know


the actual message, only
knows that person X has sent
some message to person Y
eCash to DigiCash

• 1989: DigiCash Inc. founded by David Chaum


• ECash could not provide much additional benefit
• Not very popular among people – currency management
overhead is more than bank notes
• 1998: The company got bankrupted
Morphing the Definition

• An automated payment system having the properties

• Inability of the third parties to determine payee, time, or


the amount of payments made by individuals – Even the
banks will not be able to track it

• Ability to show the proof of payment

• Ability to stop the use of payment media


reported stolen
Morphing the Definition

• An automated payment system having the properties

• Inability of the
A complete distributed
third parties toplatform for
determine payee, time, or
the amount of payments made by individuals – Even the
cryptocurrency
banks exchange
will not be able to track it

• Ability to show the proof of payment

• Ability to stop the use of payment media


reported stolen
Moving Further ...

• 1998: Wei Dai publishes another anonymous, distributed


electronic cash system called b-money

• Nick Szabo describes "bit gold"


• Participants solve a cryptographic puzzle that depends on
the previous puzzle
• Some central control still needs to verify that the puzzle
has been solved correctly
Moving Further ...

• 1998: Wei Dai publishes another anonymous, distributed


electronic cash system called b-money

• Nick Szabo describes "bit gold"


• Participants solve a cryptographic puzzle that depends on
the previous puzzle
• Some central control still needs to verify that the puzzle
has been solved correctly
The Open Question

Can we verify the proof of the puzzle solving in a


distributed way?
The Open Question

Can we verify the proof of the puzzle solving in a


distributed way?

Distributed Consensus

Majority agrees that the puzzle has been solved correctly


Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering

Lecture 10: Open Consensus and Bitcoin


• Consensus over an Open Network

• Bitcoin – Open Blockchain Network

• The success of Bitcoin as a cryptocurrency


• Bitcoin

• Open Consensus

• PoW
The Open Question

Can we verify the proof of the puzzle solving in a


distributed way?

Distributed Consensus

Majority agrees that the puzzle has been solved correctly


The Open Question

Can we verify the proof of the puzzle solving in a


distributed way?
The network is open
Distributed Consensus: The Limitation
Distributed Consensus: The Limitation

Message Passing
Distributed Consensus: The Limitation

Message Passing
Needs the identity
of others
Distributed Consensus: The Limitation

Needs the identity of others


Works within a
closed system ...
Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


Consensus in an Open Network: Puzzle Solving

We need a leader
But nobody knows each other!
Consensus in an Open Network: Puzzle Solving

Let the Network elect a


leader !!
Consensus in an Open Network: Puzzle Solving

Network gives a Puzzle


Everyone tries to solve it
Consensus in an Open Network: Puzzle Solving

One who gives the solution


first becomes the leader
Consensus in an Open Network: Puzzle Solving

Whatever the leader says,


everyone agrees to that
Consensus in an Open Network: Puzzle Solving

Different leader at different


round, eventually everyone is
satisfied
Consensus in an Open Network: Puzzle Solving

• Need a good puzzle


• Difficult to solve
• Easy to verify
Consensus in an Open Network: Puzzle Solving

• Need a good puzzle


• Difficult to solve
• Easy to verify

• Y = H (X || N), Given X and Y, find out N


Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


• Hash Chain + Puzzle Solving as a Proof (from Bit Gold) +
Coin Mining in an open P2P setup
Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


• Hash Chain + Puzzle Solving as a Proof (from Bit Gold) +
Coin Mining in an open P2P setup
• Proof of Work (PoW) -- Nakamoto Consensus
Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


• Hash Chain + Puzzle Solving as a Proof (from Bit Gold) +
Coin Mining in an open P2P setup
• Proof of Work (PoW) -- Nakamoto Consensus

The Key to Success:


Give more emphasis on "Liveness"
rather than "Safety"
Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


• Hash Chain + Puzzle Solving as a Proof (from Bit Gold) +
Coin Mining in an open P2P setup
• Proof of Work (PoW) -- Nakamoto Consensus

Give more emphasis on "Liveness"


rather than "Safety"
Participants may agree on a transaction that is not
the final one in the chain
Consensus Finality over an Open Network

What if two persons solve


the puzzle simultaneously?
Consensus Finality over an Open Network

Pizza or Burger?
Can't say immediately
Bitcoin Proof of Work: An Open Consensus

• 2008: A whitepaper got floated on the Internet


• Hash Chain + Puzzle Solving as a Proof (from Bit Gold) +
Coin Mining in an open P2P setup
• Proof of Work (PoW) -- Nakamoto Consensus
• Have not coined the term "Blockchain" in the paper !!
From Cryptocurrency to Blockchain

• 2011: Litecoin got introduced

• 2015: Ethereum network went live

• Sometime around 2016: Term "Blockchain" got popular


Conclusion

• Classical distributed consensus can't be applied on the


blockchain for cryptocurrencies
• Open network, can't support message passing

• Use puzzle solving to reach open consensus – used on Bitcoin

• But, why should someone solve the puzzle?


• The puzzle is hard to solve, needs computing power
Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 11: Bitcoin Mining and Beyond


• Bitcoin Mining

• The Economic Model of Bitcoin

• Popularity of Cryptocurrencies
• Mining and Miners

• Mining reward

• Bitcoin Price

• Beyond Bitcoins
Bitcoin Mining: The Key to Consensus

• There are special nodes, called the Miners


• Miners propose new blocks – solve the puzzle (find the nonce
corresponding to a target block hash), and add the solution as a
proof of solving the challenge to be the leader
• Solving the challenge needs some work to be done –
Proof of Work (PoW)
Bitcoin Mining: The Key to Consensus

• There are special nodes, called the Miners


• Miners propose new blocks – solve the puzzle (find the nonce
corresponding to a target block hash), and add the solution as a
proof of solving the challenge to be the leader
• Solving the challenge needs some work to be done –
Proof of Work (PoW)

Why someone would want to be the leader?


Bitcoin Mining: The Key to Consensus

• There are special nodes, called the Miners


• Miners propose new blocks – solve the puzzle (find the nonce
corresponding to a target block hash), and add the solution as a
proof of solving the challenge to be the leader
• Solving the challenge needs some work to be done –
Proof of Work (PoW)

Why someone would want to be the leader?

Earn money (bitcoin) by solving


the puzzle!
Mining a Block: The Reward
Mining a Block: The Reward
The Economics behind Reward

Encourage the
community to
participate in the
mining through
incentivization
The Economics behind Reward

Encourage the
Produces new Bitcoins in
community to
the System
participate in the
(Similar to a Minting new
mining through
Coins)
incentivization
The Economics behind Reward

The Bitcoin network works like a Reserve Bank


to regulate the flow of Money (Bitcoin) in the
market, but without explicit governance
Blockchain 1.0: Distributed Ledger

• Use of the Distributed Ledger Technology (DLT) to design the


"Money of the Internet" -- Bitcoin and other cryptocurrencies
Blockchain 1.0: Distributed Ledger

• Use of the Distributed Ledger Technology (DLT) to design the


"Money of the Internet" -- Bitcoin and other cryptocurrencies
• 3rd January 2009: Nakamoto mined the first block of the
Bitcoin network (called the genesis block)
• 2013: Coinbase reported selling US$1 Million worth of
Bitcoin
• Many other cryptocurrencies have been evolved after that
• Ethereum
• Litecoin
• ...
The Price of Bitcoins

• Bitcoin value increased drastically over time


• May 2010: < $0.01
• April 2014: $340 - $530
• December 2017: ~$13800

• Today (24 Sept, 2021 10:30 am): $44,285.50


Bitcoin Millionaires
Popularity of Cryptocurrencies
Popularity of Cryptocurrencies
Popularity of Cryptocurrencies

Growing interests in
developing decentralized
applications (Dapps)
What are these Dapps?

• DLTs can contain information beyond financial transactions


• What about submitting an executable code as a
transaction?

• Not a new idea, people already knows about Remote Code


Execution or Code Injection
What are these Dapps?

• DLTs can contain information beyond financial transactions


• What about submitting an executable code as a
transaction?

• Transaction gets executed == Your code is getting executed


• And you have consensus on the code execution !
What are these Dapps?

• DLTs can contain information beyond financial transactions


• What about submitting an executable code as a
transaction?
Smart Contacts
• Transaction gets executed == Your code is getting executed
• And you have
Will see them in the
consensus nextcode
on the lecture!
execution !
Blockchain and its applications
Prof. Sandip Chakraborty
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 12: Smart Contracts and the Permissioned


Models of Blockchain
• Smart Contracts and automated code execution

• Permissioned Blockchain
• Smart Contracts

• Blockchain 2.0 and 3.0

• Permissioned Models

• Enterprise Blockchains
DLTs for Code Execution

• DLTs can contain information beyond financial transactions


• What about submitting an executable code as a
transaction?

• Transaction gets executed == Your code is getting executed


• And you have consensus on the code execution !
Smart Contracts

• DLTs can contain information beyond financial transactions


• What about submitting an executable code as a
transaction?
Smart Contacts
• Transaction gets executed == Your code is getting executed
Automatically Execute Code over a
• And you have consensus onPlatform
Decentralized the code execution !
Traditional Way of Maintaining Digital Contacts
Traditional Way of Maintaining Digital Contacts
Traditional Way of Maintaining Digital Contacts

Input
Traditional Way of Maintaining Digital Contacts

Response
Traditional Way of Maintaining Digital Contacts

Input
Traditional Way of Maintaining Digital Contacts

Response
Traditional Way of Maintaining Digital Contacts

How will you check that the


inputs are valid?
Traditional Way of Maintaining Digital Contacts

What if I deny about an


input later on?
Decentralized Code Execution
int pay (float *sndAcc, float *rcvAcc, float amount) {
if (*sndAcc < amount) return -1;
else {
*sndAcc -= amount;
*rcvAcc += amount;
return 1;
}
}

int deliverGoods (int count, int pricePerC) {


int success = pay (sender, receiver, count*pricePerC);
if(success == 1) {
sceduleLogistics();
return 1;
}
Return 0;
}
Decentralized Code Execution
int pay (float *sndAcc, float *rcvAcc, float amount) {
if (*sndAcc < amount) return -1;
else {
*sndAcc -= amount; sndAcc = i
*rcvAcc += amount;
return 1;
rcvAcc = j
} count = 0
}

int deliverGoods (int count, int pricePerC) {


int success = pay (sender, receiver, count*pricePerC);
if(success == 1) {
sceduleLogistics();
return 1;
}
Return 0;
}
Decentralized Code Execution
int pay (float *sndAcc, float *rcvAcc, float amount) {
if (*sndAcc < amount) return -1;
else {
*sndAcc -= amount; sndAcc = i sndAcc = i
*rcvAcc += amount;
return 1;
rcvAcc = j rcvAcc = j
} count = 0 count = 0
}
deliverGoods (10, 4)
int deliverGoods (int count, int pricePerC) {
int success = pay (sender, receiver, count*pricePerC);
if(success == 1) {
sceduleLogistics();
return 1;
}
Return 0;
}
Decentralized Code Execution
int pay (float *sndAcc, float *rcvAcc, float amount) { deliverGoods (10, 4)
if (*sndAcc < amount) return -1; pay(sndAcc, rcvAcc, 40) > 1
else {
*sndAcc -= amount; sndAcc = i
*rcvAcc += amount;
sndAcc = i - 40
return 1;
rcvAcc = j rcvAcc = j + 40
} count = 0 count = 40
}

int deliverGoods (int count, int pricePerC) {


int success = pay (sender, receiver, count*pricePerC);
if(success == 1) {
sceduleLogistics();
return 1;
}
Return 0;
}
Decentralized Code Execution
int pay (float *sndAcc, float *rcvAcc, float amount) { deliverGoods (10, 4)
if (*sndAcc < amount) return -1; pay(sndAcc, rcvAcc, 40) > 1
else {
*sndAcc -= amount; sndAcc = i
*rcvAcc += amount;
sndAcc = i - 40
return 1;
rcvAcc = j rcvAcc = j + 40
} count = 0 count = 40
}

int deliverGoods (int count, int pricePerC) {


int success = pay (sender, receiver, count*pricePerC);
if(success == 1) {
sceduleLogistics();
return 1; Put the states of execution
}
Return 0; in a blockchain
}
Smart Contract Execution
Smart Contract Execution
Submit the anonymized
(through public key
encryption) contract to a
blockchain network
Smart Contract Execution

Everyone in the network


can see and validate the
execution steps
Cryptokitties – A Popular Game on Ethereum
Cryptokitties – A Popular Game on Ethereum
Permissioned Model of Blockchain

• PoW (Nakamoto Consensus) works good in an open network


• But, transaction latency is very high
• ~10 minutes in Bitcoin block commitment
• Few seconds to few minutes for Ethereum (depending on
the cost that you pay)
Permissioned Model of Blockchain

• PoW (Nakamoto Consensus) works good in an open network


• But, transaction latency is very high
• ~10 minutes in Bitcoin block commitment
• Few seconds to few minutes for Ethereum (depending on
the cost that you pay)

• Can we think of any other Blockchain applications beyond


cryptocurrency?
• The high latency makes them unsuitable for most of
the real-time applications
Permissioned Model of Blockchain

• Many decentralized applications do not demand an open


environment
• The food supply chain
• Know Your Customer (KYC)
• Trade financing
• ...
Blockchain 3.0

• "Trustless Decentralization" over a closed network


• Automatically transact assets among multiple
organizations who do not trust each other
• Run smart contracts within a consortium of various
organizations – the individual organizations know each
other but do not trust each other
Blockchain 3.0

• Advantages:
• Go back to the classical distributed consensus protocols –
low latency for commitment and high transaction
throughput
• Use "Witness Cosigning" instead of "Proof Mining" for new
block generation
• Classical Distributed Consensus + Digital Signature
Permissioned Blockchain

• The participants are pre-authenticated and pre-authorized


• But they can still behave maliciously

• Run blockchain (and smart contracts) on top of this


closed network
• Ensure trusted computing among the participants
Conclusion

• Smart Contracts revolutionizes the blockchain/DLT applications


• Supports automated code execution over a decentralized
platform

• Permissioned blockchains have emerged for enterprise


applications
Conclusion

• Smart Contracts revolutionizes the blockchain/DLT applications


• Supports automated code execution over a decentralized
platform

• Permissioned blockchains have emerged for enterprise


applications

• Now let us explore the detailed internal structure of


a blockchain …. our next lecture
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 08: Blockchain Elements - I


• What is a Blockchain
• Blocks in a Blockchain
• Block Header
• Block Structure
• Block Header
• Mining a Block
• Block Generation Puzzle
What is Blockchain?

• A Platform for executing transactional services

• Spanned over multiple organizations or individuals who


may not (need not) trust each other

• An append-only shared ledger of digitally signed and


encrypted transactions replicated across a network of
peer nodes
The Block in a Blockchain – Securing Data Cryptographically
• Digitally signed and
encrypted
transactions
“verified” by peers

• Cryptographic
security – Ensures
that participants can
only view information
on the ledger that
they are authorized to
see Image source: http://dataconomy.com/
Structure of a Block
• A block is a container data structure that contains a series of
transactions
• In Bitcoin: A block may contain more than 500 transactions on
average, the average size of a block is around 1 MB (an upper
bound proposed by Satoshi Nakamoto in 2010)
• May grow up to 8 MB or sometime higher (several
conflicting views on this!!)
• Larger blocks can help in processing large number of
transactions in one go.
• But longer time for verification and propagation
Structure of a Block (Reference: Bitcoin)

• Two components:
• Block Header
• List of Transactions

Block Source: https://btc.com/btc/blocks OR https://blockchain.com/explorer


Block Header (Reference: Bitcoin)
H0
• Metadata about a block – (1)
Previous block hash, (2) Mining
H1 = Hash(H0)
statistics used to construct the
block, (3) Merkle tree root
H2 = Hash(H1)
• Previous block hash: Every block
inherits from the previous block –
we use previous block’s hash to H3 = Hash(H2)
create the new block’s hash – make
the blockchain tamper proof H4 = Hash(H3)
Block Generation Puzzle

Block Header Block Header Block Header

Previous Previous Previous


Hash
Nonce Hash
Nonce Hash
Nonce

Merkle Block Merkle Block Merkle Block


Root Hash Root Hash Root Hash

Find out the nonce which generates the desired hash (certain
number of zero bits at the prefix) -
0000000000000000004a2b84f93a285b7a7………
Block Header (Reference: Bitcoin)
• Mining – the mechanism to generate the hash
• The mechanism needs to be complicated enough, to
make the blockchain tamper proof
• Bitcoin Mining: Hk = Hash(Hk-1 || T || Nonce ||
Something more)
• Find the nonce such that Hk has certain predefined
complexity (number of zeros at the prefix)
• The header contains mining statistics – timestamp, nonce and
difficulty
Block Header (Reference: Bitcoin)
• Understanding Difficulty and Bits
• “Bits” written in Hex, e.g., 0x170e2632
• First byte is index and next three bytes form coefficient
• Target = Coefficient*2^(8*(index-3))
• Difficulty is the largest possible target
(0x00000000FFFF00000000000000000000000000000000000000000
00000000000) divided by the current target , e.g.,
• (0x0000000000000000000E2631FFFFFFFFFFFFFFFFFFFFFBB0C4B0219
13E000000)
• Remember: “Cost of Mining” – Pretty High (Computing Power
and Energy)
[Number conversion utility: https://www.rapidtables.com/convert/number/hex-to-
decimal.html]
Hashes in a Block Header (Reference: Bitcoin)

• Block identifier – the hash of the current block header


(Hash algorithm: Double SHA256)
• Merkle Root
• Previous block hash is used to compute the current block
hash
• Timestamp, Previous hash, Merkle root, Difficulty Bits,
Nonce and Version used to compute current hash

Demonstration
https://dlt-repo.net/bitcoin-block-hash-verification-tool/
Block Source: https://btc.com/btc/blocks
• We have described the structure of a block in blockchain
• Main components of a block header
• How to solve block generation puzzle
• What is meant by mining of a block
• Cryptography and Network Security – Principles and Practice
by William Stallings, Pearson (2017)
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Any other standard textbook on blockchain/bitcoin
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 14: Blockchain Elements - II


• Block Generation Cost
• Transactions in a Block
• Bitcoin Scripts
• Hash Generation Rate
• Transaction Input and Output
• Bitcoin Script
Block Generation Cost
• Energy efficiency ~0.098 J/GH = ~100 J/TH
• ASIC Hardware for bitcoin can perform about 750 TH/s
• Hash rate approx. 120M TH/s!! Many actually go waste 
• Network consumes about 80 TW-hours of electricity annually.
Figures vary between sources and are some form of estimates
• Average household in Germany of four people consumes
approx. 4,000 KW-hours of electricity per year.
• Can power about 20,000 households
• Concept of Pooling is used (https://btc.com/ )
• What ensures tamperproof operation in terms of honest
nodes??
Blockchain Replicas
• Every peer in a Blockchain network maintains a local copy of
the Blockchain.
• Size is just about 351 GB 
• As a new user joins the network, she can get the whole copy

• Requirements
• All the replicas need to be updated with the last mined
block
• All the replicas need to be consistent – the copies of the
Blockchain at different peers need to be exactly similar
Transactions in a Block

• Transactions are organized as a Merkle Tree. The Merkle


Root is used to construct the block hash

• If you change a transaction, you need to change all the


subsequent block hashes

• The difficulty of the mining algorithm determines the


toughness of tampering with a block in a blockchain
Merkle Tree – A Quick Recap
Root Hash
Merkle Root
Hroot=Hash(H0+H1)

L1 Hash L1 Hash
H0= Hash(H00+H01) H1=Hash(H10+H11)

L2 Hash L2 Hash L2 Hash L2 Hash


H00=Hash(T1) H01=Hash(T2) H10=Hash(T3) H11=Hash(T4)

T1 T2 T3 T4
Transactions in a Block

Block Source: https://btc.com/btc/blocks


Bitcoin Transactions and Input and Output

TX TX
TX
1 3
0
input() input()
input()
100 BTC
output1() output1()
output1()

output2()
output2()
TX TX
2 4
input() input()

output1() output1()
Bitcoin Scripts – A Simple Example

T(A->B)

How Bob will verify that the transaction


is actually originated from Alice?
Bitcoin Scripts – A Simple Example

T(A->B)

KAPUB, SA(T(A->B))

Send the public key of Alice along with


the signature -> Bob can verify this
Bitcoin Scripts – A Simple Example

T(A->B)

KAPUB, SA(T(A->B))

Bitcoin indeed transfers scripts instead of


the signature and the public key
Bitcoin Scripts – A Simple Example

T(A->B)

scriptPubKey, scriptSig

Bitcoin indeed transfers scripts instead of


the signature and the public key
Bitcoin Scripts – A Simple Example

T(A->B)

scriptPubKey, scriptSig

Bob can spend the bitcoins only if both


the scripts return TRUE after execution
Bitcoin Scripts

• Simple, compact, stack-based and processed left to right


• FORTH like language

• Not Turing Complete (no loops)


• Halting problem is not there
Bitcoin Scripts

• With every transaction Bob must provide


• A public key that, when hashed, yields the address of
Bob embedded in the script
• A signature to provide ownership of the private key
corresponding to the public key of Bob
• Discussed the cost of block generation
• How transactions are included in blocks
• Use of scripts for making and claiming payments
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Any other standard textbook on blockchain/bitcoin
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 15: Blockchain Elements - III


• Understanding Bitcoin Scripts
• Some Interesting Bitcoin Scripts
• Bitcoing Script
• scriptPubKey
• scriptSig
• Stack
Bitcoin Scripts

Transaction 18E14A7B6A30…
scriptSig:
Input D61967F63C7DD…

OP_DUP
OP_HASH160
Transaction scriptPubKey: 16UwLL9Risc3QfPqBUvKof…
OP_EQUALVERIFY
Output OP_CHECKSIG

See for detailed steps:


https://developer.bitcoin.org/devguide/transactions.html
Bitcoin Scripts

scriptPubKey: OP_DUP
OP_HASH160 <pubKeyHash>
OP_EQUALVERIFY
OP_CHECKSIG
The stack is initially empty.
scriptSig: <sig> Both the scripts are
combined – input followed by output
<pubKey>
<sig> <pubKey> OP_DUP
OP_HASH160 <pubKeyHash>
OP_EQUALVERIFY OP_CHECKSIG
A real example
For more examples to explore: https://btc.com/btc/blocks
from Bitcoin
Bitcoin Scripts
<pubK
<sig> <pubKey> OP_DUP <si
ey>
OP_HASH160 <pubKeyHash> g>
OP_EQUALVERIFY OP_CHECKSIG
The top two items are pushed to Stack one
after another

OP_DUP OP_HASH160
<pubKeyHash> OP_EQUALVERIFY
OP_CHECKSIG
Bitcoin Scripts
<pubK
OP_DUP OP_HASH160 ey>
<pubK
<pubKeyHash> OP_EQUALVERIFY ey>
<si
OP_CHECKSIG g>
Top stack item is duplicated

OP_HASH160 <pubKeyHash>
OP_EQUALVERIFY OP_CHECKSIG
Bitcoin Scripts
<pubH
ash>
<pubK
OP_HASH160 <pubKeyHash>
ey>
<s
OP_EQUALVERIFY OP_CHECKSIG
ig
Top stack item is hashed (RIPEMD-160
hashing)
>

<pubKeyHash> OP_EQUALVERIFY
OP_CHECKSIG
Bitcoin Scripts
<pubKey
<pubHa
Hash>
<pubKeyHash> <pubKe
sh>
<si
y>
OP_EQUALVERIFY OP_CHECKSIG g>
The constant is pushed in the stack

OP_EQUALVERIFY OP_CHECKSIG
Bitcoin Scripts
<pubKey
<pubHa
Hash>
<pubKe
sh>
OP_EQUALVERIFY OP_CHECKSIG <si
y>
g>
Equality is checked between the top two items
in the stack

OP_CHECKSIG
Bitcoin Scripts
<pubK
OP_CHECKSIG <si
ey>
g>
Signature is checked based on the top two
stack item

TRUE
Bitcoin Script Instructions

• Total 256 opcodes (15 disabled, 75 reserved)


• Arithmetic operations
• if-then conditions
• Logical operators
• Data handling (like OP_DUP)
• Cryptographic operations
• Hash functions
• Signature verification
• Multi-signature verification
Interesting Bitcoin Scripts

• Provably un-spendable or prunable outputs


scriptPubKey: OP_RETURN
{zero or more ops}
• Anyone-can-spend outputs
scriptPubKey: {empty}
scriptSig: OP_TRUE
Source: https://en.bitcoin.it/wiki/Script
Interesting Bitcoin Scripts

• Freezing funds until a time in the future


scriptPubKey: <expiry_time>
OP_CHECKLOCKTIMEVERIFY OP_DROP
OP_DUP OP_HASH160 <pubKeyHash>
OP_EQUALVERIFY OP_CHECKSIG
scriptSig: <sig> <pubKey>

Source: https://en.bitcoin.it/wiki/Script
• Use of scripts in generating input and output of bitcoin
transactions
• Public key cryptography and digital signature for
cryptographically protecting transactions
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Any other standard textbook on blockchain/bitcoin
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 16: Blockchain Elements - IV


• Joining a Bitcoin Network
• Transaction Flooding
• Block Mining
• Block Propagation
• Forking and Propagation of Longest Chain
• Bitcoin Node
• Transaction Flooding
• Block Reward
• Block Propagation
• Fork in Blockchain
Bitcoin P2P Network

• An ad-hoc network with random topology, Bitcoin protocol


runs over TCP

• All nodes (users) in the bitcoin network are treated equally

• New nodes can join any time, non-responding nodes are


removed after 3 hours
Joining in a Bitcoin P2P Network
Joining in a Bitcoin P2P Network
Joining in a Bitcoin P2P Network
Seed Node

Give me the
address
Joining in a Bitcoin P2P Network
Seed Node

<address list>
Joining in a Bitcoin P2P Network

Seed Node
Joining in a Bitcoin P2P Network

Get most recent


blockchain
Joining in a Bitcoin P2P Network

Start transaction
Transactions in a Bitcoin Network

• Alice joins the Bitcoin network by opening her


applet

• Alice makes a transaction to Bob: A->B: BTC 10

• Alice includes the scripts with the transactions

• Alice broadcasts this transaction in the Bitcoin


network
Transaction Flooding in a Bitcoin Network
Transaction Flooding in a Bitcoin Network
Transaction Flooding in a Bitcoin Network

Validate the
Transaction
Transaction Flooding in a Bitcoin Network

Flood the
Transaction
Transaction Flooding in a Bitcoin Network
I have already
A->B:BTC10 seen the
transaction
Which Transactions Should You Relay?
• The transaction is valid with current blockchain
– No conflict
– No double spending
• The script matches with a pre-given set of whitelist scripts
– Avoid unusual scripts, avoid infinite loops
• Does not conflict with other transactions that I have
relayed after getting the blockchain updated – avoid
double spending
Transaction Flooding in a Bitcoin Network
A->B:BTC10
C->D:BTC20 A->B:BTC10
C->D:BTC20
A->B:BTC10

A->B:BTC10 A->B:BTC10

C->D:BTC20
C->D:BTC20

C->D:BTC20
A->B:BTC10

A->B:BTC10
Different nodes Accept the first
may have different transactions that
transaction pools you have heard
Transaction Flooding in a Bitcoin Network

A->B:BTC10
C->D:BTC20 A->B:BTC10
C->D:BTC20
A->B:BTC10

A->B:BTC10 A->B:BTC10

C->D:BTC20
C->D:BTC20

C->D:BTC20
A->B:BTC10
Accept the first set of
A->B:BTC10
transactions that you
have heard
Mining in a Bitcoin Network

Miner collects all the


transactions flooded and
starts mining
Block Generation

The miner who solves the puzzle


first, generates a new block
Block Flooding

Flood the blockchain with the


new block included
Block Propagation
Multiple miners can
mine a new block
simultaneously or
in a near identical
time

“Forks” may get created


Block Propagation – Accept the Longest Chain
Block 3 Block 6

Block 1 Block 2 Block 5 Block 7 Block 8 Block 10

Block 4 Block 9 Block 11

• “Accidental” forks occur rarely. Even if they occur, eventually only one
becomes part of the longest chain
• There are “intentional” forks of two type: hard forks and soft forks to come
up with new versions like Bitcoin Cash, etc., or to upgrade software versions
Which Block to Relay

• Block contains the correct hash based on the existing


blockchain

• All the transactions inside the block are valid


– Check the scripts
– Validate with the existing blockchain

• The block is included in the current longest chain


– Do not relay the forks
• Shown how a new node can join the bitcoin network
• Creation and propagation of transactions
• Accumulating transactions and mining new blocks
• Propagation of new bitcoin blocks
• Discussed how forking is handled in a blockchain
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Blockchain: Hype or Innovation by Tatiana Gayvoronskaya
and Christoph Meinel, Springer (2021)
• Any other standard textbook on blockchain/bitcoin
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 17: Blockchain Elements - V


• Start of the Bitcoin Network and Creation of Coins
• Variation of Block Reward with Time
• Handling of Double Spending Problem
• Payment using Bitcoin and Anonymity
• Bitcoin Exchange
• Block Reward
• Double Spending
• Anonymity
• Bitcoin Exchange
Bitcoin Basics – Creation of Coins

• Controlled Supply: Must be limited for the currency to have


value – any maliciously generated currency needs to be
rejected by the network
• Bitcoins are generated during the mining – each time a user
discovers a new block
• The rate of block creation is adjusted every 2016 blocks to
aim for a constant two week adjustment period
• The last bitcoin will be mined in 2140 (estimated and unless
changed)
Bitcoin Basics – Creation of Coins

• Number of bitcoins generated per block is set to decrease


geometrically, with a 50% reduction for every 210,000
blocks, or approximately 4 years
• This reduces with time the amount of bitcoins generated
per block
– Theoretical limit for total bitcoins: Slightly less than 21
million
– Miners will get less reward as time progresses
– How to pay the mining fee – increase the transaction fee
Projected Number of Bitcoins

Information Source: https://en.bitcoin.it/wiki/


Bitcoin Basics – Sending Payments
• Alice wants to send bitcoin to Bob
– Bob sends his address to Alice
– Alice adds Bob’s address and the amount of
bitcoins to transfer in a “transaction” message
– Alice signs the transaction with her private key,
and announces her public key for signature
verification
– Alice broadcasts the transaction on the Bitcoin
network for all to see

Information Source: https://en.bitcoin.it/wiki/


Double Spending
• Same bitcoin is used for more
than one transaction
• Double spending Cash??
• In a centralized system
for digital currency, the
bank prevents double
spending
• How can we prevent
double spending in a
decentralized network?
A:50
Handle Double Spending using Blockchain

• When multiple valid continuation to this chain appear,


only the longest such branch is accepted and it is then
extended further (longest chain)
• Once a transaction is committed in the blockchain,
everyone in the network can validate all the transactions
by using Alice’s public address
• The validation prevents double spending in bitcoin
Bitcoin Anonymity

• Bitcoin is permission-less, you do not need to setup


any “account”, or required any e-mail address, user
name or password to login to the wallet
• The public and the private keys do not need to be
registered, the wallet can generate them for the users
• The bitcoin address is used for transaction, not the
user name or identity
Bitcoin Anonymity

• A bitcoin address mathematically corresponds to a public


key based on ECDSA – the digital signature algorithm used
in bitcoin
• A sample bitcoin address:
1PHYrmdJ22MKbJevpb3MBNpVckjZHt89hz
• Each person can have many such addresses, each with its
own balance
– Difficult to know which person owns what amount
To Sum it All Up!!
• Bitcoins do not really “exist” as any tangible or electronic
object.
• There is no bit”coin” as you see in its logo
• Owning a bitcoin simply means you have access to a key pair
that includes
– A public key to which somebody else had sent some bitcoin
– A matching private key that gives you the authority to send
the previously received bitcoin to another address
• If you lose your private key, you lose the corresponding
bitcoin(s)
Physical Payment using Bitcoin
• All that is needed is a (set of) private key(s) – Public key
can be generated from the private key.
• Safely store the private key – in your desktop, on the
web, mobile phone, special hardware attachment,
printed on a piece of paper as QR
• For online payment, you can use the wallet and an
appropriate mode of applying the private key
• For off line payments like in store payments or paying to
your friend, you can use your mobile phone to present
the private key or use the hardcopy!! As simple as using
PayTm, Google Pay and so on.
Bitcoin Exchange
• Trading bitcoin as commodity
• Centralized exchanges – (In India: WazirX, CoinDCX, Zebpay,
CoinSwitch Kuber, etc.)
– Identity verification using KYC documents
– Maintain your balance in Bitcoin and another currency like INR.
– You set the buying and selling prices and quantities
– If necessary, you can take the money out in a referred currency
– Some exchanges provide the payout option in anonymous
prepaid cards
• There can also be decentralized exchanges with appropriate
procedures for handling similar requirements
• Generation (Mining) of new coins
• Variation of block reward with time
• Handling double spending
• Anonymity in bitcoin
• Paying using bitcoin and role of exchange
• Blockchain Basics: A Non-Technical Introduction in 25 Steps
by Daniel Drescher, Apress (2017)
• Blockchain: Hype or Innovation by Tatiana Gayvoronskaya
and Christoph Meinel, Springer (2021)
• Any other standard textbook on blockchain/bitcoin
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 18: Permissionless Model and Open


Consensus
• Permissionless Model

• Consensus Requirements for Open Networks

• FLP Impossibility and Open Consensus


• Permissionless Models

• Synchronous and Asynchronous

• Failures in distributed system

• Safety vs Liveness
Permissionless Model

• Open network
• Anyone can join in the network and initiate transactions
• Participants are free to leave the network, and can join
later again
Permissionless Model

• Open network
• Anyone can join in the network and initiate transactions
• Participants are free to leave the network, and can join
later again

• Assumption: More than 50% of the participants are honest


• A society cannot run if majority of its participants are
dishonest !!
Permissionless Blockchain
Consensus Challenges

• Participants do not know others


• Cannot use message passing !!

• Anyone can propose a new block


• Who is going to add the next block in the blockchain?

• The network is asynchronous


• We do not have any global clock
• A node may see the blocks in different orders
Consensus Challenges
B1 B2 B3
Consensus Challenges
B1 B2 B3

B3
Consensus Challenges
B1 B2 B3

B3 B2
Consensus Challenges

• Any types of monopoly needs to be prevented


• A single user or a group of users should not gain the
control – we don't trust anyone
Synchronous vs Asynchronous

• Synchronous vs Asynchronous Networks


• Synchronous: I am sure that I'll get the message in real
time (theoretically no delay or minimum delay)
• Asynchronous: I am not sure whether and when the
message will arrive
Failure in a Network

• Crash Fault: A node stops responding

• Link Fault (or Network Fault): A link fails to


deliver the message

• Byzantine Fault: A node starts behaving


maliciously
Failure in a Network

• Crash Fault: A node stops responding

• Link Fault (or Network Fault): A link fails to


deliver the message

• Byzantine Fault: A node starts behaving


maliciously
B1 B2
Failure in a Network

• Crash Fault: A node stops responding


B1 B4

• Link Fault (or Network Fault): A link fails to


deliver the message

• Byzantine Fault: A node starts behaving


maliciously
Remember FLP Impossibility?

• The Impossibility Theorem: Consensus is not possible in


a perfect asynchronous network even with a single
crash failure
• Cannot ensure safety and liveness simultaneously
The Safety vs Liveness Dilemma

The Nakamoto Consensus (Proof of Work)

Liveness is more important than Safety

Immediate focus is on liveness with a minimum safety


guarantee, full safety will be ensured eventually
The Consensus Problem

TX11 TX10
TX19 TX16
TX13
TX42 TX55
TX45 TX40
TX67
TX56 TX32

Miner 1 Miner 2 Miner 3


The Consensus Problem
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Bitcoin Unconfirmed TX : https://www.blockchain.com/btc/unconfirmed-transactions

Unconfirmed TX Unconfirmed TX Unconfirmed TX

Miner 1 Miner 2 Miner 3


The Consensus Problem
TX10 TX16
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16

Miner 1 Miner 2 Miner 3


The Consensus Problem
TX10 TX17
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17

Miner 1 Miner 2 Miner 3


The Consensus Problem
TX10 TX22
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX22

Miner 1 Miner 2 Miner 3


The Consensus Problem
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
The Consensus Problem
Which one would
TX10 be the next block?
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Conclusion
• Message passing is not possible over an open network

• FLP Impossibility: Safety vs Liveness

• Priority over Liveness


• More suitable for Blockchain? Include the correct block –
whether it is final, think later

• Different miners see different blocks


• Which one to add?
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 19: Nakamoto Consensus (Proof of Work)


• Nakamoto Consensus

• Block Mining
• PoW

• Block Mining

• Safety and Liveness


The Consensus Problem
Which one would
TX10 be the next block?
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Safety-1: The next block should be "correct" in practice


• Transactions are verified, block contains correct Hash and Nonce
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX16
This can be ensured – the
TX13
TX45
TX42 TX55 block mined by a miner is
TX67 TX40
TX56
TX32
verified by all

Safety-1: The next block should be "correct" in practice


• Transactions are verified, block contains correct Hash and Nonce
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Safety-2: All the miners should agree on a single block


• The next block of the blockchain should be selected unanimously
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness Miners do not know
TX10
each other – how can
TX11
TX13
TX19 TX16 they agree on the same
TX45
TX42 TX55
block?
TX67 TX40
TX56
TX32

Safety-2: All the miners should agree on a single block


• The next block of the blockchain should be selected unanimously
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX11
TX10 PoW compromises here
TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

Safety-2: All the miners should agree on a single block


• The next block of the blockchain should be selected unanimously
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32
Liveness: Add a block as long as it is correct
(contains valid transactions from the unconfirmed TX list)
and move further
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
Two (or more) different
TX11 TX19
TX10 miners may add two (or
TX16
TX13
TX45
TX42 TX55 more) different blocks
TX67 TX40
TX56
TX32
Liveness: Add a block as long as it is correct
(contains valid transactions from the unconfirmed TX list)
and move further
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness Two (or more) different miners
may add two (or more) different
TX10
TX11 TX19 blocks
TX16
TX13
TX45
TX42 TX55 Will resolve this later!
TX67 TX40
TX56
TX32
Liveness: Add a block as long as it is correct
(contains valid transactions from the unconfirmed TX list)
and move further
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX16
TX13
TX45
TX42 TX55
TX67 TX40
TX56
TX32

TX22
TX16 TX17 TX17
TX17 TX22 TX16
TX37 TX87 TX31
Unconfirmed TX TX87 Unconfirmed TX TX37 Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
• No fixed ordering of transactions
Safety vs Liveness • No fixed number of transactions
TX10 per block
TX11
TX13
TX19 TX16 • Limit on the Block size
TX45
TX42 TX55
TX67 TX40
TX56
TX32

TX22
TX16 TX17 TX17
TX17 TX22 TX16
TX37 TX87 TX31
Unconfirmed TX TX87 Unconfirmed TX TX37 Unconfirmed TX
TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness • Generate the proof (nonce)
TX11 TX19
TX10
TX16
• Generation: Complex
TX13
TX45
TX42 TX55
TX40
• Verification: Easy
TX56 TX67
TX32

TX22
TX16 TX17 TX17
TX17 TX22 TX16
TX37 TX87 TX31
Unconfirmed TX TX87 Unconfirmed TX TX37 Unconfirmed TX
TX16 TX16 ?
? TX17 ? TX17
TX17 TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness • Expectation: One of
TX11 TX19
TX10
TX16
the miners will be able
TX13
TX45
TX42 TX55
TX40
to generate the proof
TX56 TX67
TX32

TX22
TX16 TX17 TX17
TX17 TX22 TX16
TX37 TX87 TX31
Unconfirmed TX TX87 Unconfirmed TX TX37 Unconfirmed TX
TX16 TX16 ?
? TX17 ? TX17
TX17 TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness • Expectation: One of
TX11 TX19
TX10
TX16
the miners will be able
TX13
TX45
TX42 TX55
TX40
to generate the proof
TX56 TX67
TX32

TX22
TX16 TX17 TX17
TX17 TX22 TX16
TX37 TX87 TX31
Unconfirmed TX TX87 Unconfirmed TX TX37 Unconfirmed TX
TX16 TX16 NM3
? TX17 ? TX17
TX17 TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31
TX32

• Sign the block and broadcast TX22


• Gossip over the P2P network TX17
TX16
TX31
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX17
TX16 NM3
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
Safety vs Liveness
TX10
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31
TX32

• Remove the committed transactions from unconfirmed TX list

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX87 TX87
TX49 TX37
TX37 TX88

Miner 1 Miner 2 Miner 3


Safety vs Liveness Unconfirmed TX

TX10
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16 Miner 4
TX67 TX40
TX56 TX31
TX32

• Start the next round ...

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX87 TX87
TX49 TX37
TX37 TX88

Miner 1 Miner 2 Miner 3


Conclusion

• Nakamoto Consensus (PoW)


• Any correct blocks can be added
• No guarantee that every miner will try to mine the same
block
• No guarantee that you can see your transaction in the latest
block

• What if two miners mine block simultaneously?


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 20: Limitations of PoW: Forking and Security


• PoW Forks

• Attacks on PoW

• The Monopoly Problem


• Forks

• Security

• 51% attack
PoW: Mining a New Block
TX10
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31
TX32

• The miner who is able to solve the puzzle becomes the


TX22
leader TX17
• The block from the leader is appended in the blockchain TX16
TX31
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16 TX17
TX16 NM3
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
PoW: Mining a New Block What if two miners
TX10 solve the puzzle
TX11 TX19 TX22
TX16 simultaneously?
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31
TX32

TX16 TX16 TX22


TX17 TX17 TX17
TX87 TX87 TX16
TX49 TX49 TX31
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX16
NM1 ? TX16 NM3
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
PoW: Mining a New Block Fork TX22
TX17
TX16
TX10 TX31
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
TX49

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
PoW: Mining a New Block Fork TX22
TX17
TX16
TX10 TX31
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Consensus finality is not ensured – Safety not satisfied immediately TX49
• The network remains partitioned for some amount of time

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX16 TX16
TX17
TX17 TX17
TX22
TX87 TX22
TX87
TX49 TX31
TX37
TX37 Miner 1 TX88 Miner 2 Miner 3
PoW: Mining a New Block Fork TX22
TX17
TX16
TX10 TX31
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Momentary Decision: Miners remove the TXs corresponding TX49
to both the blocks, from their Unconfirmed TX list

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX37 TX37
TX88

Miner 1 Miner 2 Miner 3


PoW: Mining a New Block Fork TX22
TX17
TX16
TX10 TX31
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Forks are resolved eventually TX49
• For the next block creation, a miner accepts the previous block that
it hears from the majority of the neighbor
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX37 TX37
TX88

Miner 1 Miner 2 Miner 3


PoW: Mining a New Block Fork TX22
TX17
TX37
TX88
TX16 TX91
TX10 TX31 TX97
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Forks are resolved eventually TX49
• For the next block creation, a miner accepts the previous block that
it hears from the majority of the neighbor
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX100 TX100
TX100
TX110
TX110

Miner 1 Miner 2 Miner 3


PoW: Mining a New Block Fork TX22
TX17
TX37
TX88
TX16 TX91
TX10 TX31 TX97
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Eventually, one block becomes part of the main chain TX49

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX100 TX100
TX100
TX110
TX110

Miner 1 Miner 2 Miner 3


PoW: Mining a New Block Fork TX22
TX17
TX37
TX88
TX16 TX91
TX10 TX31 TX97
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
For a forked block, if the transactions are not yet committed, TX49
include them in the Unconfirmed TX list

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX100 TX100
TX100
TX110
TX110

Miner 1 Miner 2 Miner 3


PoW: Mining a New Block Fork TX22
TX17
TX37
TX88
TX16 TX91
TX10 TX31 TX97
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
For a forked block, if the transactions are not yet committed, TX49
include them in the Unconfirmed TX list

Unconfirmed TX Unconfirmed TX Unconfirmed TX


TX100 TX100
TX100
TX87 TX110
TX110
TX49 TX87
TX87
TX49
TX49
Miner 1 Miner 2 Miner 3
PoW: Mining a New Block Fork TX22
TX17
TX37
TX88
TX16 TX91
TX10 TX31 TX97
TX11 TX19 TX22
TX16
TX13 TX17
TX45
TX42 TX55
TX16
TX67 TX40
TX56 TX31 TX16
TX32
TX17
TX87
Eventual consensus finality: TX49
• (Bitcoin) Cannot use a transaction until confirmation of 6 blocks –
ensured through scripts
Unconfirmed TX Unconfirmed TX Unconfirmed TX
TX100 TX100
TX100
TX87 TX110
TX110
TX49 TX87
TX87
TX49
TX49
Miner 1 Miner 2 Miner 3
Security Measures for PoW

• Sybil Attacks
• Attacker attempts to fill the network with the clients under
its control
• Create multiple identities (multiple public key addresses) to
control the network – refuse to relay valid blocks or relay
attacked blocks
• Solution: Diversify the connections – Bitcoin allows one
outbound connection to per /16 block of IP addresses –
cannot make both 202.141.81.2/16 and
202.141.80.18/16 as the peers
Security Measures for PoW

• Denial of Service (DoS)


• Send a lot of data to a node – block the processing power
• Solution: Limit forwarding of blocks, disconnect a peer that
sends too many transactions
Breaking PoW

• Bitcoin PoW is computationally difficult to break, but


not impossible

• Attackers can deploy high power servers to do more


work than the total work of the blockchain
Breaking PoW

• A known case of successful double-spending


• (November 2013) “it was discovered that the
GHash.io mining pool appeared to be engaging in
repeated payment fraud against BetCoin Dice, a
gambling site” [Source: https://en.bitcoin.it/]
The Monopoly Problem

• PoW depends on the computing resources available


to a miner
• Miners having more resources have more
probability to complete the work
The Monopoly Problem

• Monopoly can increase over time (Tragedy of the


Commons)
• Miners will get less reward over time
• Users will get discouraged to join as the miner
• Few miners with large computing resources may
get control over the network
The Monopoly Problem

• 51% Attack: A group of miners control more than


50% of the hash rate of the network
• Hypothetical as of now for Bitcoin (as the network is large),
but not impossible (happened for Kryptom – Ethereum
based blockchain, in August, 2016)
Conclusion

• PoW may result a fork – consensus finality is not


ensured

• The security of PoW is ensured with the condition


that attackers cannot gain more than 50% of the
hash power
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 21: Beyond PoW


• Open Consensus beyond PoW
• Proof of Stake (PoS)

• Proof of Burn (PoB)

• Proof of Elapsed Time (PoET)


The Limit of PoW

• The Good: A fully decentralized consensus for


permissionless models
• works good for cryptocurrencies – serves its
purposes
The Limit of PoW

• The Bad: Do not trust the individuals, but trust the


society as a whole
• You need a real large network to prevent the 51%
attack – not at all suitable for enterprise
applications
The Limit of PoW

• The Ugly: Low transaction throughput, Overuse of


computing power !!
• (Bitcoin) 3.3 to 7 transactions per second,
(Ethereum) ~15 transactions per second
• Millions of miners – thousands tries, but only one
gets the success
Bitcoin Energy Consumption

Image Source: Digiconomist Bitcoin Energy Consumption Index


Bitcoin Energy Consumption

Carbon Footprint
825.47 kg / TX
Equivalent
to 137,578 hours of
watching YouTube

Image Source: Digiconomist Bitcoin Energy Consumption Index


Bitcoin Energy Consumption

Electrical Energy
Carbon Footprint
1737.82 kWh / TX
825.47 kg / TX
Equivalent to power
Equivalent
consumption of an
to 137,578 hours of
average U.S. household
watching YouTube
over 59.56 days.

Image Source: Digiconomist Bitcoin Energy Consumption Index


Proof of Stake (PoS)

• Possibly proposed in 2011 by a Member in Bitcoin


Forum ‐
https://bitcointalk.org/index.php?topic=27787.0
• Make a transition from PoW to PoS when bitcoins are
widely distributed
Proof of Stake (PoS)

• PoW vs PoS
• PoW: Probability of mining a block depends on the work
done by the miner
• PoS: Amount of bitcoin that the miner holds – Miner
holding 1% of the Bitcoin can mine 1% of the PoS blocks.
Proof of Stake (PoS)

• Provides increased protection


• Executing an attack is expensive, you need more
Bitcoins
• Reduced incentive for attack – the attacker needs
to own a majority of bitcoins – an attack will have
more affect on the attacker
Proof of Stake (PoS)

• Variants of “stake”
• Randomization in combination of the stake (used
in Nxt and BlackCoin)
• Coin‐age: Number of coins multiplied by the
number of days the coins have been held (used in
Peercoin)
Proof of Burn (PoB)

• Miners should show proof that they have burned some


coins
• Sent them to a verifiably un‐spendable address
• Expensive just like PoW, but no external resources are used
other than the burned coins
• PoW vs PoB
• Real resource vs virtual/digital resource
• PoB works by burning PoW mined cryptocurrencies
Proof of Burn (PoB)

• Miners should show proof


PoS andthatPoB
they have burned some
coins
• Sent them to a verifiably un‐spendable address
• Expensive
Ultimately depends
just like PoW, but noon PoWresources
external mined are used
other than the burned coins
cryptocurrencies
• PoW vs PoB
You cannot
• Real resource use themresource
vs virtual/digital to bootstrap a
new blockchain
• PoB works by burning PoW mined cryptocurrencies
Proof of Elapsed Time (PoET)

• Proposed by Intel, as a part of Hyperledger


Sawtooth – a blockchain platform for building
distributed ledger applications

• Basic idea:
• Each participant in the blockchain network waits a
random amount of time
• The first participant to finish becomes the leader for the
new block
Proof of Elapsed Time (PoET)

• How will one verify that the proposer has really


waited ?
• Utilize special CPU instruction set – Intel Software Guard
Extension (SGX) – a trusted execution platform
• The trusted code is private to the rest of the application
• The specialized hardware provides an attestation that the
trusted code has been set up correctly
Intel SGX
Conclusion
• PoW is significantly costly
• Reduce the cost by moving towards PoS/PoB

• Los‐cost consensus from the bootstrap: PoET


• Needs specialized hardware

• What about enterprise application?


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 22: Ethereum 1


• Ethereum Introduction
• Ethereum Network
• Go Ethereum
• Query using RPC over HTTP
• Ethereum

• Geth

• Testnets
Ethereum

• "Ethereum is a technology that lets you send


cryptocurrency to anyone for a small fee. It
also powers applications that everyone can
use and no one can take down."

• Permissionless blockchain capable of


executing smart contracts.

https://ethereum.org/en/what‐is‐ethereum/
Ethereum Network

• Distributed network of computers, known as


nodes that can verify blocks and transaction
data.

• An application, known as a client, running on


your computer is a node.
Ethereum Network
Ethereum Mainnet

• No central server

• Independent nodes connected


in a P2P network.

https://ethstats.net/
https://www.ethernodes.org/countries
Interacting with an Ethereum Network
Interacting with an Ethereum Network

Mainnet / Testnet
Go Ethereum (Geth)
• Official Go implementation of the Ethereum protocol
• Main Ethereum CLI client
• Entry point into the Ethereum network
• main, test, or private net
• Capable of running as:
• Full node (default)
• Archive node (retaining all historical state)
• Light node (retrieving data live).
• Provides JSON RPC endpoints exposed on top of HTTP,
WebSocket and/or IPC transports.
Installing Geth

For Ubuntu

1. Add ethereum repository:


sudo add‐apt‐repository ‐y ppa:ethereum/ethereum

2. Then install the stable version of go‐ethereum:


sudo apt‐get update
sudo apt‐get install ethereum
Managing Ethereum Accounts
USAGE:
geth account command [command options] [arguments...]

COMMANDS:
list Print summary of existing accounts
new Create a new account
update Update an existing account
import Import a private key into a new account
Create an account
geth account new
List Accounts
geth account list

cat ~/.ethereum/keystore/<key file>


Connect to a network
• Starting geth without any flag connects to the Ethereum
mainnet.

• In addition to the mainnet, geth recognizes a few testnets


which you can connect to via the respective flags:

• --ropsten, Ropsten proof-of-work test network


https://ropsten.etherscan.io/

• --rinkeby, Rinkeby proof-of-authority test network


https://rinkeby.etherscan.io/

• --goerli, Goerli proof-of-authority test network


https://goerli.etherscan.io/
Sync modes
You can start Geth in one of three different sync modes using the ‐‐syncmode
"<mode>" argument that determines what sort of node it is in the network:

• full: Downloads all blocks (including headers, transactions, and receipts)


and generates the state of the blockchain incrementally by executing
every block.
• fast: Downloads all blocks (including headers, transactions and receipts),
verifies all headers, and downloads the state and verifies it against the
headers.
• snap (Default): Same functionality as fast, but with a faster algorithm.
• light: Downloads all block headers, block data, and verifies some
randomly.
Connecting to Goerli testnet
geth –goerli ‐‐syncmode "light"

Copy account to testnetwork


cp ~/.ethereum/keystore/UTC‐‐2021‐10‐26T20‐23‐14.304161080Z‐‐
8010319e8e3115ea522dc2f00ab9bc28a5abbf80 ~/.ethereum/rinkeby/keystore/
Interacting with Geth
You can interact with Geth in two ways:
• Directly with the node using the JavaScript console over IPC
or
• Connecting to the node remotely over HTTP using RPC.

IPC allows you to do more, especially when it comes to creating


and interacting with accounts, but you need direct access to the
node.

RPC allows remote applications to access your node but has


limitations and security considerations.
Using RPC over HTTP
geth ‐‐goerli ‐‐syncmode "light" ‐‐http
Query Balance
Querying the balance of an account:
POST request to the HTTP endpoint (default: 127.0.0.1:8545)

JSON Payload:
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",
"latest"
],
"id": 1
}
Query using curl
Querying the balance of an account:
POST request using curl:

curl -X POST http://localhost:8545 \


-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "method":"eth_getBalance",
"params":["0x5342722156fcd4b0e0b140c4fb9cd63dcea347f4","latest"], "id":1}'
Ethereum Units
Conclusion

• Ethereum
• Permissionless, smart contract support
• Go ethereum
• Main network, test networks
• Accounts

• Query using RPC over HTTP


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 23: Ethereum 2


• Obtaining Ethereum for testnets
• Unlocking account
• Geth transactions using RPC over HTTP
• Ethereum Transactions

• Gas

• Faucet
Query Balance
Ensure Geth is running.

Querying the balance of an account:


POST request to the HTTP endpoint (default: 127.0.0.1:8545)

JSON Payload:
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",
"latest"
],
"id": 1
}
Query Balance
Querying the balance of an account:
POST request using curl:

curl -X POST http://localhost:8545 \


-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "method":"eth_getBalance",
"params":["0x5342722156fcd4b0e0b140c4fb9cd63dcea347f4","latest"],
"id":1}'
Ethereum Transactions
• Transactions are cryptographically
signed instructions from accounts.

• An account will initiate a transaction to


update the state of the Ethereum
network.

• The simplest transaction is transferring


ETH from one account to another.
Ethereum Transactions
• Transactions are cryptographically
signed instructions from accounts.

• An account will initiate a transaction to


update the state of the Ethereum
network.

• The simplest transaction is transferring


ETH from one account to another.

Requires:
1. Access to account private key
2. Gas
Gas

• Each Ethereum transaction requires


computational resources to execute.

• Each transaction requires a fee.

• Gas refers to the fee required to conduct a


transaction on Ethereum successfully.

• Gas is paid as amounts of Ethers.


Get ether in testnet
• For executing transactions in a testnet, we can
obtain ethers from faucet.

• Goerli faucet:
• Social faucet: https://faucet.goerli.mudit.blog/
• Simple faucet: https://goerli-faucet.slock.it/

• Rinkeby faucet: https://faucet.rinkeby.io/


Get ether in Goerli testnet
• Post a tweet containg ethereum account address.
Get ether in Goerli testnet
• Paste tweet link in faucet.
Unlock Account
• Create new account for goerli testnet, suppose
password is set to "123"
• Write account password in a text file. Here we
name it pwd.txt
geth --goerli account new
echo "123" > pwd.txt

• Unlock account while starting geth


geth --goerli --syncmode "light" --http --allow-insecure-unlock --unlock
d84a0607843b28c3f468857f82f784d9ff743bf8 --password pwd.txt
eth_sendTransaction
POST sendTransaction
Creates new message call transaction or a contract creation, if the data field contains code.

Parameters
Object - The transaction object
from: DATA, 20 Bytes - The address the transaction is send from.
to: DATA, 20 Bytes -The address the transaction is directed to.
gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It
will return unused gas.
gasPrice: QUANTITY - (optional, default: To-Be-Determined) The gasPrice used for each paid gas
value: QUANTITY - (optional) Integer of the value sent with this transaction
data: DATA - The compiled code of a contract OR the hash of the invoked method signature and
encoded parameters. For details see Ethereum Contract ABI
nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending
transactions that use the same nonce.

Returns
DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available.
Prepare Transaction
{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [
{
"from": "0xd84a0607843b28c3f468857f82f784d9ff743bf8",
"to": "0x5f2316ff45c1c782e027b548f6f6e604655148f1",
"value": "0x2386F26FC10000"
}
],
"id": 0
} 0.1 eth
Submit Transaction
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "method":"eth_sendTransaction", "params":[{"from":
"0xd84a0607843b28c3f468857f82f784d9ff743bf8","to":
"0x5f2316ff45c1c782e027b548f6f6e604655148f1","value": "0x2386F26FC10000"}],
"id":0}'
View Transaction on Etherscan

https://goerli.etherscan.io/
Get Transaction by Hash
{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [
"0x576f04f98e8eb109e018d0727a69c9ebde64028491b4d17ddb
c01af6cfa24a65"
],
"id": 1
}
Get Transaction by Hash
curl -X POST http://localhost:8545 \
-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "method":"eth_getTransactionByHash",
"params":["0x576f04f98e8eb109e018d0727a69c9ebde64028491b4d17ddbc01af6cfa24a65"],
"id":1}'
Query Blocks
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"0x5828AD",
true
],
"id": 1
}

curl -X POST http://localhost:8545 \


-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "method":"eth_getBlockByNumber",
"params":["0x5828AD", true], "id":1}'
Query Blocks
Many More RPC Methods

https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-
apis/assembled-spec/openrpc.json
Conclusion

• Ethereum Transactions
• Obtaining Ether for testnets
• Unlocking Account
• Submit Transactions and monitor transactions
Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 24: Ethereum 3


• Ethereum applications - DAPPS

• Using web3.js to programmatically access Ethereum


network
• web3.js

• DAPPS
DAPPS in Ethereum
• DAPP - decentralized application
Smart Contracts
• Application that is built for decentralized
networks like Ethereum

• Combines two components: DAPP UI

1. Smart Contracts
2. User interface for executing
transactions and contracts
Programmatically access Ethereum networks

DAPP UI

Mainnet / Testnet
web3.js
• Ethereum JavaScript API
https://web3js.readthedocs.io/
DAPP UI
• Collection of libraries that allow you to
interact with a local or remote ethereum Web3.js
nodes. • HTTP​
• IPC​
• WebSocket​
• It can connect using:
Geth
• HTTP
• IPC
• WebSocket
Install web3.js
• Install Node.js
https://nodejs.org/en/

wget https://nodejs.org/dist/v16.13.0/node-v16.13.0-linux-x64.tar.xz

tar -xvf node-v16.13.0-linux-x64.tar.xz

export PATH=/home/<username>/nptel/node-v16.13.0-linux-x64/bin:$PATH

• Check node and npm version


node --version

npm --version
Install web3.js
• Install web3.js
npm install web3

• Verify that you can import web3


node
var Web3 = require('web3');
console.log(Web3.version)
Connecting web3.js to Geth

// Import web3
var Web3 = require('web3');

// Connect to local Geth client


var web3 = new Web3('http://localhost:8545');
Query Balance
• Create a file with .js extension. Example: "balance.js"
// Import web3
var Web3 = require('web3');

// Connect to local Geth client


var web3 = new Web3('http://localhost:8545');

// Query balance of an account


console.log("Balance of the account 0x35F18427567108F800BDC2784277B9246eED37fA is:");
web3.eth.getBalance("0x35F18427567108F800BDC2784277B9246eED37fA").then(console.log
);
Query Balance
• Create a file with .js extension. Example: "balance.js"
// Import web3
var Web3 = require('web3');

// Connect to local Geth client


var web3 = new Web3('http://localhost:8545');

// Query balance of an account


console.log("Balance of the account 0x35F18427567108F800BDC2784277B9246eED37fA is:");
web3.eth.getBalance("0x35F18427567108F800BDC2784277B9246eED37fA").then(console.log
);
Transfer Ether
// Import web3
var Web3 = require('web3');

// Connect to local Geth client


var web3 = new Web3('http://localhost:8545');

// Prepare transaction
var transaction = {
from: "0x7dad3a076678a05b2b4e2b93206dbecef0d7bbf0",
to: "0x35F18427567108F800BDC2784277B9246eED37fA",
value: Web3.utils.numberToHex(10000000000000000)
}

// Send the transaction


web3.eth.sendTransaction(transaction).then(console.log);
Transfer Ether
Conclusion

• Web3.js for DAPP Development

• Build interface for Ethereum applications


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 25: Ethereum 4


• Ethereum smart contracts

• Ethereum Virtual Machine (EVM)

• Solidity language

• Deploy and execute contracts


• Ethereum Smart Contracts

• EVM

• Solidity
Smart Contracts
• Program that is executed in a
decentralized setting.

• Acts on distributed ledger data. Smart Contracts

• Output of the program depends on


consensus of independent participants
executing it.
Ethereum Smart Contracts
• Program that reads data from the Ethereum ledger, performs operations on
it, and writes back the output to the ledger.

• Smart contracts are a type of Ethereum account.


• have a balance
• can send transactions over the network
• not controlled by a user, run as programmed

• User accounts interact with a smart contract by submitting transactions


that execute a function defined on the smart contract.
Ethereum Virtual Machine - EVM
• Ethereum implements a
distributed state machine /
replicated state machine.

• Ledger data holds the state -


accounts, balances, and other
variables.

• Transactions deterministically
change the machine from one
state to another.
Compiler
Deploy
Bytecode Smart Contract

Smart Contract Code

Compiler
• Solidity
• Vyper

Application Binary
Interface (ABI) Web3.js

https://vyper.readthedocs.io/en/stable/
https://docs.soliditylang.org/en/v0.8.9/
Solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;
• High-level language for implementing
smart contracts contract SimpleStorage {

uint storedData;
• Statically typed
• Supports inheritance function set(uint x) public {
storedData = x;
• Libraries }
• Complex user-defined types
function get() public view returns (uint) {
return storedData;
• Syntax influenced by Javascript and C++ }

https://docs.soliditylang.org/en/v0.8.9/
Compiling Solidity
• solc compiler • Remix editor
• Compile .sol files to bytecode • Browser based
• Command line tool • Compile, emulate, deploy contracts
• https://remix.ethereum.org/

https://docs.soliditylang.org/en/v0.8.9/installing-solidity.html#installing-solidity
Simple Storage Contract
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Storage {

uint256 positivenumber;

function store(uint256 inputnumber) public {


positivenumber = inputnumber;
}

function readdata() public view returns (uint256){


return positivenumber;
}

}
Executing with Web3
var Web3 = require('web3');
var Contract = require('web3-eth-contract');

Contract.setProvider(new Web3.providers.HttpProvider('http://localhost:8545'));

var myContract = new Contract(<ABI>,

"0xb3f36458FFc0C686DB4f2FF6002a55bFD85C03C8",
{
from: "0xd84a0607843b28c3f468857f82f784d9ff743bf8",
gasPrice: "20000000000"
}

);

myContract.methods.readdata().call().then(function (output) { console.log(output) });

Read data
Executing with Web3
var Web3 = require('web3');
var Contract = require('web3-eth-contract');

Contract.setProvider(new Web3.providers.HttpProvider('http://localhost:8545'));

var myContract = new Contract(<ABI>,

"0xb3f36458FFc0C686DB4f2FF6002a55bFD85C03C8",
{
from: "0xd84a0607843b28c3f468857f82f784d9ff743bf8",
gasPrice: "20000000000"
}

);

myContract.methods.store("11").send().then(function (output) { console.log(output) });

Write data
Conclusion

• Ethereum smart contracts

• Remix editor

• Executing smart contracts from Web3 for DAPPS


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 26: Consensus for Permissioned Models


• Permissioned Model

• State Machine Replication


• Consensus on State Machines
Permissioned Model

• A blockchain architecture where users are authenticated a


priori
• A Membership Service Provider (MSP) helps to obtain the chain
membership
• Users know each other
• However, users may not trust each other
• Security and consensus are still required.
• Run blockchain among known and identified
participants
Permissioned Model

• Particularly interesting for business applications – execute


contracts among a closed set of participants

• Example: Provenance tracking of assets in a supply chain


A Use Case
Smart Contracts over Closed Networks

• Smart Contracts: “A self-executing contract in which the


terms of the agreement between the buyer and the seller
is directly written into the lines of code” -
http://www.scalablockchain.com/
Smart Contracts over Closed Networks

• Agreement on a Smart Contract Execution:


• Store the contract on a blockchain
• Once an event is triggered, execute the codes locally on
each peer
• Generate transactions as the output of the contract
execution
• The peers of the blockchain network validates the
transaction, and the output is committed in the
blockchain – may trigger the next event to execute the
code further
Smart Contracts over Closed Networks

• Agreement on a Smart Contract Execution:


• Store the contract on a blockchain
• Once an event is triggered, execute the codes locally on
each peer
• Generate transactions as the output of the contract
execution
Do we really need to execute
• The peers of the blockchain network validates the
transaction,the code
and the oniseach
output peer?
committed in the
blockchain – may
When trigger
does thepeer
each next event to execute
execute the the
code further
code?
Smart Contracts over Closed Networks

• Execute contract at a subset of nodes, and ensure


that the same state is propagated to all the nodes
• Majority of the peers should agree on the state
• Validation: Generate a "proof" that a peer has agreed
on the "state of execution"
Smart Contracts over Closed Networks

• Execute contract at a subset of nodes, and ensure


that the same state is propagated to all the nodes
• Majority of the peers should agree on the state
• Validation: Generate a "proof" that a peer has agreed
on the "state of execution"

How will we generate the


proof?
Smart Contracts over Closed Networks

• Execute contract at a subset of nodes, and ensure


that the same state is propagated to all the nodes
• Majority of the peers should agree on the state
• Validation: Generate a "proof" that a peer has agreed
on the "state of execution"
Smart Contract as State Machines

• State Machine Replication:


• Represent the smart contract as a state machine
– Remember, any deterministically executable
code can be represented as a state machine
Smart Contract as State Machines

S1:
while (moreGoods == 1)
DeliverGoods();
S2:
if (allOrderComplete == 0) goto S1;
else {
S3:
printf("Goods transfer complete");
}
State Machine Replication Replicate the state machine
on multiple independent
servers
State Machine Replication T1:
I have delivered 100kg
potatoes
T1
State Machine Replication
T1

T2:
I have delivered
50kg tomatoes
T2
State Machine Replication
T1

T2
State Machine Replication
T1

Consensus on the
Ordering of the
transactions

T2
State Machine Replication T1
T2

T1 T1
T2 T2
State Machine Replication T1
T2

T1 Independently T1
T2 execute the T2
transactions
on the state
machine
State Machine Replication T1
T2

T1 Independently T1
T2 execute the T2
transactions
on the state
machine
State Machine Replication

S2

S2

Consensus on the
Final State
S2
State Machine Replication

S2

S2

S2
Importance of Consensus

S2

S3

S2
Importance of Consensus

S2

Majority Voting – S3

Agree on S2
S2
Conclusion
• Consensus is still required within a closed environment

• How can we extend state machine replication for


permissioned models?
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 27: State Machine Replication as Distributed


Consensus
• State Machine Replication as a Consensus

• Synchronous vs Asynchronous Consensus with Crash


Faults
• Crash Fault Tolerance

• Paxos
State Machine Replication as Consensus

• There is a natural reason to use state machine


replication-based consensus over permissioned
blockchains
• The network is closed, the nodes know each other, so
state replication is possible among the known nodes
• Avoid the overhead of mining - do not need to spend
anything (like power, time, bitcoin) other than message
passing
• However, consensus is still required - machines can be
faulty or behave maliciously
State Machine Replication as Consensus

• There is a natural reason to use state machine


replication-based consensus over permissioned
blockchains
• The network is closed, the nodes know each other, so
stateBut,
replication is possible
we need among
a bit the known
redesign ! nodes
• Avoid the overhead of mining - do not need to spend
anything (like power, time, bitcoin) other than message
passing
• However, consensus is still required - machines can be
faulty or behave maliciously
State Machine Replication as Consensus

• There is a natural reason to use state machine


replication-based consensus over permissioned
But, we need a bit redesign !
blockchains
• The networkCrypto is the
is closed, thenodes
saver
know each other, so
state replication
Crypto is possible among
+ Distributed the known
Consensus = nodes
• Avoid Consensus
the overheadfor of mining - do not need to spend
Permissioned
anything (like power, time, bitcoin) other than message
passing Blockchain
• However, consensus is still required - machines can be
faulty or behave maliciously
State Machine Replication as Consensus

• Classical Distributed Consensus Algorithms (Paxos,


RAFT, Byzantine Agreement) are based on State
Machine Replication
• Let us (re)visit those algorithms
Faults in a Distributed Systems

• Crash Faults: The node stops operating – hardware


or software faults
• In an asynchronous system: You do not know whether
messages have been delayed or the node is not
responding
• Rely on majority voting – progress as and when you have
received the confirmation from the majority
• Propagation of the consensus information – nodes on a
slow network will receive it eventually
Faults in a Distributed Systems

• Byzantine Faults: Nodes misbehave – send different


information to different peers (partition the
network)
• More difficult to handle
• More suitable for blockchains
Asynchronous Consensus with Crash Faults

• Remember the FLP Impossibility


• Give priority to safety over liveness

• Guarantees the followings --


• Validity: If all correct process proposes the same value v,
then any correct process decides v
• Agreement: No two correct processes decide differently
• Termination: Every correct process eventually decides
Asynchronous Consensus with Crash Faults

• Guarantees the followings --


• Validity: If all correct process proposes the same value v, then
any correct process decides v ( Unlikely to happen in PoW)

• Agreement: No two correct processes decide


differently (Safety – Not in PoW)

• Termination: Every correct process eventually


decides (Liveness – Priority in PoW)
CFT Consensus

• CFT Consensus
• Paxos (Proposed by Lamport, the most fundamental CFT) --
used in DynamoDB
• RAFT (Much simpler than Paxos) -- Used in Fabric Transaction
Ordering
CFT Consensus
We'll see how Paxos works
• CFT Consensus
• Paxos (Proposed by Lamport, the most fundamental CFT) --
used in DynamoDB
• RAFT (Much simpler than Paxos) -- Used in Fabric Transaction
Ordering
CFT in a Synchronous System
CFT in a Synchronous System

Let's go for
a dinner
CFT in a Synchronous System

Let's go for
a dinner

Perfect!
I'm in ...

Let's go ...
CFT in a Synchronous System

Let's go for
a dinner Majority agreed …
Perfect!
Perfect consensus
I'm in ...

Let's go ...
CFT in an Asynchronous System

Let's go for
a dinner
CFT in an Asynchronous System

Let's go for
a dinner
I'm in
CFT in an Asynchronous System

Let's go for
a dinner
I'm in

I'm okay
CFT in an Asynchronous System

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
CFT in an Asynchronous System

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
prefer movie
CFT in an Asynchronous System

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
CFT in an Asynchronous System

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
CFT in an Asynchronous System

Let's go for
a dinner Consensus on a
I'm in Movie
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
CFT in an Asynchronous System

We are going for


dinner, right?
CFT in an Asynchronous System

We are going for


dinner, right?

Nopes ! We decided
for a movie!
CFT in an Asynchronous System

We are going for


dinner, right?

Nopes ! We decided
for a movie!

Umm! May
not like, but that's
the only option for
me :(
CFT in an Asynchronous System

How many
We are going for people can be
dinner, right?
sleeping at a time?
Nopes ! We decided
for a movie!

Umm! May
not like, but that's
the only option for
me :(
CFT in an Asynchronous System

How many people can be


sleeping
We are going for at a time?
dinner, right?

Nopes ! We decided
for a movie!
2
Umm! May
not like, but that's
the only option for
me :(
Asynchronous CFT
• If there are F faulty nodes (crash fault), we need atleast 2F+1
nodes to reach consensus

• Paxos: A family of distributed algorithms to reach consensus


in an asynchronous CFT
What is Paxos?

• We'll discuss vanilla Paxos


• Proposed by Lamport in 1989
• Received a lot of criticism about its proof of
correctness
• Accepted in ACM Transactions on Computer
Systems in 1998, titled "The Part-
time Parliament"
• Lamport received the Turing award in 2013
Conclusion
• Consensus is harder on asynchronous environment

• For asynchronous CFT, we need 2F+1 nodes with F crash


faults only

• Let's explore Paxos in the next class


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 28: Paxos


• Paxos – CFT Consensus
• Paxos

• CFT
Paxos – The Roles of Individuals

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Paxos – The Roles of Individuals
Proposer Proposer

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Paxos – The Roles of Individuals
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Acceptor Acceptor
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Learner Learner
Learner Acceptor Learner Learner Acceptor
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
I'm in
Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Learner Learner
Learner Acceptor Learner Learner Acceptor
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
I'm in
A node can have any or all of
the three roles Can we go
I'm okay for a movie?
I would
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Learner Learner
Learner Acceptor Learner Learner Acceptor
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
A node can have any or all of the three roles
I'm in
However, the nodes must knowCan howwe go
I'm okay for a movie?
many acceptors aI majority
would
is
Movie is a prefer movie
better idea
I'm okay with
movie too ...
Learner Learner
Learner Acceptor Learner Learner Acceptor
Acceptor Proposer Acceptor Acceptor Proposer

Let's go for
a dinner
Two majorities will always overlap in
I'm in
atleast I'm
one okay nodes Can we go
for a movie?
5 acceptors, majority = 3,I would
Movie is a 2 proposers: prefer movie
better idea
To accept based on majority voting, at least one acceptor
I'm okay with
movie need
too ... to choose between one of the two proposals
Paxos Basics

• Paxos is based on state-machine replication


• Proposers and Acceptors maintain a state of the running
epochs
• Uses a variable IDp where p is an epoch number –
maintains the state
• A Paxos run aims at reaching a single consensus
• Once a consensus is reached, Paxos cannot progress to
another consensus
• To reach multiple consensus, you need to run Paxos in
rounds (Multi-Paxos)
Paxos Algorithm
Proposer

Acceptor
Acceptor
Acceptor
Paxos Algorithm
Proposer

Acceptor
Acceptor
Acceptor

• Proposer wants to propose its choice (values):


• Sends PREPARE IDp to a majority (or all) of
the acceptors
Paxos Algorithm
PREPARE 100
Proposer

Acceptor
Acceptor
Acceptor

• Proposer wants to propose its choice (values):


• Sends PREPARE IDp to a majority (or all) of
the acceptors
Paxos Algorithm
PREPARE 100
Proposer
IDp must be unique across proposers
for each PREPARE message
Acceptor Ex. Use Hash(timestamp+Proposer
Acceptor
Acceptor ID) to generate p

• Proposer wants to propose its choice (values):


• Sends PREPARE IDp to a majority (or all) of
the acceptors
Paxos Algorithm
PREPARE 100
Proposer

Acceptor
Acceptor
Acceptor

• Acceptor received a PREPARE message with IDp:


• Did it promised to ignore requests with this IDp?
• YES: Ignore
• NO: Will promise to ignore any request lower than IDp
• (?) Reply with PROMISE IDp
Paxos Algorithm
PREPARE 100
Proposer

Acceptor
Acceptor
Acceptor
PROMISE 100

• Acceptor received a PREPARE message with IDp:


• Did it promised to ignore requests with this IDp?
• YES: Ignore
• NO: Will promise to ignore any request lower than IDp
• (?) Reply with PROMISE IDp
Paxos Algorithm If majority of acceptors
PREPARE 100 promise, no ID < IDp can pass
Proposer
the protocol

The acceptors agree on State


Acceptor
Acceptor
Acceptor 100
PROMISE 100

• Acceptor received a PREPARE message with IDp:


• Did it promised to ignore requests with this IDp?
• YES: Ignore
• NO: Will promise to ignore any request lower than IDp
• (?) Reply with PROMISE IDp
Paxos Algorithm
PREPARE 100
Proposer

Acceptor
Acceptor
Acceptor
PROMISE 100

• Proposer gets majority of PROMISE messages for a specific


IDp:
• Sends ACCEPT-REQUEST IDp, VALUE to a majority (or
all) of Acceptors
• (?) It picks any value of its choice
Paxos Algorithm ACCEPT-REQUEST 100,
PREPARE 100 "Dinner"
Proposer

Acceptor
Acceptor
Acceptor
PROMISE 100

• Proposer gets majority of PROMISE messages for a specific


IDp:
• Sends ACCEPT-REQUEST IDp, VALUE to a majority (or
all) of Acceptors
• (?) It picks any value of its choice
Paxos Algorithm ACCEPT-REQUEST 100,
PREPARE 100 "Dinner"
Proposer

Acceptor
Acceptor
Acceptor
PROMISE 100

• Acceptor receives an ACCEPT-REQUEST IDp, VALUE :


• Did it promised to ignore request with this IDp?
• YES: Ignore
• NO: Reply with ACCEPT IDp, VALUE; Also send it
to all learners
Paxos Algorithm ACCEPT-REQUEST 100,
PREPARE 100 "Dinner"
Proposer
Learner

Acceptor
Acceptor
Acceptor
PROMISE 100 ACCEPT 100, "Dinner"

• Acceptor receives an ACCEPT-REQUEST IDp, VALUE :


• Did it promised to ignore request with this IDp?
• YES: Ignore
• NO: Reply with ACCEPT IDp, VALUE; Also send it
to all learners
Paxos Algorithm ACCEPT-REQUEST 100,
PREPARE 100 "Dinner"
Proposer
Learner
If majority of acceptors accept
IDp, VALUE, consensus is
Acceptor reached
Acceptor
Acceptor
PROMISE 100 ACCEPT 100, "Dinner"
Consensus is reached on the
• Acceptor receives an ACCEPT-REQUEST IDp, VALUE :
value, not on IDp
• Did it promised to ignore request with this IDp?
• YES: Ignore
• NO: Reply with ACCEPT IDp, VALUE; Also send it
to all learners
Paxos Algorithm ACCEPT-REQUEST 100,
PREPARE 100 "Dinner"
Proposer
Learner

Acceptor
Acceptor
Acceptor
PROMISE 100 ACCEPT 100, "Dinner"

• Proposer or Learner gets ACCEPT message with IDp, VALUE:


• If a proposer/learner gets majority of accept for a
specific IDp, they know that consensus is reached for
the value (not IDp).
Paxos – Multiple Proposers
PREPARE 50
Proposer Proposer

Acceptor
Acceptor
Acceptor
ACCEPT 100, "Dinner"
Paxos – Multiple Proposers
PREPARE 150
Proposer Proposer
PROMISE 150,
accepted 100,
Acceptor "Dinner"
Acceptor
Acceptor
ACCEPT 100, "Dinner"
• Acceptor received a PREPARE message with IDp:
• Did it promised to ignore requests with this IDp?
• YES: Ignore
• NO: Will promise to ignore any request lower than IDp
• Has it ever accepted anything? (Assume accepted ID = IDa)
• YES: Reply with PROMISE IDp accepted IDa, VALUE
• NO: Reply with PROMISE IDp
Paxos – Multiple Proposers
PREPARE 150
Proposer Proposer
PROMISE 150,
accepted 100,
Acceptor "Dinner"
Acceptor
Acceptor
ACCEPT 100, "Dinner"

What the proposer will do?


Paxos – Multiple Proposers
PREPARE 150
Proposer Proposer
PROMISE 150,
accepted 100,
Acceptor "Dinner"
Acceptor
Acceptor
ACCEPT 100, "Dinner"

• Proposer gets majority of PROMISE messages for a specific IDp:


• It sends ACCEPT-REQUEST IDp, VALUE to a majority (or
all) of Acceptors
• (?) It picks any value it wants
Paxos – Multiple Proposers
PREPARE 150
Proposer Proposer
PROMISE 150,
accepted 100,
Acceptor "Dinner"
Acceptor
Acceptor
ACCEPT 100, "Dinner"
• Proposer gets majority of PROMISE messages for a specific IDp:
• It sends ACCEPT-REQUEST IDp, VALUE to a majority (or
all) of Acceptors
• Has it got any already accepted value from promises?
• YES: Picks the value with the highest IDa
• NO: Picks the value of its choice
Paxos – Multiple Proposers ACCEPT-
PREPARE 150 REQUEST 150, "Dinner
Proposer Proposer "
PROMISE 150,
accepted 100,
Acceptor "Dinner"
Acceptor
Acceptor
ACCEPT 100, "Dinner"
• Proposer gets majority of PROMISE messages for a specific IDp:
• It sends ACCEPT-REQUEST IDp, VALUE to a majority (or
all) of Acceptors
• Has it got any already accepted value from promises?
• YES: Picks the value with the highest IDa
• NO: Picks the value of its choice
Conclusion
• Paxos works in two rounds
• Agreement on the state (ID)
• Agreement on the value

• Safety and liveness of Paxos?


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 29: Paxos – Safety and Liveness


• Safety and Liveness of Paxos
• Paxos: Correctness

• Leader Election

• Multi-Paxos
Paxos – Message Exchanges
PREPARE 100 ACCEPT-REQUEST 100, "Dinner"
Proposer
Learner

Acceptor
Acceptor
Acceptor
PROMISE 100 ACCEPT 100, "Dinner"

• Two rounds of message exchanges


• PREPARE – PROMISE: Agree on a state (ID)
• ACCEPT-REQUEST – ACCEPT: Agree on a value
• The consensus is on the "value"
Majority Voting
Proposer 1
PREPARE 100

Proposer 2

Acceptor 1

Acceptor 2

Acceptor 3
Majority Voting
Proposer 1
PREPARE 100

Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2

Acceptor 3
Majority Voting
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2

Acceptor 3
Majority Voting
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2
PROMISE 100
Acceptor 3
Majority Voting
If the majority of the acceptors
PREPARE 100
Proposer 1 promised on ID100, ID50 cannot
PREPARE 50 get through (those acceptors will
Proposer 2
ignore)

Acceptor 1
PROMISE 100

Acceptor 2
PROMISE 100
Acceptor 3
Majority Voting
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 ignore
Acceptor 3
Majority Voting
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 ignore
Acceptor 3
Majority Voting
Proposer 1
PREPARE 100 Not a majority
PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 ignore
Acceptor 3
PROMISE 50
Majority Voting
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 ignore
Acceptor 3
PROMISE 50 PROMISE 100
Majority Voting – Case 2
Proposer 1
PREPARE 100

Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2

Acceptor 3
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2

Acceptor 3
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 50

Acceptor 3
Majority Voting – Case 2
PREPARE 100 Becomes the
Proposer 1
majority
PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 50

Acceptor 3
PROMISE 50
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50 ACCEPT-REQUEST 50, "Movie"


Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 50

Acceptor 3
PROMISE 50
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50 ACCEPT-REQUEST 50, "Movie"


Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 50 PROMISE 100

Acceptor 3
PROMISE 50
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50 ACCEPT-REQUEST 50, "Movie"


Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 50 PROMISE 100

Acceptor 3
PROMISE 50 PROMISE 100
Majority Voting – Case 2
Proposer 1
PREPARE 100

PREPARE 50 ACCEPT-REQUEST 50, "Movie"


Proposer 2

Acceptor 1
PROMISE 100 ignore ignore
ignore
Acceptor 2
PROMISE 50 PROMISE 100 ignore

Acceptor 3
PROMISE 50 PROMISE 100
Majority Voting – Case 2 100 Becomes the
majority
Proposer 1
PREPARE 100

PREPARE 50 ACCEPT-REQUEST 50, "Movie"


Proposer 2

Acceptor 1
PROMISE 100 ignore ignore
ignore
Acceptor 2
PROMISE 50 PROMISE 100 ignore

Acceptor 3
PROMISE 50 PROMISE 100
Liveness
Proposer 1
PREPARE 100

Proposer 2

Acceptor 1

Acceptor 2

Acceptor 3
Liveness
Proposer 1
PREPARE 100

Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2
PROMISE 100
Acceptor 3
Liveness
Proposer 1
PREPARE 100

PREPARE 150
Proposer 2

Acceptor 1
PROMISE 100

Acceptor 2
PROMISE 100
Acceptor 3
Liveness
Proposer 1
PREPARE 100

PREPARE 150
Proposer 2

Acceptor 1
PROMISE 100 PROMISE 150

Acceptor 2
PROMISE 100 PROMISE 150
Acceptor 3
Liveness
PREPARE 100 ACCEPT-REQUEST 100, "Dinner"
Proposer 1

PREPARE 150
Proposer 2

Acceptor 1
PROMISE 100 PROMISE 150

Acceptor 2
PROMISE 100 PROMISE 150
Acceptor 3
Liveness
PREPARE 100 ACCEPT-REQUEST 100, "Dinner"
Proposer 1

PREPARE 150
Proposer 2

ignore
Acceptor 1
PROMISE 100 PROMISE 150
ignore
Acceptor 2
PROMISE 100 PROMISE 150
Acceptor 3
Liveness
PREPARE 100 ACCEPT-REQUEST 100, "Dinner" PREPARE 200
Proposer 1

PREPARE 150
Proposer 2

ignore
Acceptor 1
PROMISE 100 PROMISE 150
ignore
Acceptor 2
PROMISE 100 PROMISE 150
Acceptor 3
Liveness
PREPARE 100 ACCEPT-REQUEST 100, "Dinner" PREPARE 200
Proposer 1

PREPARE 150
Proposer 2

ignore
Acceptor 1
PROMISE 100 PROMISE 150 PROMISE 200
ignore
Acceptor 2
PROMISE 100 PROMISE 150 PROMISE 200
Acceptor 3
Liveness
PREPARE 100 ACCEPT-REQUEST 100, "Dinner" PREPARE 200
Proposer 1 There is no termination guarantee
PREPARE 150 on Paxos
Proposer 2

ignore
Acceptor 1
PROMISE 100 PROMISE 150 PROMISE 200
ignore
Acceptor 2
PROMISE 100 PROMISE 150 PROMISE 200
Acceptor 3
Majority of Accepts
• Majority of acceptors accept a request with an ID and a
value
• Consensus has been reached
• The consensus is on the value

• Accept request with a lower ID


• Will not be accepted by the majority (Would require
majority of promises with the lower ID, but we got
for a higher one, hence the accept request)
Majority of Accepts
• Majority of acceptors accept a request with an ID and a
value
• Consensus has been reached
• The consensus is on the value

• Accept request with a lower ID


• Will not be accepted by the majority (Would require
majority of promises with the lower ID, but we got
for a higher one, hence the accept request)
Majority of Accepts
• Accept request with a higher ID but a different value
• Will not be accepted by the majority
• At least one acceptor will piggyback the previously
accepted value (Remember, two majority implies
that there is a common node)
Majority of Accepts
• Accept request with a higher ID but a different value
• Will not be accepted by the majority
• At least one acceptor will piggyback the previously
So, thevalue
accepted consensus is on
(Remember, the
two valueimplies
majority
that there is a common node)
We need the ID to maintain the current
state of promise and accept, so that
multiple values does not propagate
Paxos for Leader Election
PREPARE 100 ACCEPT-REQUEST 100, "Leader"
Proposer
Learner

Acceptor
Acceptor
Acceptor
PROMISE 100 ACCEPT 100, "Leader"
Multi-Paxos
• Applications often needs a continuous stream of agreed
values
• Commit the transactions in a replicated database – each
transaction needs a consensus to be agreed upon by the
replicas

• Run multiple instances of Paxos with different round


numbers
• Each value is associated with a round number
Multi-Paxos
• If a value is already accepted for Round n, ignore the accept
requests for a different value under Round n
• Forward an ACCEPT IDp, (ROUNDn, VALUE) only when no
value has been agreed upon for the Round n
Conclusion
• CFT consensus in asynchronous system – Paxos
• Safety is ensured, but liveness is compromised

• Does Paxos work when a node sends a wrong message?


Conclusion – Attack on Paxos
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 PROMISE 50
Acceptor 3
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 30: Byzantine Faults


• Byzantine Faults

• Byzantine Agreement Protocols


• BFT Consensus

• BFT Agreement
Malicious Behavior on Paxos
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 PROMISE 50
Acceptor 3
Malicious Behavior on Paxos
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 PROMISE 50
Acceptor 3
PROMISE 50
Malicious Behavior on100Paxos
is the
majority
Proposer 1
PREPARE 100

PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 PROMISE 50
Acceptor 3
PROMISE 50
Malicious Behavior on100Paxos
is the
majority
50 is the
Proposer 1
PREPARE 100 majority
PREPARE 50
Proposer 2

Acceptor 1
PROMISE 100 ignore

Acceptor 2
PROMISE 100 PROMISE 50
Acceptor 3
PROMISE 50
Malicious Behavior on Paxos
Proposer 1
A-R 100, "Dinner"

A-R 50, "Movie"


Proposer 2

Acceptor 1
ACCEPT 100, ignore
"Dinner"
Acceptor 2
ACCEPT 100, ACCEPT 50,
"Dinner" "Movie"
Acceptor 3
ACCEPT 50,
"Movie"
We agreed
Malicious Behavior on Paxos
for Dinner

Proposer 1
A-R 100, "Dinner"

A-R 50, "Movie"


Proposer 2

Acceptor 1
ACCEPT 100, ignore
"Dinner"
Acceptor 2
ACCEPT 100, ACCEPT 50,
"Dinner" "Movie"
Acceptor 3
ACCEPT 50,
"Movie"
We agreed
Malicious Behavior on Paxos
for Dinner No, we
A-R 100, "Dinner" agreed for
Proposer 1
Movie
A-R 50, "Movie"
Proposer 2

Acceptor 1 Click to add text


ACCEPT 100, ignore
"Dinner"
Acceptor 2
ACCEPT 100, ACCEPT 50,
"Dinner" "Movie"
Acceptor 3
ACCEPT 50,
"Movie"
Byzantine Generals Problem

Lieutenant - 1

Commander
Lieutenant - 2
Byzantine Generals Problem

Attack
Lieutenant - 1

Commander
Lieutenant - 2
Attack
Byzantine Generals Problem

Faulty Attack
Commander
Lieutenant - 1

Commander
Lieutenant - 2
Retreat
Byzantine Generals Problem We need a consensus
mechanism to decide
who is faulty
Faulty Attack
Commander
Lieutenant - 1

Commander
Lieutenant - 2
Retreat
Byzantine Generals Problem

Faulty Attack
Commander
Lieutenant - 1

Attack

Commander
Lieutenant - 2
Retreat
Byzantine Generals Problem

Faulty Attack
Commander
Lieutenant - 1

Attack Retreat

Commander
Lieutenant - 2
Retreat
Byzantine Generals Problem
Can we reach
consensus?
Faulty Attack
Commander
Lieutenant - 1

Attack Retreat

Commander
Lieutenant - 2
Retreat
Byzantine Generals Problem

Good Attack
Commander
Lieutenant - 1

Commander
Attack Lieutenant - 2
Byzantine Generals Problem

Good Attack
Commander
Lieutenant - 1

Attack Retreat

Commander
Attack Lieutenant - 2

Faulty
Lieutenant
Byzantine Generals Problem

Good Attack
Commander
Lieutenant - 1
Consensus is NOT POSSIBLE with one
commander and two lieutenants,
when one is faulty Attack Retreat

Commander
Attack Lieutenant - 2

Faulty
Lieutenant
Byzantine Generals Problem – Case 2
Faulty
Commander Attack

Attack

Retreat
Byzantine Generals Problem – Case 2
Faulty
Commander Attack

Attack

Retreat
Retreat

Retreat
Byzantine Generals Problem – Case 2
Faulty
Commander Attack

Attack Attack
Attack
Retreat
Attack
Retreat

Retreat
Attack
Byzantine Generals Problem – Case 2
Faulty Attack: 2
Commander Attack Retreat: 1

Attack Attack
Attack
Retreat
Attack
Retreat

Retreat
Attack: 2 Attack: 2
Attack
Retreat: 1 Retreat: 1
Byzantine Generals Problem – Case 2
Faulty Attack: 2
Commander Attack Retreat: 1

Attack Attack
Consensus is reached !Attack
Retreat
Attack
Retreat

Retreat
Attack: 2 Attack: 2
Attack
Retreat: 1 Retreat: 1
Byzantine Generals Problem – Case 2
Good
Commander Attack

Attack

Attack
Byzantine Generals Problem – Case 2
Good
Commander Attack

Attack

Attack

Retreat

Faulty Attack
Lieutenant
Byzantine Generals Problem – Case 2
Good
Commander Attack

Attack Attack
Attack
Attack
Attack
Retreat
Faulty
Commander
Attack

Attack
Byzantine Generals Problem – Case 2
Good Attack: 2
Commander Attack Retreat: 1

Attack Attack
Attack
Attack
Attack
Retreat
Faulty
Commander
Attack
Attack: 3 Attack: 3
Attack
Retreat: 0 Retreat: 0
Byzantine Generals Problem – Case 2
Good Attack: 2
Commander Attack Retreat: 1

Attack Attack
Consensus is reached !Attack
Attack
Attack
Retreat
Faulty
Commander
Attack
Attack: 3 Attack: 3
Attack
Retreat: 0 Retreat: 0
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
• Faulty nodes create partition in the network
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
• Faulty nodes create partition in the network
3F
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
• Faulty nodes create partition in the network
F F F
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
• Faulty nodes create partition in the network
F F F

PL PF PR
Asynchronous Byzantine Agreement
• F faulty nodes – need 3F + 1 nodes to reach consensus
• Faulty nodes create partition in the network
F F F
0 1

0 1

PL PF PR
Asynchronous Byzantine Agreement
Either PL or PR
• F faulty nodes – need 3F + 1 nodes to reach consensus must break the
• Faulty nodes create partition in the network tie
F F F
0 1

0 1

PL PF PR
Asynchronous Byzantine Agreement
Put
• F faulty nodes – need 3F + 1 nodes to reach consensus one additional
• Faulty nodes create partition in the network node to PL / PR
F F F
0 1

0 1

PL PF PR
Asynchronous Byzantine Agreement
Put
• F faulty nodes – need 3F + 1 nodes to reach consensus one additional
• Faulty nodes create partition in the network node to PL / PR
F+1 F F
0 1
Breaks the
tie to
reach 0 1
consensus

PL PF PR
Conclusion
• Paxos does not work with Byzantine faults
• Much harder to solve than crash faults

• With F faulty nodes, we need 3F + 1 nodes to reach


consensus in a BFT system
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 31: Byzantine Agreement Protocols


• Practical Byzantine Fault Tolerance (PBFT)
• PBFT Algorithm

• Quorum in PBFT
BFT Consensus
• Lamport-Shostak-Peas Algorithm*
• Synchronous environment
• Reliable communication channel
• Fully Connected Network
• Receivers always know the identity of the Senders

* LAMPORT, LESLIE, ROBERT SHOSTAK, and MARSHALL PEASE.


"The Byzantine Generals Problem." ACM Transactions on
Programming Languages and Systems 4.3 (1982): 382-401.
BFT Consensus
Unrealistic
• Lamport-Shostak-Peas Algorithm* assumptions for real
• Synchronous environment networks
• Reliable communication channel
• Fully Connected Network
• Receivers always know the identity of the Senders

* LAMPORT, LESLIE, ROBERT SHOSTAK, and MARSHALL PEASE.


"The Byzantine Generals Problem." ACM Transactions on
Programming Languages and Systems 4.3 (1982): 382-401.
BFT Consensus
• Many different variants of BFT Consensus have emerged

• Practical Byzantine Fault Tolerance (PBFT)**


• Use cryptographic techniques to release the
*unrealistic* assumptions

** Castro, Miguel, and Barbara Liskov. "Practical byzantine fault


tolerance." USENIX OSDI. Vol. 99. No. 1999. 1999.
Practical Byzantine Fault Tolerance
• Why Practical?
• Considers an asynchronous environment (Gives priority
to Safety over Liveness)
• Utilizes digital signature to validate the identity of the
senders
• Low overhead
Practical Byzantine Fault Tolerance
• Incorporated in a large number of distributed applications
including blockchain
• Tendermint
• Hyperledger Fabric

• Uses cryptographic techniques to make the messages


tamper-proof
PBFT Overview
• Based on State Machine Replication
• Considers 3F + 1 replicas where F can be the maximum
number of faulty replicas
PBFT Overview
• The replicas move through a succession of configurations,
known as views
• One replica in a view is considered as the primary (works like a
leader), and others are considered backups
• The primary proposes a value (similar to the Proposers in
Paxos), and the backups accept the value (similar to the Paxos
Acceptors)
• When the primary is detected as faulty, the view is changed –
PBFT elects a new primary and a new view is initiated
• Every view is identified by a unique integer v
• Only the messages from the current view is accepted
PBFT Overview
• The replicas move through a succession of configurations,
known as views
• One replica in a view is considered as the primary (works like a
leader), and others are considered backups
• The primary proposes a value (similar to the Proposers in
Paxos), and the backups accept the value (similar to the Paxos
Acceptors)
• When the primary is detected as faulty, the view is changed –
PBFT elects a new primary and a new view is initiated
• Every view is identified by a unique integer v
• Only the messages from the current view is accepted
PBFT – Broad Idea
Request
Client Primary

Backups
PBFT – Broad Idea
Request
Client Primary

Request
Request Request
Request Request

Backups
PBFT – Broad Idea
Request Client waits for 2F+1 replies,
Client Primary where F is the maximum
number of faulty nodes

Reply
Reply
Reply

Backups
PBFT – The Algorithm
Request
C

R1

R2

R3

• The protocol starts by the client sending a Request message to the


primary
PBFT – The Algorithm
Request
C

R1

R2

R3

• The primary collects all the Request messages from different


clients and order them based on certain pre-defined logic
•v is the current view number, d is the
PBFT – The Algorithm message digest, m is the message
•β_p is the private key of the primary​
C
Pre-prepare
P

R1

R2

R3
• Primary assigns a sequence number n to the Request (or a set of
Requests) and multicast a message <<PRE-PREPARE, v, n, d>β_p, m> to
all the backups
PBFT – The Algorithm
C
Pre-prepare
P

R1

R2

R3
• Pre-prepare works as a proof that the Request was assigned a
sequence number n for the view v
Accepting Pre-Prepare
• A backup accepts the Pre-prepare message, if
• The signature is correct and d is the digest of the
message m
• The backup is in view v
• It has not received a different Pre-Prepare message with
sequence n and view v with a different message digest
• The sequence number is within a threshold (the message
is not too old – prevents a reply attack)
PBFT – The Algorithm
C

P
Prepare
R1

R2

R3
• The correct backups send a Prepare message to all other backups
including the primary – works as proof that the backups agree on the
message with the sequence number n under view v
PBFT – The Algorithm
C

P
Prepare
R1

R2

R3
• Message format for backup k : <PREPARE, v, n, d, k>β_k
Accepting Prepare Message
• Primary and backups accepts the Prepare message, if
• The signatures are correct
• View number is equal to the current view
• Sequence number is within a threshold (note that
messages may be received out of order – so a backup
may receive the Prepare message before the
corresponding Pre-prepare message – so it needs to keep
track of all the messages received)
Three Phase Commit
• Pre-prepare and Prepare ensure that non-faulty replicas
guarantee on a total order for the requests within a view
Three Phase Commit
• Pre-prepare and Prepare ensure that non-faulty replicas
guarantee on a total order for the requests within a view

• Assumptions for Commit:


• Primary is non-faulty
• You may have a maximum of f faults including Crash + Network
+ Byzantine
Three Phase Commit
• A message is committed if
• 2f Prepare from different backups matches with the
corresponding Pre-prepare
• You have total 2f + 1 votes (one from the primary that you
already have!) from the non-faulty replicas
Three Phase Commit
• A message is committed if
• 2f Prepare from different backups matches with the
corresponding Pre-prepare
• You have total 2f + 1 votes (one from the primary that you
already have!) from the non-faulty replicas

• Note that all 2f + 1 votes may not be same


• You have votes from Byzantine faulty replicas as well
Quorum – Why 2f+1 Votes?
• Quorum: Minimum number of votes a distributed transaction
needs to obtained to get committed
• Proposed by David Gifford in 1979 (Gifford, David K.
(1979). Weighted voting for replicated data. SOSP '79)
• Widely used in Commit protocols and Replica management
Quorum – Why 2f+1 Votes?
• Byzantine Dissemination Quorum:
• Intersection: Any two quorums have at least one correct
replica in common
• Availability: There is always a quorum available with no
faulty replicas
Quorum – Why 2f+1 Votes?
• Byzantine Dissemination Quorum:
• Intersection: Any two quorums have at least one correct
replica in common
• Availability: There is always a quorum available with no
faulty replicas

• PBFT uses Byzantine Dissemination Quorum with


2f + 1 replicas
Quorum in PBFT
• You have f number of faulty nodes – you need at least 3f + 1 replicas
to reach consensus
• But you do not know whether those are Crash faults, Network
faults, or Byzantine Faults
Quorum in PBFT
• Case 1: All f are Crash or Network faulty – You'll not receive
messages from them!
• You'll receive 2f + 1 Prepare messages from non-faulty nodes
• All these 2f + 1 are non-faulty votes – you can reach to an
agreement
Quorum in PBFT
• Case 2: All f are Byzantine faulty – they send messages!
• You may receive at most 3f + 1 Prepare messages (votes) -- f are
from Byzantine nodes
• Sufficient to wait till 2f + 1 Prepare messages – even if f are
faulty, you still have f+1 non-faulty votes
• You cannot wait for f+1, the first f might be all faulty
Quorum in PBFT
• Case 2: All fRemember, you–are
are Byzantine faulty they on
sendan
messages!
• You may receive at most 3f + 1 Prepare messages (votes) -- f are
asynchronous
from Byzantine nodes channel – messages get
delayedto and
• Sufficient can
wait till 2f +be received
1 Prepare out– even
messages of if f are
faulty, you still have f+1 non-faulty votes
order
• You cannot wait for f+1, the first f might be all faulty

Wait untill you receive 2f + 1 Prepare messages –


once you received 2f + 1 votes, you can safely take a
decision based on majority voting
PBFT – The Algorithm
C
Commit
P

R1

R2

R3
• Message format for replica k : <COMMIT, v, n, d, k>β_k
PBFT – The Algorithm
Reply
C

R1

R2

R3
• The protocol is committed for a replica when
• It has sent the Commit message
• It has received 2f Commit messages from other replicas
Conclusion
• PBFT works with 3f+1 replicas over 2f+1 quorum

• Next, we'll see the safety and liveness properties of PBFT


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 32: Safety and Liveness of PBFT


• Safety and Liveness of PBFT

• PBFT View Change


• Weak Synchrony assumptions

• The view change protocol


PBFT – The Algorithm
Pre-Prepare Prepare Commit Reply
C

R1

R2

R3
Safety in PBFT
• Unlike multiple Paxos proposers, PBFT works with a single
Primary
• Ping-pong does not arise from the proposals from
multiple replicas
• However, a replica needs to wait for 2f + 1 votes (Prepare
and Commit messages)
Safety in PBFT
• PBFT is safe with 2f+1 quorum
• The leader can always have the majority votes to support
its proposal

• The leader can reach to the consensus even when it does not
receive messages from some of the replicas due to
asynchronous nature of the channel
Liveness in PBFT
• However, a primary may fail – the liveness gets hampered as
the protocol cannot progress any further
• Primary failure cannot be handled in a pure
asynchronous system – you do not know whether it is a
message delay from the primary, or a primary failure
Weak Synchrony Assumption
• Weak Synchrony:
• (1) Both sender and the receiver is correct,
• (2) Sender keeps retransmitting the messages until it is
received,
• (3) There is an asymptotic upper bound on the message
transmission delay
The View Change Protocol
• What if the primary is faulty ?
• Non-faulty replicas detect the fault
• Replicas together start view change operation

• View-change protocol provides eventual liveness --


Allows the system to make progress when primary fails
The View Change Protocol
• If the primary fails, backups will not receive any message or
will receive faulty messages from the primary

• View changes are triggered by timeouts (weak synchrony


assumption)
• Prevent backups from waiting indefinitely for requests to
execute
The View Change Protocol
• Backup starts a timer when it receives a request, and the
timer is not already running
• The timer is stopped when the request is executed
• Restarts when some new request comes

• If the timer expires at view v, backup starts a View Change to


move to the view v + 1
The View Change Protocol
R1
View-Change
p(v)

R1
P(v+1)

R3

R4
Multicast the View Change message <VIEW-CHANGE, v+1, n, C, P, k>β_k
• n is the sequence number of last stable checkpoint s known to k
• C is a set of 2f + 1 valid checkpoint messages corresponding to s
• P is a set containing a set Pm for each request m that prepared
at k with a sequence number higher than n
The View Change Protocol
R1
View-Change
p(v)

R1
P(v+1)

R3

R4
• The new view is initiated after receiving 2f + 1 View Change messages
• Next primary selection
• Round Robin (Hyperledger Sawtooth)
• Leader election (Hyperledger Fabric)
The View Change Protocol
View-Change View-Change ACK New-View
R1
p(v)

R1
P(v+1)

R3

R4
• Replicas send a View Change ACK – quorum is formed on these
messages
• New View message to initiate a new view
Conclusion
• PBFT is safe under 2f+1 quorum over an asynchronous
environment

• Liveness if affected when the primary is faulty

• View change to elect a new primary when the primary is


detected as faulty
• Weak synchrony assumption
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 33: Enterprise Blockchains


• Enterprise blockchains
• Enterprise blockchain applications

• The Hyperledger greenhouse

• Hyperldger Fabric
Blockchain – The Application Space

Total Blockchain Opportunity

Total Bitcoin Opportunity

Blockchain is a Blockchain can reimagine the Enterprises are


design pattern made world's most fundamental adopting Blockchain
famous by its use in business interactions and to a very broad range
Bitcoin. But its uses open the door to invent new of business
go far beyond. styles of digital interactions. applications
Asset Transfer in a Business Network
Party D’s Party A’s Bank’s
records records records

Auditor’s
records

Party C’s Party B’s


records records

… Inefficient, expensive, vulnerable


Asset Transfer in a Business Network

… Consensus, provenance, immutability, finality


Benefits of Blockchain for Business
Append-only distributed
Shared Ensuring appropriate
system of record shared Security visibility; transactions are
across business network Ledger secure, authenticated &
verifiable

Business terms embedded Smart All parties agree to network


in transaction database & Consensus verified transaction
executed with transactions Contracts

Enables
ReducesRisk NewBusiness
ReducesTime Removes Cost
Models

Transaction time Overheads and IoT Integration


Tampering, fraud
from days to near cost of into supply
& cyber crime chain
instantaneous intermediaries
Degree of Centralization

Figure source: “Distributed Ledger Technology: Beyond Blockchain”, A report by UK Govt Chief Scientific Adviser
Permissionless vs Permissioned Blockchains
Permissionless Permissioned
Access Open read/write access to Permissioned read/write access to
database database
Scale Scale to a large number of Scale in terms of transaction
nodes, but not in transaction throughput, but not to a large
throughput number of nodes
Consensus Proof of work/ proof of stake Closed membership consensus
algorithms
Identity Anonymous/pseudonymous Identities of nodes are known, but
transaction identities can be
private/anonymous/pseudonymous
Asset Native assets Any asset/data/state
The Linux Foundation Hyperledger Project
A collaborative effort created to advance blockchain technology by identifying and addressing important
features for a cross-industry open standard for distributed ledgers that can transform the way business
transactions are conducted globally.

https://www.hyperledger.org/
Hyperledger Members
https://www.hyperledger.org/about/members
Premier General (Partial list)

Associates (Partial list)


Hyperledger Fabric – Distributed Ledger Platform
https://www.hyperledger.org/use/fabric

•An implementation of blockchain


technology that is a foundation for
developing blockchain applications

•Emphasis on ledger, smart contracts,


consensus, confidentiality, resiliency and
scalability.

•V1.0 released July 2017


•159 developers from 27
organizations
Conclusion
• Enterprise blockchains have a wide spectrum of applications
and use cases that can be developed over permissioned
models

• We'll next explore Hyperledger Fabric to develop our first DLT


application
Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 34: Hyperledger Fabric 1


• Hyperledger Foundation

• Hyperledger Fabric Introduction

• Fabric Installation
• Hyperledger

• Fabric

• Permissioned Network
Hyperledger Foundation
https://www.hyperledger.org/
• Open source community - focused on
enterprise-grade blockchain deployments.

• Home for various distributed ledger frameworks


including: Hyperledger Fabric, Sawtooth, Indy,
etc.
Hyperledger Foundation
https://www.hyperledger.org/
• Open source community - focused on
enterprise-grade blockchain deployments.

• Home for various distributed ledger frameworks


including: Hyperledger Fabric, Sawtooth, Indy,
etc.

• Different companies / organizations want to collaborate


• Closed group: members know each other
• Do not fully trust each other
• Distributed shared ledger – based on permissioned consensus
Hyperledger Foundation Projects

Tooling to serve as Tooling to invoke, Permissioned Enterprise


operational deploy or query blocks Blockchain
dashboard for
Blockchains

Permissioned, EVM Identity Management


Based, BFT Consensus
Hyperledger Fabric

• Open source, enterprise-grade


• Permissioned DLT platform

• Modular blockchain framework


• Designed for developing blockchain-based products, solutions, and
applications using plug-and-play components that are aimed for use
within private enterprises.

• Pluggable Components: Including consensus and membership services.

• Smart contracts in general purpose languages such as Java, Go and Node.js.

https://hyperledger-fabric.readthedocs.io/
Install Hyperledger Fabric - Prerequisites
Install Prerequisites

• Git
• https://git-scm.com/downloads
• cURL
• https://curl.se/download.html
• Docker (Docker version 17.06.2-ce or greater is required)
• https://docs.docker.com/engine/install/
• Go
• https://golang.org/doc/install
• Docker Compose (Docker Compose version 1.14.0 or greater installed)
• https://docs.docker.com/compose/install/

https://hyperledger-fabric.readthedocs.io/en/release-2.2/prereqs.html
Install Hyperledger Fabric - Prerequisites
Install Prerequisites
• Git
• sudo apt install git

• cURL
• sudo apt install curl

• Go
• wget https://golang.org/dl/go1.17.3.linux-amd64.tar.gz
• sudo rm -rf /usr/local/go
• sudo tar -C /usr/local -xzvf go1.17.3.linux-amd64.tar.gz

https://hyperledger-fabric.readthedocs.io/en/release-2.2/prereqs.html
Install Hyperledger Fabric - Prerequisites
Install Prerequisites
Docker
sudo apt install ca-certificates gnupg lsb-release

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --


dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-


by=/usr/share/keyrings/docker-archive-keyring.gpg]
https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo
tee /etc/apt/sources.list.d/docker.list > /dev/null

sudo apt update


sudo apt install docker-ce docker-ce-cli containerd.io

sudo groupadd docker


sudo usermod -aG docker $USER
https://hyperledger-fabric.readthedocs.io/en/release-2.2/prereqs.html
Install Hyperledger Fabric - Prerequisites
Install Prerequisites

Docker Compose

sudo curl -L
"https://github.com/docker/compose/releases/download/1.29.2/docker-
compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose

https://hyperledger-fabric.readthedocs.io/en/release-2.2/prereqs.html
Install Hyperledger Fabric 2.2
Install Samples, Binaries, and Docker images

Determine a location on your machine where you want to place the fabric-samples repository and enter that directory
in a terminal window.

mkdir fabric
cd fabric
curl -sSL https://bit.ly/2ysbOFE | bash -s -- <fabric_version> <fabric-ca_version>

Example:
curl -sSL https://bit.ly/2ysbOFE | bash -s -- 2.2.4 1.5.2

export PATH=<path to download location>/bin:$PATH

https://hyperledger-fabric.readthedocs.io/en/release-2.2/prereqs.html
Conclusion

• Hyperledger Foundation

• Enterprise blockchain – Fabric

• Installation of Hyperledger Fabric


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 35: Hyperledger Fabric 2


• Fabric Architecture

• Fabric Test Network

• Sample Chaincode

• Invoke and Query Chaincode


• Fabric Test Network

• Chaincode Transactions
Fabric Architecture
A

Client Fabric Chaincode


Application SDK Peer
B
!
Events
Local

Organization O1 Channels MSP

0 1 2 3
O2
Ledger
Blockchain WorldState O3
Orderer
Fabric Test Network
• Real network consists of multiple organizations. Each maintain
their own set of:
• Peers
• Client Applications
• Optionally Orderers
• MSP

• Test Network:
• All organizations in a single system
• Development and testing purposes
• 2 Orgs, each having 1 peer and optionally one CA
• 1 orderer
• All components are containerized
Start Test Network
Navigate to the directory where you have installed fabric samples.
cd fabric-samples
cd test-network
./network.sh up
Monitor Containers
docker ps

• 2 fabric-peer containers, - 1 per organization.


• 1 fabric-orderer container
• 1 fabric-tools container
Create Channel
./network.sh createChannel

• Creates a channel with name "mychannel"

./network.sh createChannel -c <channel name>


Install Chaincode
./network.sh deployCC -ccn basic -ccp ../asset-transfer-basic/chaincode-go -ccl go
Invoke Chaincode – Configure Peer
export FABRIC_CFG_PATH=$PWD/../config/

# Set environment variables for Org1

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"

export
CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/organizations/peerOrganizations/org1.exa
mple.com/peers/peer0.org1.example.com/tls/ca.crt

export
CORE_PEER_MSPCONFIGPATH=${PWD}/organizations/peerOrganizations/org1.exampl
e.com/users/[email protected]/msp

export CORE_PEER_ADDRESS=localhost:7051
Invoke Chaincode
peer chaincode invoke -o localhost:7050 \
--ordererTLSHostnameOverride orderer.example.com \
--tls --cafile
${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp
/tlscacerts/tlsca.example.com-cert.pem \
-C mychannel \
-n basic \
--peerAddresses localhost:7051 \
--tlsRootCertFiles
${PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/t
ls/ca.crt \
--peerAddresses localhost:9051 \
--tlsRootCertFiles
${PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/t
ls/ca.crt -c '{"function":"InitLedger","Args":[]}'
Invoke Chaincode
Query Chaincode
peer chaincode query -C mychannel -n basic -c '{"Args":["GetAllAssets"]}'
Conclusion

• Fabric Test Network

• Query and Invoke Transactions


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 36: Hyperledger Fabric 3


• Hyperledger Fabric Chaincode

• Fabric Transaction Flow

• Writing your own Chaincode


• Fabric

• Chaincode

• Fabric Transactions
Fabric Smart Contracts
• Defines common data, rules and processes for businesses to transact
through the ledger.
• Smart contracts are packaged as chaincodes.

https://hyperledger-fabric.readthedocs.io/en/release-2.2/smartcontract/smartcontract.html
Fabric Transaction Flow

https://hyperledger-fabric.readthedocs.io/en/release-2.2/txflow.html
Writing Fabric Chaincode
• Written in Go, Node.js, or Java.

• Runs in a separate process from the peer.


• separate container

• fabric-contract-api of Fabric SDK


• contract interface, a high level API for implementing Chaincodes

• Go: https://pkg.go.dev/github.com/hyperledger/fabric-contract-api-go/contractapi
• Node.js: https://hyperledger.github.io/fabric-chaincode-node/release-2.2/api/
• Java: https://hyperledger.github.io/fabric-chaincode-java/release-
2.2/api/org/hyperledger/fabric/contract/package-summary.html
Define SmartContract
package main

import (
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

// SmartContract - provides functions for storing and


// retrieving keys and values from the world state
//
type SmartContract struct {
contractapi.Contract
}
InitLedger
// InitLedger (optional in recent versions of fabric)
func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
err := ctx.GetStub().PutState("testkey", []byte("testval"))

if err != nil {
return fmt.Errorf("Failed to put to world state. %s", err.Error())
}

return nil
}
GetState and PutState
// CreateKey
func (s *SmartContract) CreateKey(ctx contractapi.TransactionContextInterface, key string, val string) error
{
return ctx.GetStub().PutState(key, []byte(val))
}

// QueryKey
func (s *SmartContract) QueryKey(ctx contractapi.TransactionContextInterface, key string) (string,error) {
val, err := ctx.GetStub().GetState(key)

if err != nil {
return "", fmt.Errorf("Failed to get from world state. %s", err.Error())
}

return string(val), nil


}
Start Chaincode
func main(){
chaincode, err := contractapi.NewChaincode(new(SmartContract))

if err != nil {
fmt.Printf("Error creating chaincode: %s", err.Error())
return
}

err = chaincode.Start();

if err != nil {
fmt.Printf("Error starting chaincode: %s", err.Error())
}

}
Conclusion

• Fabric Chaincodes in general purpose programming


languages.

• Key-Value pairs in World State

• Any business logic


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 37: Hyperledger Fabric 4


• Hyperledger Fabric Application

• Fabric CAs

• Writing your own DAPP with Fabric


• Fabric Application

• Fabric CA

• DAPP
Fabric Application
A

Client Fabric Chaincode


Application SDK Peer
B
!
Events
Local

Organization O1 Channels MSP

0 1 2 3
O2
Ledger
Blockchain WorldState O3
Orderer
Fabric Application

https://hyperledger-fabric.readthedocs.io/en/release-2.2/write_first_app.html
Prerequisites

• Fabric client applications can be developed in:


• Node.js
• Java
• Go
• Python

https://hyperledger-fabric.readthedocs.io/en/release-2.2/getting_started.html#hyperledger-fabric-application-sdks
Imports
const FabricCAServices = require('fabric-ca-client')
const {Wallets, Gateway} = require('fabric-network')

const fs = require('fs')
const path = require('path')

async function main(){


….
}

main()

https://hyperledger-fabric.readthedocs.io/en/release-2.2/getting_started.html#hyperledger-fabric-application-sdks
Connection Profile and CA
// Org1 connection profile
const ccpPath = path.resolve('../organizations/peerOrganizations/org1.example.com/connection-org1.json')
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'))

// Org1 Ca
const caInfo = ccp.certificateAuthorities['ca.org1.example.com']
const caTLSCACerts = caInfo.tlsCACerts.pem
const ca = new FabricCAServices(caInfo.url, { trustedRoots: caTLSCACerts, verify: false }, caInfo.caName)
Connection Profile and CA
// Org1 connection profile
const ccpPath = path.resolve('../organizations/peerOrganizations/org1.example.com/connection-org1.json')
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'))

// Org1 Ca
const caInfo = ccp.certificateAuthorities['ca.org1.example.com']
const caTLSCACerts = caInfo.tlsCACerts.pem
const ca = new FabricCAServices(caInfo.url, { trustedRoots: caTLSCACerts, verify: false }, caInfo.caName)
Configure CA admin
// Get admin identity

const enrollment = await ca.enroll({ enrollmentID: 'admin', enrollmentSecret: 'adminpw' });

const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};

await wallet.put("admin", x509Identity)

console.log("Admin enrolled and saved into wallet successfully")

adminIdentity = await wallet.get("admin")


Register User
// Register user for this app
const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity, 'admin');

const secret = await ca.register({affiliation: 'org1.department1', enrollmentID: 'appUser', role: 'client'},


adminUser);

const enrollment = await ca.enroll({enrollmentID: 'appUser',enrollmentSecret: secret});

const x509Identity = {credentials: {certificate: enrollment.certificate,privateKey: enrollment.key.toBytes()},


mspId: 'Org1MSP',
type: 'X.509',
};

await wallet.put('appUser', x509Identity)


console.log("Enrolled appUser and saved to wallet")

userIdentity = await wallet.get("appUser")


Configure Channel and Chaincode
// Connect to gateway
const gateway = new Gateway();

await gateway.connect(ccp, {wallet, identity:'appUser', discovery: {enabled: true, asLocalhost: true}})

// connect to channel
const network = await gateway.getNetwork('mychannel')

// select the contract


const contract = network.getContract("keyvaluechaincode")
Query and Invoke Chaincodes
// Query and Invoke transactions

var result = await contract.evaluateTransaction("QueryKey", "nptel")


console.log("First query:", result.toString())

await contract.submitTransaction("CreateKey", "nptel", "a new value")

var result = await contract.evaluateTransaction("QueryKey", "nptel")


console.log("Second query:", result.toString())

// disconnect
await gateway.disconnect()
Conclusion

• Fabric Client SDK

• Fabric Identities and CA

• Query and Invoke Chaincodes


Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 38: Consensus Scalability


• Blockchain Scalability
• PoW vs PBFT

• Scalability

• Consensus Finality
Blockchain Consensus Protocols

• Permissionless Blockchain
• Proof of Work (PoW)
• Proof of State (PoS)
• Proof of Burn (PoB)
• Proof of Elapsed Time (PoET)
Blockchain Consensus Protocols

• Permissioned Blockchain

• Byzantine Agreement
• PBFT
PoW vs PBFT
• PoW
• Open environment, works over a large number of nodes
• Scalable in terms of number of nodes
• Transaction throughput is low

• PBFT
• Closed, not scalable in terms of number of nodes
• High transaction throughput
PoW Scalability
• Two magic numbers in PoW
• Block frequency - 10 minutes
• Block size - 1 MB / 8MB

• For Bitcoin:
• Let's assume, block size = 1 MB.
• Average transaction size = 380.04 bytes
• Number of transactions per block = 1048576/380.04
= 2,759.12
PoW Scalability
• Two magic numbers in PoW
• Block frequency - 10 minutes
• Block size - 1 MB / 8MB

• For Bitcoin:
• With 10 minutes (600 seconds) as block mining time,
• 2759.12 transactions in 600 seconds
• 4.6 transactions per second
PoW Scalability
• Two magic numbers in PoW
• Block frequency - 10 minutes
• Block size - 1 MB / 8MB

• Bitcoin Transaction throughput – 4.6 transactions per second


• Visa supports around 1736 transactions per second
Tuning Bitcoin PoW Scalability

https://towardsdatascience.com/the-blockchain-scalability-problem-the-race-for-
visa-like-transaction-speed-5cce48f9d44
Performance vs Scalability Vukolić, Marko. "The
quest for scalable
blockchain fabric: Proof-
of-work vs. BFT
replication." International
Workshop on Open
Problems in Network
Security. Springer, Cham,
2015.
PoW vs PBFT – Consensus Finality
• If a correct node p appends block b to its copy of blockchain
before appending block b’, then no correct node q appends block
b’ before b to its copy of the blockchain (Vukolic, 2015)

• PoW is a randomized protocol - does not ensure consensus


finality
• Remember the forks in Bitcoin blockchain

• BFT protocols ensure total ordering of transactions


• Ensures consensus finality
Vukolić, Marko. "The
PoW Consensus vs BFT Consensus quest for scalable
blockchain fabric: Proof-
of-work vs. BFT
replication." International
Workshop on Open
Problems in Network
Security. Springer, Cham,
2015.
Conclusion
• Scalability is a major issue in Blockchain consensus

• In the next lecture, we'll discuss different scalable blockchain


protocols
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 39: Bitcoin-NG


• Issues with Bitcoin – Revisit

• Bitcoin-NG
• Transaction Serializability

• Key-blocks and Microblocks


Performance vs Scalability Vukolić, Marko. "The
quest for scalable
blockchain fabric: Proof-
of-work vs. BFT
replication." International
Workshop on Open
Problems in Network
Security. Springer, Cham,
2015.
Towards a Scalable Consensus

Eyal, I., Gencer, A. E., Sirer, E. G., & Van Renesse, R.


(2016, March). Bitcoin-NG: A Scalable Blockchain Protocol.
in NSDI 2016
Issues with Nakamoto Consensus
• Transaction scalability
• Block frequency of 10 minutes and block size of 1 MB
during mining reduces the transactions supported per
second
Issues with Nakamoto Consensus
• Transaction scalability
• Block frequency of 10 minutes and block size of 1 MB
during mining reduces the transactions supported per
second

• Issues with Forks


• Prevents consensus finality
• Makes the system unfair - a miner with poor
connectivity has always in a disadvantageous position
Bitcoin-NG: Decouple Leader Election
• Bitcoin - think of the winning miner as the leader - the
leader serializes the transactions and include a new block in
the blockchain
Bitcoin-NG: Decouple Leader Election
• Bitcoin - think of the winning miner as the leader - the
leader serializes the transactions and include a new block in
the blockchain

• Decouple Bitcoin’s blockchain operations into two planes


• Leader election: Use PoW to randomly select a leader
(an infrequent operation)
• Transaction Serialization: The leader serializes the
transaction until a new leader is elected
Bitcoin vs Bitcoin-NG
Bitcoin vs Bitcoin-NG

Image Source: http://hackingdistributed.com/2015/10/14/bitcoin-ng/


Bitcoin-NG: Key Blocks
• Key blocks are used to choose a leader (similar to Bitcoin)

• A key block contains


• The reference to the previous block
• The current Unix time
• A coinbase transaction to pay of the reward
• A target hash value
• A nonce field
Key Blocks
• Key blocks are generated based on regular Bitcoin mining
procedure
• Find out the nonce such that the block hash is less than
the target value

• Key blocks are generated infrequently - the intervals


between two key blocks is exponentially distributed
Bitcoin-NG: Microblocks
• Once a node generates a key block, it becomes the leader and
generates further microblocks
• Microblocks are generates at a set rate smaller than a
predefined maximum
• The rate is much higher than the key block generation rate
Bitcoin-NG: Microblocks
• A microblock contains
• Ledger entries
• Header
• Reference to the previous block
• The current Unix time
• A cryptographic hash of the ledger entries (Markle root)
• A cryptographic signature of the header (signature of the key
block miner)
Microblock Fork
• When a miner generates a key block, he may not have heard
of all microblocks generated by the previous leader
• Common if microblock generation is frequent
• May result in microblock fork
Microblock Fork
• When a miner generates a key block, he may not have heard
of all microblocks generated by the previous leader
• Common if microblock generation is frequent
• May result in microblock fork

• A node may hear a forked microblock but not new key block
• This can be prevented by ensuring the reception of the key
block
• When a node sees a microblock, it waits for propagation time
of the network to make sure it is not pruned by a new key
block
Bitcoin-NG Performance
Bitcoin-NG Performance
Conclusion
• A major source of latency in Bitcoin is that every block needs
to be mined by different miners

• Bitcoin-NG decouples leader election from transaction


serialization
• Key blocks and Microblocks
Performance vs Scalability - Revisiting
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 40: Collective Signing (CoSi)


• Collective Signing

• Schnorr Multisignature

• PBFT as Collective Signing


• CoSi

• Multisignature
Collective Signing
• Method to protect “authorities and their clients” from
undetected misuse or exploits

• A scalable witness cosigning protocol ensuring that every


authoritative statement is validated and publicly logged by a
diverse group of witnesses before any client accepts it

Syta, Ewa, et al. "Keeping authorities "honest or bust" with


decentralized witness cosigning" 2016 IEEE Symposium on Security
and Privacy (SP), 2016.
Collective Signing

• A statement S collectively signed by W witnesses assures


clients that S has been seen, and not immediately found
erroneous, by those W observers.
CoSi Architecture • The leader organizes the witnesses
in a tree structure – a scalable way
of aggregating signatures coming
from the children

• Three rounds of PBFT (pre-


prepare, prepare and commit) can
be simulated using two rounds
of CoSi protocol
Schnorr Multisignature
• The basic CoSi protocol uses Schnorr multisignatures, that
rely on a group G of prime order
• Discrete logarithmic problem is believed to be hard
Schnorr Multisignature
Schnorr Multisignature
Schnorr Multisignature
Schnorr Multisignature
CoSi Protocol
CoSi Protocol
CoSi Protocol
• One CoSi round to implement PBFT’s pre-prepare and
prepare phases

• Second CoSi round to implement PBFT’s commit phase

• Other multisignature methods are available


• Boneh-Lynn-Shacham (BLS) Cryptography – uses
Bilinear Pairing
Conclusion
• CoSi can be used to sign a message by multiple authorities
collectively
• Verification is easy – from the collective public key

• PBFT can be emulated using two rounds of CoSi

• Next, we'll see how CoSi can be used to design a scalable


blockchain consensus
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 41: ByzCoin


• Byzcoin: Combining PoW with PBFT

• Scalability: How far can we achieve?


• Byzcoin

• Open consensus group

• The blockchain performance triangle


Revisiting the Requirements for Blockchain Consensus
• Byzantine fault tolerant – the system should work even in the
presence of malicious users while operating across multiple
administrative domains

• Should provide strong consistency guarantee across replicas

• Should scale well to increasing workloads in terms of


transactions processed per unit time

• Should scale well to increasing network size


Bitcoin-NG: The issue with a Faulty Key Block
• Problem with Bitcoin-NG: A faulty key block is verified only
after end of the round
• A faulty miner can introduce several correct microblocks
following a faulty microblock in the system
• certainly an overhead for the application - a fork
alleviates the problem further
Bitcoin-NG: The issue with a Faulty Key Block
• Problem with Bitcoin-NG: A faulty key block is verified only
after end of the round
• A faulty miner can introduce several correct microblocks
Solve this
following problem
a faulty by a in
microblock set
theofsystem
PBFT verifiers
- •who will verify
certainly a block
an overhead for and then only- athe
the application fork
block is added
alleviates the in the Blockchain
problem further
Issues with PBFT
• PBFT requires a static consensus group (because of message
passing)

• Scalability (in terms of nodes) is a problem for PBFT


• O(n2) communication complexity
• O(n) verification complexity
• Absence of third-party verifiable proofs (PBFT uses MAC - need
to share the keys among the miners)

• Sybil attack - create multiple pseudonymous identities to


subvert the 3f+1 requirements of PBFT
Open the Consensus Group
• Use PoW based system to give a proof of membership of a
miner as a part of the trustees

• Maintains a “balance of power” within the BFT consensus


group
• Use a fixed-size sliding window
• Each time a miner finds a new block, it receives
a consensus group share
• The share proves the miner’s membership in the
trustee group
Kogias, E. K., Jovanovic, P., Gailly, N., Khoffi, I., Gasser, L., & Ford,
B. (2016, August). Enhancing bitcoin security and performance
with strong consistency via collective signing. In 25th USENIX
Security Symposium 2016
Merging BFT Consensus with PoW
• Validate each microblock by a set of witness consigners
Merging BFT Consensus with PoW
• Validate each microblock by a set of witness consigners

Use CoSi
Merging BFT Consensus with PoW

• Validate each microblock by a set of witness consigners

• How do we select the witness cosigners?


Selecting a Consensus Group
Improving Efficiency of BFT Consensus
• Improve O(n) communication complexity
• Use tree-based multicast protocol - share information with
O(log n)

• Improve O(n) complexity for verification


• Use Schnorr multi-signatures
• Verification can be done in O(1) through signature
aggregation

• Multi-signatures + Communication trees = CoSi


ByzCoin Performance
ByzCoin Summary
• ByzCoin solves the problem of introducing a faulty
microblocks in Bitcoin-NG

• Combine PoW with PBFT


• Open the consensus group with the help of CoSi
ByzCoin Summary
• ByzCoin solves the problem of introducing a faulty
microblocks in Bitcoin-NG

• Combine PoW with PBFT


• Open the consensus group with the help of CoSi

• How can we achieve Internet-scale scalability?


• Both performance and network size
Bitcoin Recap
• Key Idea:
• Consensus through proof-of-work (PoW)
• Communication:
• Gossip protocol
• Key Assumption:
• Honest majority of mining computation power
Bitcoin Limitations
• Resource wastage:
• high computational, electricity cost
• Concentration of power
• only ~5 mining pools control the entire system
• Vulnerable
• easy to track miners, concentrated to a few mining
pools -
https://www.blockchain.com/btc/blocks?page=1
Bitcoin Limitations

• Scalability
• number of users not clear (1M, 10M, 100M??),
high latency(~10minutes)
• Ambiguity
• fork in blockchain
Conclusion: The Blockchain Performance Triangle

Is it ever possible to
achieve all three
simultaneously?
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 42: Algorand


• Algorand
• Cryptographic Sortition

• BA*
The Blockchain Performance Triangle

Is it ever possible to
achieve all three
simultaneously?
Algorand: Scaling Byzantine Agreements for
Cryptocurrencies

Gilad, Y., Hemo, R., Micali, S., Vlachos, G., & Zeldovich, N.
(2017, October). Algorand: Scaling byzantine agreements for
cryptocurrencies. In Proceedings of the 26th Symposium on
Operating Systems Principles (pp. 51-68). ACM.
Algorand: Overview

• Key Idea:
• Consensus through Byzantine Agreement Protocol
• Communication:
• Gossip protocol
• Key Assumption:
• Honest majority of money
Algorand: Technical Advancement
• Trivial computation
• simple operation like add, count
• True decentralization
• no concentration of mining pool power, all equal miners
and users
• Finality of payment
• fork with very low probability, block appears, and
the payment is fixed forever
Algorand: Technical Advancement

• Scalability
• millions of users, only network latency (~1minute)
• Security
• against bad adversary
Architecture of Algorand
• Select a random user
• prepare a block
• propagate block through gossiping

• Select random committee with small number of users (~10k)


• run Byzantine Agreement on the block
• digitally sign the result
• propagate digital signatures

• Who select the committee?


Cryptographic Sortition in Algorand
Cryptographic Sortition
• Each committee member selects himself according to per-
user weights
• Implemented using Verifiable Random Functions (VRFs)

• <hash,proof> ← VRFsk(x)
• x: input string
• (pki,ski): public/private key pair
• hash: hashlenbit-long value that is uniquely determined
by sk and x
• proof: enables to check that the hash indeed
corresponds to x
Committee Member Selection

• seed: publicly known random value


• seed published at Algorand’s round r using
VRFs with the seed of the previous round r −
1
• threshold: determines the expected number of users
selected for that role
• role: user for proposing a block/ committee member
• w: weight of a user
• W: weight of all users
• j: user gets to participate as j different “sub-users.”
Byzantine Agreement in Algorand: BA*

• Two phase:
• Two phase agreement –
• Final Consensus
• Tentative Consensus
Byzantine Agreement in Algorand: BA*

• Strong Synchrony: Most honest users (say, 95%)


can send message that will be received by most
other honest users within a known time bound
• Adversary can not control the network for long
• Ensures liveness of the protocol
Byzantine Agreement in Algorand: BA*

• Weak Synchrony: The network can be


asynchronous for long (entirely controlled by
adversary) but bounded period of time
• There must be a strong synchrony period after
a weak synchrony period
• Algorand is safe under weak synchrony
Final Consensus

• One user reaches final consensus


• Any other user that reaches final or tentative
consensus in the same round must agree on the
same block value (ensures safety)
• Confirm a transaction when the block reaches
to the final consensus
Tentative Consensus
• One user reaches tentative consensus
• Other users may have reached consensus on a different
(but correct) block
• Can be in two cases
• The network is strongly synchronous - adversary may be able
to cause BA* to reach tentative consensus on a block - BA* is
unable to confirm that the network was strongly
synchronous
• The network was weakly synchronous - BA* can form
multiple forks and reach tentative consensus on two different
blocks - users are split into groups
Coming out of Tentative Consensus
• Run BA* periodically to come out of tentative
consensus - run the next round
• Network cannot be under weak synchrony all
the times
• Cryptographic sortition ensures different
committee members at different rounds of the
BA*
BA* Overview
Conclusion
• Algorand has multiple advantages
• Bitcoin like scalability
• BFT like throughput
• No fork

• Caution: Needs a really large network


Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 43: Identity Management - I


• Basic Concepts of Identity
• Centralized Identity Management
• Introduction to Decentralized Identity Managment
• Identity
• Centralized Identity Management
• Single Sign on
• Self-Sovereign Principle
• Decentralized Identifier
What is Identity?

• People are known by their identities - drives every


business and social interaction
• Physical Identity is a collection of attributes
– Name
– Age
– Financial history
– Work history
– Address history
– Social history
– ….
Centralized Digital Identity

• Individuals do not have any control over the information


that comprises their identities
• Identity fraud - no visibility over the identity attributes
• Authentication
• Authorization
• Verification
Centralized Digital Identity

• Individuals do not have any control over the information


that comprises their identities
• Identity fraud - no visibility over the identity attributes
• Authentication
• Authorization
• Verification
Digital Identity - Single Sign On (SSO)
• Single identity for various purposes
• No need to maintain multiple identity documents
• Widely conceptualized in software industry
• One password to access multiple services
• Single identity provider (IDP) maintains the identity
• Identity consumers (services) use the IDP to
authenticate the identity holder
• During authentication, the identity is not exposed to
the services

Image Source: https://www.e-spincorp.com/global-theme-and-feature-topics/single-sign-on-sso/


SSO and Decentralization

Public Sector
Bank Services
Post Office

Identity Database
Mobile
Recordkeeping Companies for
Agency (IDP) user identity
verification

User
Decentralizing Digital Identity
• No Centralized Trusted Identity Provider / Registry
• Digital representation of physical identity
• Two major problems:
• Verifying the identity issuer
• Verifying the identity holder

Issuer - Holder Verifier


Government
Decentralizing Digital Identity
• No Centralized Trusted Identity Provider / Registry
• Digital representation of physical identity
• Two major problems:
• Verifying the identity issuer
• Verifying the identity holder

Issuer - Holder Verifier


Government
Fundamental Principles of Digital Identity Management

• Self-Sovereign Identity (Privacy Control)


• Individual should have full control and ownership of their
identity information
• Individuals can control the usage of their own identity
profile for business and social interactions (Consent -
agreement for information usage)
• Identical to how we use our physical identity
• Holder possesses the ID
• Holder chooses whom to present the ID
• Burden at individual user?
Decentralized Identifiers (DIDs)

• Provides Verifiable, Decentralized Digital identity


• Designed to be decoupled from:
• centralized registries
• identity providers
• certificate authorities
• Holder of DID can prove its ownership on the DID
without the help of any other party
• W3C Proposed Recommendation

https://www.w3.org/TR/did-core/
DID Architecture

https://www.w3.org/TR/did-core/
DID Architecture
1. Unique URI –
identifies a subject.

2. Entity (person / organization


/ etc.. ) being identified.
5. System where
DID documents
are stored.

3. Entity with permission to


change DID document. Might
be same as subject.

4. Contains information (e.g


public key of controller) about
the DID.
https://www.w3.org/TR/did-core/
• Introduced the fundamental concepts of identity management
• Centralized vs. decentralized identity management
• DID as a W3C recommendation
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 44: Identity Management - II


• How DID Works
• DID Work Flow
• Decentralized DID Registry – Use of Blockchain
• Verifiable Credentials
• DID
• DID Registry
• Hyperledger Indy
• Verifiable Credential (VC)
DID URI
• Controller controls a DID Document.
• A DID is a unique address (URI) to the location of that document.

System which supports DID Uniquely identifies a DID doc


scheme. - Eg. DID resolution. within the DID Method.

http://www.faqs.org/rfcs/rfc2396.html https://www.w3.org/TR/did-core/
DID Document
• A set of data describing the DID subject, including mechanisms such as cryptographic
public keys, that the DID subject or a DID delegate can use to authenticate itself and
prove its association with the DID.
• DID document consists of a map of entries, each entry consisting of a key/value pair.

Represent
ation-
specific
entries
include
JSON,
XML, etc
https://www.w3.org/TR/did-core/
DID Document Example (JSON)
{
"id": "did:example:123456789abcdefghi", DID for a particular DID subject
"authentication": [{
"id": "did:example:123456789abcdefghi#keys-1", Verification Method specifying
"type": "Ed25519VerificationKey2020", how the DID subject can
"controller": "did:example:123456789abcdefghi", authenticate itself.
"publicKeyMultibase":
"zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV
" Service Endpoint
}], denoting ways of
"service": [{ communicating with
"id":"did:example:123456789abcdefghi#linked-domain", the DID subject
"type": "LinkedDomains", // external (property value)
"serviceEndpoint": https://bar.example.com It tells how to reach the
}] subject. Otherwise,
} there is no meaningful
use of authentication
https://www.w3.org/TR/did-core/
Relationship between Different Components of DID

• A DID is an identifier
assigned by a DID controller
to refer to a DID subject and
resolve to a DID document
that describes the DID
subject.
• The DID document is an
artifact of DID resolution and
not a separate resource
distinct from the DID subject.
• DID document resides inside
verifiable data registry
Relationship between Different Components of DID

• Often the DID


Subject and the
DID Controller are
the same entity
DID Flow – DID Registration
Alice

1. Create DID 2. Register DID 3. Authenticate


Document DID controller
DID Doc (here based on signature)
id: did:registry1:alice, signedby(Sk) 4. Update DID Document
0. Generate Keys authentication: Pk
Public key: Pk, controller: did:registry1:alice
Secret key: Sk

Verifiable Data
Registry -
(registry1)

DID Method
Implementation
DID Flow – DID Registration
Alice

1. Create DID 2. Register DID 3. Authenticate


Document DID controller
DID Doc (here based on signature)
id: did:registry1:alice, signedby(Sk) 4. Update DID Document
0. Generate Keys
authentication: Pk
Public key: Pk, controller: did:registry1:alice
Secret key: Sk

6. Authenticate Alice based on


authentication method Pk
5. Fetch DID Document
for did:registry1:alice
Verifiable Data
Registry -
(registry1)

Bob
(wants to authenticate the subject DID Method
of did:registry1:alice) Implementation
DID Method Security
• DID Registry ideally enforces DID Method
protocols.
• Centralized DID Registry brings in risks
• Manipulating DID Documents
• Changing authentication methods
• Censoring DID Documents Verifiable Data
• Refusing to resolve certain DID Registry - (registry1)
Documents DID Method Implementation

• Lack of Transparency Centralized


Decentralized DID Registry
• Blockchain based Implementation of
Verifiable Data Registry
• DID Methods are implemented as smart
contracts.
• Smart contracts enforce how
authorization is performed to execute all
operations, including any necessary
cryptographic processes.
• Transparent Immutable Ledger allows
verifiability of DID Documents
• Any party can validate if a DID
Verifiable Data Registry
Document's creation / updation
transactions were authenticated or not.
Blockchain based DID Registry
Public permissioned ledger based
registry.
• Any party can read the ledger.
• Only selected (registered)
parties and write to the ledger. https://hyperledger-indy.readthedocs.io/en/latest/

Protocol for creating scalable DIDnetworks that


can run atop any existing permissionless
Sidetree blockchain. (e.g. Bitcoin, Ethereum, etc.)

https://identity.foundation/sidetree/spec/
Binding DID to Physical Identity
DIDs only allow a DID controller to prove its control over its DID Document.
This is useful to authenticate an entity with respect to its DID
Authenticate
based on Pk Fetch DID Doc

Public key: Pk, DID Doc - PK


Secret key: Sk

Does not reveal any


physical detail.

If some physical detail is presented, then that is only self attested by the
DID controller, and not any verified information.
Binding DID to Physical Identity
DIDs only allow a DID controller to prove its control over its DID Document.
This is useful to authenticate an entity with respect to its DID
Authenticate
based on Pk Fetch DID Doc

Public key: Pk, DID Doc - PK


Secret key: Sk

Does not reveal any


physical detail.

DID are not inherently tied to any physical identity (real world identity).
Verifiable Credentials
• Verifiable Credentials Data Model – W3C Recommendation
• Digital Representation of Credentials
• Driver's licenses - assert that capability of operating a motor
vehicle
• University degrees - assert our level of education
• Government-issued passports - permit to travel between
countries
• Identity – Birth Certificate, Citizenship Certificate, etc.
• Decouples Issuer, Holder and Verifier
• Cryptographically secure
• Privacy respecting
• Machine-verifiable https://www.w3.org/TR/vc-data-model/
• Implementation of DID
• Use of blockchain for DID registry implementation
• Verifiable credentials and their relationship with DID
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 45: Identity Management - III


• Working Principle of Verifiable Credentials (VCs)
• VC Issuer, Holder and Verifier
• Use of Decentralized Registry in VC Management
• VC Trust Model
• Combining DID and VC
• Verifiable Credential (VC)
• VC Presentation
• DID
• Hyperledger Aries
VC Data Model Components

https://www.w3.org/TR/vc-data-model/
VC Data Model Components
Holder - possesses one or more VC and
generating verifiable presentations from them.
Example holders include students, employees,
and customers.

Issuer –Asserts claims (in physical world) about


one or more subjects, creating a VC from these
claims, and transmitting the VC to a holder.
Example issuers include universities,
governments, etc.​
VC Data Model Components
Subject - Entity about which claims are made. Example
subjects include human beings, animals, and things.
Holder of a VC might not be the subject - example, a parent
(the holder) might hold the verifiable credentials of a child
(the subject), or a pet owner (the holder) might hold the
verifiable credentials of their pet (the subject).
Note: some credentials might even be self-certified by the
subject

Verifier – Receives verifiable presentation to assert claims


about subject. Example verifiers include employers, security
personnel, and websites.

Verifiable data registry - System for creation and verification


of DID, keys, and other relevant data, such as VC schemas,
revocation registries, issuer public keys, and so on.
VC Data
Claims

• A credential is a set of one or


more claims made by the
same entity.
• A claim is a statement about a • Proof is usually signature by
subject. the issuer
• Here Pat and Sam are subjects.
Information Graph of a basic Verifiable Credential

These two together


are effectively forming
the verifiable
credential for Pat
Information Graph of Verifiable Presentation

A verifiable presentation expresses


data from one or more VCs, and is
packaged in such a way that the
authorship of the data is verifiable.
Holder has to convince that indeed
the VC was issued to him.
Verifiable Credentials Flow
VC Trust Model
• Acting as issuer, holder, or verifier requires neither registration nor
approval by any authority, as the trust involved is bilateral between
parties.
• Verifier trusts the issuer to issue the VC that it received. To establish this
trust, a VC is expected to either:
• Include a proof establishing that the issuer generated
the credential (signature), or
• VC has been transmitted in a way clearly establishing that
the issuer generated VC is not tampered in transit or storage.
• All entities trust the verifiable data registry to be tamper-evident and to
be correct. Blockchain can help??
• Holder and verifier trust Issuer to issue true credentials about
the subject, and revoke them quickly when appropriate.
Combining DIDs and VCs
Step 1. Create and register DID

1. Create and register DID Document Verifiable


did:registry1:alice Data Registry

Alice

University

DID Method Implementation


Combining DIDs and VCs
Step 2. Issue Verifiable Credential

Verifiable
Data Registry
Alice 4. Alice authenticates as
2. Alice controller of
Requests Transcript VC did:registry1:alice
issued to 5. University issues Transcript VC
did:registry1:alice Holder: did:registry1:alice
Issuer: did:registry1:university

University DID Method Implementation


Combining DIDs and VCs
Step 3. Verifiable Presentation and Verification

Alice 7. Alice presents Transcript VP


6. Industry requests with signature authenticating
did:registry1:alice Verifiable
Transcript VP
Data Registry
8. Industry validates Transcript
Issued to did:registry:alice
9. Industry validates
issuer of Transcript by
validating issuer's
signature.

Industry
DID Method Implementation
Use of Blockchain for VCs
Hyperledger Aries is meant for creating, transmitting and storing
verifiable digital credentials
• Explained the complete workflow of VCs
• VC trust model
• Combining DID and VC
• Introduced Hyperledger Aries
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 46: Blockchain Interoperability - I


• Basic Concept of Asset and Data Transfer
• Asset Transfer in Permissionless Blockchain
• Cross Chain Transfer and Exchange of Asset
• Trusted Third Party
• Interoperability
• Asset Transfer
• Cross Chain Transfer
• Trusted Third Party
• Asset Exchange
Interoperability in Permissionless and Permissioned Blockchains

• Permissionless Blockchain
• Asset Transfer
• Crypto currency driven
• Permissioned Blockchain
• Data Transfer
• Consensus-driven
Public Blockchains as Isolated Silos

● Blockchain-based cryptocurrencies enable secure


and trustless currency transactions between parties.
● There are currently over 2000 different
cryptocurrencies in operation.
● Separate blockchain networks with often different
protocols and standards
● Continue to operate in complete isolation from one
another.
Cross Chain Asset Transfer

1 BTC 33 ETH

Alice
Alice

Ethereum Network
Bitcoin Network
Cross Chain Asset Transfer

1 BTC 33 ETH

Bob
Alice

Ethereum Network
Bitcoin Network

Possible between different account holders also


Cross Chain Asset Transfer

1 BTC 33 ETH

Bob
Alice

Ethereum Network
Bitcoin Network

To do the transfer, Alice must use some third party who owns ≥ 33 ETH
Cross Chain Asset Transfer - TTP

1 BTC 33 ETH
Trusted
Third Party

Bob
Alice

Bitcoin Network Ethereum Network


TTP based Asset Transfer
● There are hundreds of centralized cryptocurrency
exchanges now.
● Centralized, users transfer ownership of their funds to
the sole control of the exchange administrator.
● Fast, once the deposit is done, the transfer to the
destination network is often very fast (in milliseconds).

https://bitcointalk.org/index.php?topic=576337
https://www.reuters.com/article/us-bitcoin-mtgox-wallet-idUSBREA2K05N20140321
https://www.reuters.com/article/us-bitfinex-hacked-hongkong-idUSKCN10E0KP
TTP based Asset Transfer
● Lack of security: There has been numerous cases of
theft from centralized exchanges.
● 650,000 bitcoins lost when the MtGox exchange shut
down in 2014.
● Users of the Bitfinex exchange lost approximately
120,000 bitcoins in 2016

https://bitcointalk.org/index.php?topic=576337
https://www.reuters.com/article/us-bitcoin-mtgox-wallet-idUSBREA2K05N20140321
https://www.reuters.com/article/us-bitfinex-hacked-hongkong-idUSKCN10E0KP
Asset Exchange

Bob
33 ETH

Alice Alice
Bob

Bitcoin Network Ethereum Network

1 2

Transfer in both the networks from Alice to Bob (1) and from Bob to Alice (2) must be ATOMIC
Asset Exchange - Problems

• Without the presence of any Escrow, the funds are in


control of the sender and receiver parties.
• One party might abort the exchange after receiving
funds.
• Synchronization problems between the two networks, as
well as sender and receiver.
• Difficulty in agreement on exchange rates which may
keep on changing every second.
• Introduced the basic concepts of interoperability
• Asset transfer in permissionless blockchains
• Trusted third party based asset transfer
• Asset exchange and its challenges
• Web resources and research papers as mentioned from time
to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 47: Blockchain Interoperability - II


• Cross Chain Asset Exchange
• Atomic Swap
• Hashlock and Timelock
• Atomic Exchange
• Atomic Exchange
• Hashlock and Timelock
• Hashed Timelock Contract (HTLC)
• Two-party Atomic Exchange
Cross Chain Asset Transfer using Atomic Exchange

1 BTC
33 ETH 33 ETH
Alice Jack Jack Alice
2 3 Bob
(Sender) 1 (Exchanger) (Exchanger) (Sender) (Receiver)

Bitcoin Network Ethereum Network

1 2 Atomic Exchange 3 Transfer

Solving atomic exchange will solve most challenges of asset transfer.


Atomic Cross-chain Swaps (PODC ‘18)

Atomicity: An atomic transaction is an indivisible series of


operations, such that either all occur, or none occurs.

Atomic swap protocol guarantees


1. If all parties conform to the protocol, then all swaps take
place
2. If some parties deviate from the protocol, then no
conforming party ends up worse off
3. No coalition has an incentive to deviate from the
protocol
1 BTC

Basic Idea Alice Bob


33 ETH

1. Initialize smart contracts on both ends with the amount.


2. Add a common spending condition, such that when the
condition is met, both the parties are paid simultaneously
1 BTC
Alice Contract A (In Bitcoin Network)
Time

33 ETH Contract B (In Ethereum Network)


Bob
Some common 1 BTC
event trigger Contract A Contract B 33 ETH
Bob Alice

Atomic
Hashlock and Timelock

• Hashlock: a function that restricts the spending of funds


until a certain piece of data is publicly disclosed (as a
cryptographic proof)
• Hash of a secret pre-image is posted as a hashlock
• When the secret is revealed, the funds are released
• Timelock: a function that restricts the spending of funds
until a specific time (or block height) in the future
Hash Locks
• Hashlock is a type of encumbrance that restricts the
spending of an output until a specified secret key is
publicly revealed
• Inherent Property: Once any hashlock is opened
publicly, any other hashlock secured using the same key
can also be opened
Hash Locks
Example:
• Alice generates a secret key “I love strawberries”
• Alice computes the Cryptographic Hash of the key:
f1b81571baac90bed544d1910f79ea5c31fa4509

• Alice initiates a Hash Locked contract of 1 BTC


(some amount) which has the conditions:
If key is revealed - pay BOB with 1 BTC

• The contract also contains the Hash, which allows any


miner to verify the revealed key
Time Locks

• Timelock is a type of smart contract primitive that restricts the


spending/transfer of some currency until a specified future time
• Block height may be used as a proxy for time

Example:
• Alice generates a timelocked contract with 1 BTC, and
time = 2Δ ( Δ = some time unit )

• After 2Δ time, 1 BTC will be transferred to a target


account. (Target account can be Alice’s own account)
HTLC - Hashed Timelock Contract

Alice
1 BTC
Funding Contract - 1 BTC
Hash: ...Fa4509
Timeout: 2Δ
Timeout
Key revealed
OR
key: I love strawberries +
Signature BOB Time > 2Δ

1 BTC 1 BTC
Alice
Bob

Poon, Joseph, and Thaddeus Dryja. "The bitcoin lightning network: Scalable off-chain instant payments." (2016).
HTLC for Atomic Swap
Generate
Secret - key
Compute
Hash H

Alice H 33 ETH paid to


Alice
Bob knows key now.
Verify Alice created Verify Bob created 1 BTC
Bob the Funding HTLC Redeem
the Funding HTLC paid to
with H with H with key
Bob
Alice: HTLC(1BTC, H, 4Δ)
Bitcoin
Network Redeem with key
(thus key is revealed)

Ethereum Bob: HTLC(33ETH, H, 2Δ)


Network Time
What if Alice does not Reveal Key?
Generate
Secret - key
Compute
Hash H Alice refuses to reveal key

Alice H
1 BTC refunded to Alice

Verify Alice created the


Bob Funding HTLC with H Verify Bob created the
Funding HTLC with H
Alice: HTLC(1BTC, H, 4Δ) TIMEOUT
Bitcoin
Network
33 ETH refunded to Bob

Ethereum Bob: HTLC(33ETH, H, 2Δ) TIMEOUT


Network
Time
• Explained how hashed timelock contracts work
• Cross-chain atomic swap operations
• Two-party atomic exchange
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 48: Blockchain Interoperability - III


• Multi-party Cross-chain Swap
• Permissioned Blockchain Interoperability
• Data Transfer Across Multiple Hyperledger Fabric
Networks in Two Verticals
• Cross Chain Swap
• Permissioned Blockchain Interoperability
• Interconnection Relay
Multi-Party Atomic Cross-chain Swap

• Carol wants to sell her Cadillac for bitcoins


• Alice can buy Carol’s Cadillac, but wants to pay in an “alt-
coin” cryptocurrency
• Bob ready to trade alt-coins for bitcoins
• Alice, Bob and Carol arrange a three-way swap:
• Alice will transfer her alt-coins to Bob
• Bob will transfer his bitcoins to Carol
• Carol will transfer title of her Cadillac to Alice

M. Herlihy, “Atomic cross-chain swaps,” in PODC, 2018


Multi-Party Atomic Cross-chain Swap
• Alice creates a secret s, h = H(s)
• Publishes a contract on the alt-coin blockchain with
hashlock h and timelock 6Δ in the future, to transfer her
alt-coins to Bob
• Bob first confirms that Alice’s contract has been
published on the alt-coin blockchain
• He then publishes a contract on the Bitcoin blockchain
with the same hashlock h but with timelock 5Δ in the
future, to transfer his bitcoins to Carol

M. Herlihy, “Atomic cross-chain swaps,” in PODC, 2018


Multi-Party Atomic Cross-chain Swap
• Carol confirms Bob’s contract is published on Bitcoin
• She publishes a contract on the automobile title blockchain with
the same hashlock h, but with timeout 4Δ to transfer the
Cadillac’s title to Alice
• Alice confirms that Carol’s contract has been published on the
title blockchain
• she sends s to Carol’s contract, acquiring the title and revealing s
to Carol
• Carol sends s to Bob’s contract, acquiring the bitcoins and
revealing s to Bob
• Bob sends s to Alice’s contract, acquiring the alt-coins and
completing the swap M. Herlihy, “Atomic cross-chain swaps,” in PODC, 2018
Multi-Party Atomic Cross-chain Swap

M. Herlihy, “Atomic cross-


chain swaps,” in PODC,
2018.
Validity of the Protocool

• If any party halts while contracts are being deployed, then


all contracts eventually time out and trigger refunds
• If any party halts during triggering of contracts, only that
party ends up worse off
• If Carol halts without triggering her contract, then
Alice gets the Cadillac and Bob gets a refund, so Carol’s
misbehavior harms only herself

M. Herlihy, “Atomic cross-chain swaps,” in PODC, 2018


Interoperation in Permissioned Blockchains

● Permissioned blockchain networks are designed to be


private, for a closed consortium
● Different business sectors tend to have different groups
of organizations, thus have separate blockchain
networks
● TradeLens - Logistics, We.Trade Trade finance, IBM
Food Trust - Food Supply Chain, etc.
● Continue to operate in complete isolation
● Need for interoperation between different isolated
networks to achieve business goals
Abebe, E. et al., 2019, December. Enabling enterprise blockchain interoperability with trusted data transfer (industry track). In Proceedings of
the 20th International Middleware Conference Industrial Track
Interoperation in Permissioned Blockchains

Challenges
● Here interoperation is specifically Verifiable Data
Transfer between two separate permissioned
blockchain networks
● Data in a blockchain network is generated by
transactions going through consensus process
● Data consistent with the source network’s state
● Multiparty Trust - When one network consumes state
from another, it needs to establish the state validity as
per shared consensus view of parties in the network
Use Case
9. Obtain Bill of Lading (Inter-Blockchain)

SELLER
7. Create Consignment
Simplified
SELLER’S BANK 5. Request Booking TradeLens

4. Approve L/C 10. Request 6. Accept 8. Upload BL


Payment Booking Dispatch consignment
Simplified 1.Purchase Order
(Off-Blockchain)
We.Trade
CARRIER
3. Propose L/C
• We.Trade is a trade financing network
BUYER • TradeLens is trade logistics network
2. Request L/C • Letter of Credit (L/C) – a bank confirmation
that ensures payment will be made by the
BUYER’S buyer
BANK • Bill of lading proves that the seller has
Abebe, E. et al., 2019, December. Enabling enterprise blockchain interoperability with trusted dispatched the goods via the carrier,
data transfer (industry track). In Proceedings of the 20th International Middleware Conference • It enforces an obligation on the buyer (as per
Industrial Track letter of credit terms) to make a payment.
Verifiable Data Transfer in Permissioned Blockchain

● Each data (block) in a network


Enabling Enterprise Blockchain Interoperability with Trusted
has a set of endorsements Data Transfer (Middleware ‘2019)
(signatures) for consensus
● This set of endorsements
confirm the validity of a block
BUYER’s SELLER CARRIER
in the network BANK

● Thus, from the source, data is


accompanied with the set of SELLER’s
BANK
signatures - Attestations
● The attestations are validated BUYER SELLER

in the destination network Network A Network B

according to an data Abebe, E. et al., 2019, December. Enabling enterprise blockchain interoperability with trusted
data transfer (industry track). In Proceedings of the 20th International Middleware Conference
acceptance policy Industrial Track
Architecture
Abebe, E. et al.,
2019, December.
Enabling enterprise
blockchain
interoperability with
trusted data transfer
(industry track). In
Proceedings of the
20th International
Middleware
Conference Industrial
Track

● Relay Service: Provides the means of communication between the two separate networks
● Configuration Management Contract: Maintain identity (public keys) of the interoperating
networks
● Exposure Control Contract: Define and enforce policies on what data to expose to which network
● Data Acceptance: Validate the data received from a foreign network against the policy that defines
how many signatures are required (and other conditions) to verify a data
Protocol Overview

Steps:
1. Proof request is generated BUYER’s SELLER CARRIER
BANK
consisting of a verification
policy which has to be met
by the source network SELLER’s
BANK
2. Access control policies are
checked BUYER SELLER

3. Response data along with Network A Network B

proofs (endorsements)
sent back through relay
4. Proofs validated against
verification policy
Abebe, E. et al., 2019, December. Enabling enterprise blockchain interoperability with trusted
data transfer (industry track). In Proceedings of the 20th International Middleware Conference
Industrial Track
Protocol Details
Abebe, E. et al., 2019,
December. Enabling
enterprise blockchain
interoperability with
trusted data transfer
(industry track). In
Proceedings of the
20th International
Middleware
Conference Industrial
Track
• Explained how HTLC is used for three-party swap
• Permissioned blockchain interoperability
• Data transfer across different Hyperledger Fabric networks
• Web resources as mentioned from time to time
Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 49: Hyperledger Indy 1


• Hyperledger Indy Overview

• DIDs in Indy

• Hands-on tutorial on Indy


• Identity

• Indy

• DIDs
Hyperledger Indy

Hyperledger Indy provides


• tools
• libraries
• reusable components

for providing digital identities rooted on blockchains so


that they are interoperable across administrative domains,
applications, and any other silo.

https://wiki.hyperledger.org/display/indy
Indy Key Characteristics
• Distributed ledger purpose-built for decentralized identity

• BFT by design

• DIDs that are globally unique and resolvable (via a ledger) without
requiring any centralized resolution authority

• Verifiable Credentials in an interoperable format

• Zero Knowledge Proofs for Verifiable Presentations, which prove that


some or all of the data in a set of Claims is true without revealing any
additional information, including the identity of the Prover

https://wiki.hyperledger.org/display/indy
Indy Overview
Indy Overview
Indy Overview
Indy Overview
Indy Projects
• Indy-Plenum:
• Implements Byzantine Fault Tolerant Protocol
• Used for consensus in Indy
• Based on RBFT
• https://github.com/Hyperledger/indy-plenum

• Indy-Node:
• Implements the blockchain with Indy-Plenum consensus
• Defines identity specific transactions.
• https://github.com/Hyperledger/indy-node

• Indy-SDK
• Provides APIs to applications for accessing Indy network
• Indy- https://github.com/Hyperledger/indy-sdk
Install Indy – Starting an Indy Pool
Clone indy-sdk

git clone https://github.com/hyperledger/indy-sdk.git


cd indy-sdk

Build and run indy pool docker image

docker build -f ci/indy-pool.dockerfile -t indy_pool .


docker run -itd -p 9701-9708:9701-9708 indy_pool
Install Indy – Starting an Indy Pool
Easier Alternatives:

1. Starting a pre-configured docker image:

docker run -itd -p 9701-9708:9701-9708 ghoshbishakh/indy_pool

2. Start from indy-node repository:

Clone indy-node
git clone https://github.com/hyperledger/indy-node.git

Move to the directory indy-node/environment/docker/pool


./pool_start.sh [number of nodes in pool] [IP addresses of nodes] [number of
clients] [port for the first node]
Eg.
./pool_start.sh 4 10.0.0.2,10.0.0.3,10.0.0.4,10.0.0.5 10 9701
Install Indy SDK
Ubuntu based distributions (Ubuntu 16.04 and 18.04)
It is recommended to install the SDK packages with APT:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys CE7709D068DB5E88
sudo add-apt-repository "deb https://repo.sovrin.org/sdk/deb (xenial|bionic)
{release channel}"
sudo apt-get update
sudo apt-get install -y {library}

• {library} must be replaced with libindy, libnullpay, libvcx or indy-cli.


• (xenial|bionic) xenial for 16.04 Ubuntu and bionic for 18.04 Ubuntu.
• {release channel} must be replaced with master, rc or stable to define corresponded release channel.
Please See the section "Release channels" above for more details.

Install Python3 Wrapper


pip install python3-indy

https://github.com/hyperledger/indy-sdk
Scenario

University Alice Company


Scenario
Transcript
Transcript Verifiable
Verifiable Presentation in
Credential Job Application

1 2
University Alice Company

Indy Network
DIDs, Credential Schema, Definitions, Revocation Lists
Configuring Identities in Indy
Roles:
STEWARDS
• Public permissioned network
• Only pre-approved participants, known as stewards, are permitted to participate in the validation
process.

Trust Anchor(TA)
• Link between User and Stewards.
• E.g. banks, universities, hospitals, service providers, insurance companies.
• Onboarded by approvals of Stewards.
• Accepts the request from user and forwards this request to Stewards in case of writing into the ledger.
Configuring Identities in Indy
STEP1 - Connect to Indy Pool
- Genesis txn

STEP2 - Get ownership of Steward's DID

STEP3 - Register DID for Government, University and Company


- Nym Transactions
Conclusion

• Indy – public permissioned network

• Stewards and Trust anchors

• DID registration through Stewards


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 50: Hyperledger Indy 2


• Indy Verifiable Credentials

• Presentations
• Indy

• Verifiable Credentials

• Verifiable Presentations
Scenario
Transcript
Transcript Verifiable
Verifiable Presentation in
Credential Job Application

1 2
University Alice Company

Indy Network
DIDs, Credential Schema, Definitions, Revocation Lists
Indy Credential - Presentation Flow
STEP4 – Register Credential Schema
- Government creates transcript schema.

STEP5 – Create Credential Definition


- University creates a credential definition.

STEP6 - Issue Credential


- University issues transcript credential to Alice.

STEP7 – Verifiable Presentation


Alice sends Verifiable Presentation to Company.

STEP8 – Validate Presentation


Company validates Alice's claims from the presentation.

Source Code: https://github.com/ghoshbishakh/nptelindy


Conclusion

• Verifiable Credentials

• Verifiable Presentations

• Communication between participants


Blockchain and its applications
Bishakh Chandra Ghosh

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 51: Hyperledger Aries


• Aries Overview

• Aries Architecture

• Installation and usage


• Digital Credentials

• Aries
Hyperledger Aries
Hyperledger Aries provides a shared, reusable,
interoperable tool kit designed for initiatives
and solutions focused on creating, transmitting
and storing verifiable digital credentials.

It is infrastructure for blockchain-rooted, peer-


to-peer interactions.

Aries agent frameworks -.


• Aries Cloud Agent - Python (ACA-Py)
• For any non-mobile application. Has production deployments.
• Aries Framework - .NET
• Aries Static Agent - Python

https://www.hyperledger.org/use/aries
Aries Architecture
ACA-Py
• ACA-Py exposes a REST API to
access Aries capabilities

• Write a ‘Controller’ to implement


application business logic.

• Controller sends HTTP requests


(REST) to execute commands.

Response events are fed back to the


controller as webhooks.
Aries Architecture
The agent -
• Configured via command line
parameters
• Interacts with other agents via
pluggable transports
• Manages storage, ledger with
pluggable implementations
• Manages messages and protocol
state
• Invokes protocols (configurable set)
• Driven by a controller
• Sends events to controller
• Exposes an HTTP JSON
administrative API to
controller
Installation
• Install libindy and indy-cli
• apt-key adv --keyserver keyserver.ubuntu.com --recv-keys
CE7709D068DB5E88
• apt-add-repository "deb https://repo.sovrin.org/sdk/deb
bionic master" -y
• apt-get update
• apt-get install -y libindy indy-cli

• Install python3-indy
• python3 -m pip install python3-indy

• Install aries-cloudagent
• python3 -m pip install aries-cloudagent
Installation
If you installed the PyPi package, the executable aca-py should be
available on your PATH.

Use the following commands to check the version, list the available modes
of operation, and see all of the command line parameters:
• aca-py --version
• aca-py --help
• aca-py provision --help
• aca-py start --help
Starting Aries Agent
Provisioning a Wallet
It is possible to provision an Indy wallet before running an agent:
aca-py provision --wallet-type indy --seed $SEED

Use the SEED to configure existing nodes in the indy pool, e.g. Stewards.
Starting Aries Agent
When starting an agent instance, at least one inbound and one outbound transport MUST
be specified.

For example:
aca-py start --inbound-transport http 0.0.0.0 8000 --outbound-transport http

More Parameters:
• Transports: inbound, outbound, endpoint • Protocol automation flags
• Logging/debugging settings • Ledger parameters (e.g. genesis URL, etc.)
• Label: self-attested agent name • Add timing information to messaging
• Wallet implementation and related info • Optional protocols to load
• For controller: Admin API configuration • From controller: Event webhook URL
• URL
• Security selection
Using Aries with Indy
aca-py start --inbound-transport http 0.0.0.0 8000 \
--outbound-transport http \
--admin-insecure-mode \
--admin 0.0.0.0 8001 \
--seed 000000000000000000000000Steward1 \
--replace-public-did \
--wallet-type indy \
--genesis-file
/home/bishakh/Documents/TA/Blockchain/indytutorial/pool1.txn \
--wallet-name agent1 \
--wallet-key agent1 \
--log-level debug \
--log-file /tmp/arieslog.txt
--admin-insecure-mode \ For experimentation and debugging
--admin 0.0.0.0 8001 \ only
Aries Admin OpenAPI Interface
Conclusion

• Aries

• Communication between participants

• Digital Credentials
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 52: Blockchain Security - I


• Risks in Blockchain
• Common Risks and Specific Risks
• 51% Vulnerability
• Private Key Security
• Criminal Activities
• Double Spending
• Transaction Privacy
Risks in Blockchain

Risks
Common Risks Specific Risks

Blockchain Development,
operation mechanism deployment and
(Blockchain 1.0, 2.0) execution of
smart contract
(Blockchain 2.0)

"A Survey on the Security of Blockchain Systems", Xiaoqi Li, Peng Jiang, Ting Chen, Xiapu Luo and Qiaoyan
Wen, Future Generation Computer Systems
Risks in Blockchain
Risk
Blockchain operation Smart contract
mechanism execution
51% vulnerability Criminal smart contract
Private key security Vulnerabilities in smart contract
Criminal activity Under-optimized smart contract
Double spending Under-priced operations
Transaction privacy leakage
Common Risk: 51% Vulnerability
Hashing power

Block Block Block Block


10 11 12 13

Block Block Block Block


11' 12' 13' 14'

Hashing power
Common Risk: 51% Vulnerability
Coins

Block Block Block Block


10 11 12 13

Block Block Block Block


11' 12' 13' 14'

Coins
Common Risk: Private Key Security
Steal Alice's
private key

Alice's private key to sign the Alice's public key to verify the
Alice message message Bob
Common Risk: Criminal Activities

Valid
Chaff
Ransomware coin
coin
Money
Underground laundering
market
Common Risk: Double Spending
1. TXv is added to the wallet of the targeted vendor

Vendor

Attacker

2. TXa is mined as valid into the blockchain

Bitcoin Network Mining Pool


3. The attacker gets TXv ’s output before the vendor detects misbehavior
Common Risk: Transaction Privacy Leakage
A new transaction (the star) which spends an available coin (the second circle from the right)

Transactions and tracing in Bitcoin Transactions and tracing in Cryptonote

 Each transaction input explicitly  Each transaction input identifies a set of coins,
identifies the coin being spent, including the real coin along with several chaff
thus forming a linkage graph coins called “mixins.”
 Many mixins can be ruled out by deduction
 The real input is usually the “newest” one
• Introduced the basic risk types in blockchain
• Discussed in detail some of the common risks
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 53: Blockchain Security - II


• Selfish Mining Attack
• Different Scenarios and Attacker’s Actions
• Selfish Mining
• Attacker’s Pool
• Public Chain
• Block Suppression
Selfish Mining Attack

Others

Block 10 Block 11 Block 12 Block 13

Block 11' Block 12' Block 13' Block 14'

Mining Pool

"Majority Is Not Enough: Bitcoin Mining Is Vulnerable", Ittay Eyal and Emin Guen Sirer, Financial Cryptography, 2014
Selfish Mining Attack

Others

Block 10 Block 11 Block 12 Block 13

Block 11' Block 12' Block 13' Block 14'

Mining Pool
Selfish Mining Attack
Pool intentionally forking the chain for keeping
discovered blocks private

The honest nodes continue to mine on the public chain


The pool mines on its own private branch

Discovering more blocks by pool develops a longer lead on the


public chain, and continues to keep these new blocks private

When the public branch approaches the pool’s private branch in length,
the selfish miners reveal blocks from their private chain to the public
Selfish Mining Attack
1. Any state but two branches of length 1, pools finds a block

 The pool appends one block to its private branch, increasing its lead on the public branch by one
 Revenue from this block will be determined later
11pub Others' public chain

10 10 Pool's private chain

11pool 12pool 13pool 14pool


OR
11pub

10 1
0

11pool 11pool 12pool 13pool 14pool 15pool


Selfish Mining Attack
2. Was two branches of length 1, pool finds a block
 The pool publishes its secret branch of length two
 Pool obtains a revenue of two

11pub 11pub 11pub

10
10 10

11pool 12pool
11pool 11pool 12pool
Selfish Mining Attack
3. Was two branches of length 1, others find a block after pool head

 The pool and the others obtain a revenue of one each - the others for the new head, the pool for its
predecessor

11pub 11pub 12pub

10 10
11pool 11pool
Selfish Mining Attack

4. Was two branches of length 1, others find a block after others’ head

 The others obtain a revenue of two

11pub 11pub 12pub

10 10

11pool 11pool
Selfish Mining Attack

5. No private branch, others find a block

 Both the pool and the others start mining on the new head
 The others obtain a revenue of one

11pub
10
10
Selfish Mining Attack

6. Lead was 1, others find a block

 There are two branches of length one, and the pool publishes its single secret block
 The revenue from this block cannot be determined yet

11pub 11pub
10 10 10
11pool 11pool 11pool
Selfish Mining Attack

7. Lead was 2, others find a block


 The pool publishes its secret blocks, causing everybody to start mining at the head of the
previously private branch
 Pool obtains a revenue of two

11pub 12pub

11pub
10

10
11pool 12pool 13pool

11pool 12pool 13pool


Selfish Mining Attack
7. Lead was 2, others find a block (Contd.)
 The pool publishes its secret blocks, causing everybody to start mining at the head of the
previously private branch
 Pool obtains a revenue of two

11pub 12pub
11pub 12pub

10
10
11pool 12pool 13pool
11pool 12pool 13pool
Selfish Mining Attack
8. Lead was more than 2, others win
11pub
 The pool now reveals its i’th block
 Pool obtains a revenue of one
10
10

11pool 12pool 13pool

11pool 12pool 13pool


11pub

10

11pool 12pool 13pool


• Discussed selfish mining attack in detail
• Decisions of the attacker under different conditions
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Shamik Sural
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur

Lecture 54: Blockchain Security - III


• Eclipse Attack
• Front-running Attack
• Eclipse Attack
• Peer-to-Peer Network
• Front-running Attack
• Displacement, Insertion, Suppression
Eclipse Attack
Normal
nodes

To be victim
node

"Eclipse Attacks on Bitcoin’s Peer-to-Peer Network", Ethan Heilman, Alison Kendler, Aviv
Zohar and Sharon Goldberg, 24th USENIX Security Symposium, 2015
Eclipse Attack
Normal
Attacker
nodes
node

Victim node
Eclipse Attack
Attacker
nodes Normal
nodes

Victim node
Eclipse Attack

Victim Attacker
node node

Rest of
network
Off-path attack - attacker controls end-hosts, but not key
network infrastructure between the victim and the rest of the
bitcoin network
Eclipse Attack

Benefit: 51% attack with 40% mining power


30%
Hashing
power

40%
30% < 40% Hashing 40% >30%
power

30%
Hashing Attacker partitions miners so they can't build on each other blocks
power The attacker then outcompetes each partitioned miner
Eclipse Attack

Attacker populates the victim node's peer tables with attacker's IP addresses

Victim node restarts and loses current outgoing connections

The victim establishes all new outgoing connections to attacker IP addresses


Eclipse Attack
1. Populating of IP addresses
 Each node picks its peers from IP addresses stored in two tables
 New table: IPs the node has heard about
 Tried table: IPs the node peered with some point
 The tables also store a timestamp for each IP
 Each table stores the IPs in buckets
 To find an IP to make an outgoing connection to:
1. Choose new or tired table to select from
2. Select an IP with newest timestamp
3. Attempt an outgoing connection to that IP
Attacker populates tables with attacker IPs so that the victim
node only connects to the attacker IPs
Selection Bias: Attacker ensures its IPs are the newer one
Eclipse Attack

2. Restarting node event is natural?

 Software/security updates
 Packets of death/DoS attacks
 Power/network failures
 ISP outages
Eclipse Attack

3. Bucket eviction
 The bucket is full, and an IP is inserted into it
1. Randomly selects 4 IPs
2. Delete oldest IP
3. Insert new IP

Eviction Bias: Attacker IPs will always have the most recent
timestamps

Try-Try-Again: If an attacker IP replaces another attacker IP, the


evicted IP is resend and eventually replaced by honest IP
Front-running Attack

Attacker
2. Detects
Buy (1000)

Ethereum Network

Alice
"SoK: Transparent Dishonesty: Front-Running Attacks on Blockchain", Shayan
Eskandari, Seyedehmahsa Moosavi and Jeremy Clark, FC 2019 Workshops, 2020
Front-running Attack

Front-running Attack

After Attacker's run, Alice's function call is not


Displacement
important to the attacker

After Attacker's run, the state of the contract is changed.


Insertion
Alice's function call is needed to run on this modified state

After Attacker's run, she tries to delay Alice's function


Suppression call. After the delay, Alice's function call is indifferent to
the attacker
Front-running Attack
Front-running Attack
(Displacement / Insertion / Suppression)

Asymmetric Alice is trying to cancel an offer, and Attacker is trying to fulfill


it first

Bulk Attacker is trying to run a large set of functions and Alice is trying
to buy a limited set of shares offered by a firm on a blockchain
Front-running Attack
Markets and Exchanges: Spotting a profitable cancellation transaction
(Unordered) mempool Reordered Block
[…] Block Height #N
Cancel (order 100) Register (Bi)
Breed (cryptokittie 1, Buy (order 100)
cryptokittie 2) Adversarial
miner Cancel (order 100)
Buy (order 101) mines a Buy (order 101)
Bid (Bj) block with
preferred Bid (Bj)
Register (Bi) order Breed (cryptokittie 1,
[…] Ethereum Network cryptokittie 2)
Front-running Attack

Gambling: Bribing miners for prioritizing themselves

 When the timer of Fomo3D game reached


about 3 minutes, the winner bought 1 ticket
and then sent multiple high gasPrice
transactions to her own DApps
 Transactions congested the network
 Bribed miners to prioritize them ahead
of any new ticket purchases in Fomo3D

Users

Attacker DApps
• Described eclipse attack and front-running attack
• Importance of identifying attacks on blockchain and suggesting
remedies
• Combining multiple attacks
• Web resources as mentioned from time to time
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 55: Use Cases


• Blockchain use cases

• What makes a good blockchain use case?


• Use cases for enterprises

• Requirements for defining a blockchain


• Network
• People
• Assets
• Transactions
Simple Use Cases by Industry
What makes a good blockchain use case?
• Identifying a good blockchain use-case is not always easy!
• However, there should always be:

1. A business problem to be solved


• That cannot be more efficiently solved with other
technologies

2. An identifiable business network


• With Participants, Assets and Transactions

3. A need for trust


• Consensus, Immutability, Finality or Provenance
Understanding the Business Problem

1. What is the specific business problem / challenge that


the project will address?
• Scope the business challenge up front

2. What is the current way of solving this business


problem?
• Understand current systems and areas for
improvement

3. Assuming the business problem is large, what specific


aspects of this business problem will be addressed?
Understanding the Participants

1. Who are the business network participants


(organizations) involved and what are their roles?
• If there is no business network involved, then this
is not a good use case

2. Who are the specific people within the organization


and what are their job roles?
• Understand the key users in a business network.
Understanding the Participants
• Who are the participants? How many types of participants?
• How will they access and interact with the blockchain?
• Will they be peer nodes?
• Do you need web or mobile apps?
• Are gateways (such as exchanges or data providers) needed?
• Do you need to integrate to external data sources?
• Who will operate the blockchain? Who will govern/regulate
the blockchain?
• What is the value/incentive for each participant to join the
network?
Identities
• Do you need to know your users?
• Pseudo-anonymous blockchain like bitcoin does not
require user identities to be verified
Identities
• In most business use-cases, some form of identity is
required
• In public blockchains, an identity oracle (linked to a
trusted database) could provide such information sources
• Sources can come from governments, financial institutions
or utility providers
• In private blockchains, a gateway or controller ensures
identity is verified before credentials are issued to the
user
• Decentralized identity management is also possible – we
have seen that – may be the preferred way for a
blockchain application
Understanding the Assets and Transactions

1. What assets are involved and what is the


key information associated with the assets?

2. What are the transactions involved,


between whom, and what assets are
associated with transactions?
• Understand under what business or contractual
conditions assets are under, as they transfer
from one owner to another.
Defining Transactions

• What types of processes need to take place in your


blockchain network?
• Invoke actions – add, delete, change, transfer
• Query
• Do you need to control access to these functions based
on participant types or roles?
Additional Points of Understanding
1. What are the main steps in the current workflow
and how are these executed by the business
network participants?

2. What is the expected benefit of applying blockchain


technology to the business problem for each of the
network participants?

3. What legacy systems are involved? What degree of


integration with the legacy systems is needed?
Conclusion
• We need to think carefully before applying blockchain
directly on a problem
• Do we really need to use blockchain?
• What are the pros and cons of using blockchain to solve the
problem?
• Can there be a better technology?
• Can we define the entities?
• The business network
• The participants, assets, and transactions
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 56: A Potential Use Case – From a Critics


Perspective
• Land Registry Records – Can we use a Blockchain?
• Requirement analysis

• Tradeoff analysis
Maintaining Land Registry Records
• Historically, land registries were paper-based
• Can be lost, destroyed, falsified, or otherwise manipulated

• Selling a property (land)


• Owner has to prove the ownership

• A complex business network – multiple realtors,


inspectors, appraisers, escrow
• Help people to do the best purchase / sell of the property
Real Estate Scams and Frauds
Real Estate Scams and Frauds

Can a blockchain help?


Real Estate Scams and Frauds

Can a blockchain help?


What is the business network?
Who are the participants?
Who will maintain the blockchain?
What are the transactions?
The People in the Business Network
• Government
• Real estate agents (?)
• Buyers
• Sellers
• Investors (Crowdfunding)
• Startups (real estate business)
The Assets
• Lands
• Properties (buildings, etc.)
• Money
The Transactions
• Buy lands and/or properties
• Sell lands and/or properties
• Crowdfund an investment
• Return from a crowdfunded investment
Public or Private Blockchain

• Public Blockchain
• Pros: Open network, anyone can
invest or participate as a startup
• Cons: You do not know to whom you
are investing
Public or Private Blockchain

• Private Blockchain
• Pros: The identity of the participants
are known, better security (?)
• Cons: Who will validate the
authenticity? May fallback to a
centralized system
Advantages of using blockchain

• Provides a decentralized platforms and marketplace


• Can avoid intermediaries
• Liquidity in business – can be traded readily
• Fractional ownership and crowdfunded investments
• Reduced cost of transactions
• Better transparency
But there are many important implementation
questions ...
• Who are going to be the full nodes of the system?
• Government?
• Investors?
• Startups?
• Buyers, sellers?
But there are many important implementation
questions ...

• Everyone is a full node


• I'll sell my property for once … why should I
download the entire blockchain?
• Should I sign out once I am done? How do I
resolve a query that comes later on?
• Do I need to keep my keys forever?
• What if I loose the keys?
But there are many important implementation
questions ...

• I am not the full node


• Which full node should I trust?
But there are many important implementation
questions ...

• Blockchain, by default, is world-readable


and world-writable
• Isn't it a privacy concern?
• Say, I am an investor. Everyone can see where I
have invested and how much money I have
invested
But there are many important implementation
questions ...

• Blockchain, by default, is world-readable


and world-writable
• Isn't it a privacy concern?
• Say, I am an investor. Everyone can see where I
have invested and how much money I have
invested
• Cross-argument: Use keys to secure the
channel
But there are many important implementation
questions ...
• Blockchain, by default, is world-readable
and world-writable
• Isn't it a privacy concern?
• Say, I am an investor. Everyone can see where I
have invested and how much money I have
invested
• Cross-argument: Use keys to secure the
channel
• Who is going to provide the key?
But there are many important implementation
questions ...
• What should be the credential to participate as an
investor or a start-up?
• Who will validate that a start-up is not a fraud
• Trusted third party?
• Then why can't that trusted third party
maintain a database?
• Note: There are methods for blind
signatures, you don't need to
reveal all information to the TTP
Conclusion
• There are many fundamental questions that need to
be solved before putting an application to the
blockchain

• The application designer needs to analyze all


possible trade-offs
• Is the benefit more than the cost?

• Digitizing the land and property records might solve


many of the problems! Need to think of it ...
Conclusion

• We have seen the idea of decentralized identity


management
• Can explore whether that can be coupled with
other applications to solve some of the problems
that we mentioned
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 57: Blockchain in Financial Services


• Cross-border payments over blockchain

• Project Ubin
• Steller Protocol and Network

• Ripple Protocol and Network

• Project Ubin
Cross-Border Payments
• Classic use case for which Bitcoin was created and perhaps the
holy grail of cryptocurrencies
• To date, we have over 6000 cryptocurrencies!
• But, what qualifies as a currency. In economics, the following
criteria must be satisfied:
• Medium of exchange: Are merchants willing to accept the
currency in exchange for goods and services
• Unit of account: Is it a measure of the real value of goods and
services (e.g., would a merchant be willing to accept the same
value regardless of relative currency fluctuations)
• Store of value: A mode of investment
Steller Protocol and Network
• Decentralized, hybrid blockchain platform with open membership;
launched in 2014; Lumens as native asset
• Federated Byzantine Agreement (FBA) – quorums formed based on
participants individual trust decisions, followed by agreement within
quorums (Steller Consensus Protocol)
• 2-5 second transaction clearance
• Anchors act as bridges between a given currency and Stellar
network
• Has a distributed exchange: pay in EUR with INR balance
and network will automatically convert it at lowest rate
for you https://www.stellar.org/
Steller Protocol and Network
• The idea got published in a SOSP 2019 Paper --
• Lokhava, Marta, et al. "Fast and secure global payments with
Stellar." Proceedings of the 27th ACM Symposium on Operating
Systems Principles. 2019.

• Federated voting: Nodes try to agree on abstract statements by


first voting, then accepting, and finally confirming statements.
• Keep on voting any valid statement
(that the nodes believe to be valid)
• Accept when a majority votes (form quorums)
• Confirm when the quorum unanimously accepts a statement
Federated Voting in Steller
Federated Voting in Steller
Vote x

Vote y
Federated Voting in Steller
Vote x

Vote x Vote x

Vote x

Vote y

Vote y Vote y
Federated Voting in Steller
Accept x

Vote x Accept x

Accept x

Vote y

Vote y Vote y
Federated Voting in Steller
Accept x

Accept x Accept x

Accept x

Accept x

Vote y Vote y
Federated Voting in Steller
Accept x

Accept x Accept x

Accept x

Accept x

Accept x Accept x
Steller Protocol and Network
• Partially synchronous protocol
• Safety under asynchronous assumptions
• Liveness require a synchronous network

• Performance:
Ripple Protocol and Network
• Protocol for banks to clear and settle payments in real time through a
distributed network
• Consensus (XRP Ledger – XRPL -- https://xrpl.org/ ) allows payment
exchanges and remittance to happen without need for a centralized clearing
house
• Average 5 second confirmations; no mining, custom protocol that hasn’t yet
been validated for correctness and fault tolerance
• Gateway nodes convert fiat currencies to XRP (currency in Ripple)
• Market-makers convert from one currency to another
• Centralized governance, with Ripple still holding a large fraction
of the cryptocurrency
• https://ripple.com
Ripple Protocol and Network

• Unlike Steller, there are open questions on Ripple consensus


• Chase, Brad, and Ethan MacBrough. "Analysis of the XRP ledger
consensus protocol." arXiv preprint arXiv:1802.07242 (2018).
• Claims that XRPL violates safety and liveness
Project Ubin: SGD on Distributed Ledger

• A collaborative project with the industry to explore the use of


Blockchain and Distributed Ledger Technology (DLT) for clearing and
settlement of payments and securities
• Taken up by the Monetary Authority of Singapore (MAS) in November,
2016
• Reports available on the MAS website:
https://www.mas.gov.sg/schemes-and-initiatives/project-ubin
Project Ubin: SGD on Distributed Ledger

• Five-phase project
• Phase 1: Tokenized SGD
• Phase 2: Re-imagining RTGS
• Phase 3: Delivery versus Payment (DvP)
• Phase 4: Cross-border Payment versus Payment (PvP)
• Phase 5: Enabling Broad Ecosystem Collaboration
Project Ubin: SGD on Distributed Ledger

• Phase 1: Tokenized SGD


• Consortium of financial institutions to conduct inter-bank
payments using blockchain technology
• Bank of America Merrill Lynch, Credit Suisse, DBS Bank, HSBC, JP
Morgan, Mitsubishi UFJ, OCBC, R3, Singapore Exchange (SGX),
United Overseas Bank
• Include DLT-based payment in MEPS+
• Participant banks pledge cash into a custody account
held at MAS. MAS will then create the equivalent value
in Digital SGD on the DL and assign them to the
respective banks.
Project Ubin: SGD on Distributed Ledger
Project Ubin: SGD on Distributed Ledger

• Phase 2: Re-imagining RTGS


• Led by MAS and The Association of Banks in Singapore (ABS)
• Developed PoC using three DLT platforms – Ethereum, Fabric,
and R3 Corda; open-sourced https://github.com/project-ubin
• Solves the problem of gridlock
Project Ubin: SGD on Distributed Ledger

• Phase 3: Delivery versus Payment (DvP)


• The cash payment for a purchased security occurs prior to,
or upon, its delivery
• Two counterparties (traders) meets at an agreed time
to exchange the agreed assets.
• In this phase, MAS and SGX collaborated to realise
domestic DvP settlement on two separate blockchain
platforms
Project Ubin: SGD on Distributed Ledger

• Phase 3: Delivery versus Payment (DvP)


Project Ubin: SGD on Distributed Ledger

• Phase 4: Cross-border Payment versus Payment (PvP)


• Joint initiative by Bank of Canada (BoC), Bank of England
(BoE) and MAS; initiated in November, 2018
• Transparency in payment status, availability of cross-border
payment services, reduced time for payment
processing, reduced costs
• Considers three different payment models and analyzes
their respective impact and scale
Project Ubin: SGD on Distributed Ledger

• Phase 4: Cross-border Payment versus Payment (PvP)


• Model 2
Project Ubin: SGD on Distributed Ledger

• Phase 5: Enabling Broad Ecosystem Collaboration


• Provides technical insights into the blockchain-based multi-
currency payments network prototype that was built
• Describes how the network could benefit the financial
industry and blockchain ecosystem.
Project Ubin: SGD on Distributed Ledger

• Phase 5: Enabling Broad Ecosystem Collaboration


Project Ubin: SGD on Distributed Ledger
• Phase 5: Enabling Broad Ecosystem Collaboration
Blockchain for Procure-to-Pay
(B2P)
Automated document verification
and payment processing
Conclusion

• Financial services have been one of the key use-cases


for Blockchain
• Project Ubin develops a payment network prototype for
multi-currency payments; the project has been open-
sourced
• Check the project reports for
Ubin: https://www.mas.gov.sg/schemes-and-
initiatives/project-ubin
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 58: Public Sector Use Cases


• Government use cases of blockchain
• Public data management

• Public taxation

• National strategies
Blockchain and Government
• Government needs to maintain (in digital or in paper form)
• Daily operations and activities
• Government assets (land records, buildings etc.)
• Details of people, organizations and institutions
• Records of people
• Business transactions
Multi-institutional and Multi-Organizational
• Different levels of governance

Country State District Village,


Panchyat, Cities
Multi-institutional and Multi-Organizational
• Every level builds its own ledger of data
• Different access management policies
• Role based access control or access management

• Different priority of data


• High priority or highly secured data - restricted
access - needs to prevent from unauthorized access
(example: AADHAAR Data)
Blockchain and Government
• Blockchain can help in management of government
data at different levels

• Note
• Directly store the data on blockchain?
• The data cannot be altered without colluding majority of
the blocks
• Data access as transactions - can check or verify who
has accessed what
Government and Cyber Crime
• Government database is a major target for
hackers
• In 2020, there are 1001 cases of data breaches that
affected 155.8 million individuals
(Source: https://www.statista.com/)

• “Cyber War” - actions by a nation-state to


penetrate another nation’s computers or
networks (Richard Clarke)
Theft of Government Data
Processing of Government Data
• Data is shared among multiple organizations at
different level of government structure

• The problem of data breaches increases at every


level
• Data duplication
• Data multiplicity

• Protection of data gets diluted if multiple copies


of same data exist
Sharing of Passport Data: An Example

Passport
Data

Ministry of foreign
Affairs - Passport
data management
Sharing of Passport Data: An Example

Airport/ Sea port


Custom Check

Passport
Data

Ministry of foreign
Affairs - Passport
data management
Sharing of Passport Data: An Example
National Army
Defense Agency

Airport/ Sea port


Custom Check

Passport
Data

Ministry of foreign
Affairs - Passport
data management
Sharing of Passport Data: An Example
National Army
Defense Agency
National Police Agency
Airport/ Sea port CBI/CID - Crime department
Custom Check
Public Service
Identity Database
Passport
Data

Ministry of foreign
Affairs - Passport
data management
Sharing of Passport Data: An Example
National Army
Defense Agency
National Police Agency
Airport/ Sea port CBI/CID - Crime department
Custom Check
Public Service
Identity Database
Passport
Data

Ministry of foreign
Income Tax Department Affairs - Passport
National Intelligence data management
National Audit Agency
Sharing of Passport Data: An Example
National Army
Defense Agency
National Police Agency
Airport/ Sea port CBI/CID - Crime department
Custom Check
Public Service
Identity Database
Passport
Data

Ministry of foreign
Income Tax Department Affairs - Passport
Ministry of
National Intelligence data management
Public Service
National Audit Agency
Government Information Sharing System: A
Typical Example
Service
Requester Agency Directory

Service Broker
Service Broker
Organization Service
Service Gateway

Data Directory Service


Service Gateway

Search, Account and


Other Service

Government Information Sharing


Civic Service System Portal
System
How Blockchain Helps
• Access and verification of a central data
– Data is in a central database
– Access to the database are the transaction
– Every such transactions (access to the data) is logged in a
blockchain
– Data can be accessed only through the blockchain
– Anyone can verify who has accessed data and for what
purpose
How Blockchain Helps
• Sharing of data
– Data is in the blockchain
– (May not be the ideal solution all the time)
– Everyone can verify which data has been shared
– Data cannot be altered
How Blockchain Helps
• Sharing of data and access control
– Keep both the data and the access at a blockchain
– Depends on the size of the data
– Anyone can verify the data and the access
– Neither data nor access can be altered
– Access cannot be denied
Case Study: Processing Tax Payments
• Goods and Services Tax (GST) - indirect tax covering
various goods and services during the production and
service stages
• IGST
• SGST
• CGST
• The entire workflow is pretty complex -
Let’s see how Blockchain can help!
Case Study: Processing Tax Payments
• Say, you want to purchase a dress - it has multiple
workflows at the production stages
GST without Blockchain

A GST Invoice Buyer pays Information of the


is issued by the bill with payment is recorded
the seller GST at GST Portal

Seller pays to the


Additional payment Final Tax goes to
suppliers
is adjusted the government
GST with Blockchain

A GST Invoice Buyer pays


Seller pays to the
is issued by the bill with
suppliers
the seller GST

Smart Contract adjusts the tax


Final Tax goes to
calculation during the payment
the government
Case Study: Processing Tax Payments

• During the payment for a good or a service


• Blockchain smart contracts can calculate the invoice
based on the tax amount that is already levied during the
production process
• Smart contract directly transfers the tax amount to tax
authority (CGST or SGST)
• The refund, if any, is directly paid to the customer’s
account
Advantages of using Blockchain

• The administrative burden for accounting services is


drastically reduced
• All the transactions are done in real time, no “return
filing” is required, or “return filing” can be avoided
• All the transactions are transparent
• Reduces risk of fraud and mistakes
• Immediate auditing from the transaction log
Draft National Strategy of Blockchain in India
• Published by Ministry of Electronics and Information Technology
(MeiTY) during January 2021
Draft National Strategy of Blockchain in India
• Highlights a number of use cases for possible national interests

• Transfer of Land Records (Property Record Management)


• Digital Certificates Management (Education, Death, Birth,
agreements, sale deeds …)
• Pharmaceutical supply chain
• e-Notary Service (Blockchain enabled e-Sign Solution)
• Farm Insurance
• Identity management
• Power distribution
• Duty payments
Draft National Strategy of Blockchain in India
• Highlights a number of use cases for possible national interests

• Agriculture and other supply chains


• eVoting
• Electronic Health Record Management
• Digital Evidence Management System
• Public Service Delivery
• IoT Device Management and Security
• Vehicle lifecycle management
• Chit fund operations administration
• Microfinance for Self-Help Groups
Draft National Strategy of Blockchain in India
National Blockchain Roadmap, Australia
Conclusion

• There are various scopes for applying blockchains in


public services that involve multiple stakeholders
• Are we sufficiently prepared?

• However, we should be careful about the possible


side channels
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 59: Blockchain for Decentralized Marketplace


(Part 1)
• Blockchain application for a decentralized marketplace
• Design a blockchain use-case

• Analyzing the requirements


Online Service Providers
• Offers services to the consumers (end-users).​
• Use web interface or mobile apps for communicating with consumers.​
• Examples: Service
• Ecommerce​ Request
• Cloud Service Providers​
• Media Service Providers​
• Logistics Providers​ Consume Service Provider
r Service,
invoice, etc..
Online Service Providers
● Multiple service providers (SPs) come into agreement to collaborate.
● Gain access to the common larger set of end-users.
● Offer wider range of services under the same platform.
● Meet user demands by sharing resources.
● Examples:
○ Different sellers under ebay, Amazon.
○ Cloud infrastructure providers under OnApp Federation.
○ Hotels under trivago
Online Service Providers

Trade Logistics
Ecommerce Platform Network

Seller 1 Seller 3
Ban
k
Seller 2
Existing Consortia -- Centralized
Consumers

Ecommerce Platform

Seller 1 Seller 3
Seller 2
Consumers
Limitations
● Usually governed by a single authority (service
broker / marketplace )
○ Unfair business advantage to the broker
● Only service broker or marketplace provider
is responsible for communicating with end-users.
SP 1 SP 3
● Profit sharing with central broker
SP 2
● Bias of broker towards a particular provider
● Risk of manipulation & unfair dispute resolution
Objective
• Design a transparent decentralized architecture for
service providing consortium, while eliminating any
centralized broker/marketplace.
Objective
• Design a transparent decentralized architecture for
service providing consortium, while eliminating any
centralized broker/marketplace.

Blockchain Interoperability for Service Decentralization​,


IEEE INFOCOM 2021

Bishakh Chandra Ghosh (IITKGP), Tanay Bhartia (IITKGP),


Sourav Kanti Addya (NITK), Sandip Chakraborty (IITKGP)
Centralized to Decentralized
Consumer Consumer
s s

SP
SP
broker / marketplace

SP SP SP
SP
SP
Requirements
• While eliminating the central broker/marketplace, all its
functionalities must be preserved in the decentralized
consortium architecture:
● Unified Interface
○ The consortium should have a unified interface to its consumers.
○ The interface should be without any centralized broker or agent.
○ Consumers should be able to view catalog, query prices, request
for resources, get resource access information and credentials,
make payment, etc., through the interface.
Challenges

A. Byzantine behavior B. Byzantine faulty C. Verifiability and confidentiality of


of consortium SPs. consumers with ability to create information from the consortium
multiple identities.​
• There is no single trusted spokesperson of
• The participating SPs might • End-users / consumers can exhibit the consortium.​
be byzantine faulty [8].​ byzantine fault.​ • The results of the consortium is based on
• SPs can maliciously try to • Each user requests must be agreed agreement of the SPs.​
affect the pricing, scheduling, upon by the consortium participants to • This agreement must be manifested outside
and policies of the process it correctly.​ the federation, and should be verifiable by
consortium.​ • Consumers can create as the end-users.​
• SPs can be biased many identities (accounts) as they • Sensitive consortium response must remain
towards certain users and want introducing the risk of confidential between the consumers and the
also might try to block certain Sybil attacks[8].​ SPs.​
user requests by affecting the
consortium agreement.​
Threat Models
● Byzantine faults: We consider that at most 1/3 of the SPs may be
Byzantine Faulty. Non-faulty consumers control majority of computing power.
● Sybil attacks: End-user consumers can create multiple accounts/identities
for accessing the consortium services.
● Impersonation attacks: Decentralized consortium does not have a
single spokesperson. A malicious SP might try to deceive a
consumer by posing as the consortium’s spokesperson.
● Leakage of sensitive information: Sensitive information of the
consortium as well as users might be exposed while passed
over the decentralized network.
Architectural Requirements
1 Decentralized Consortium Collaboration
1. Agreement on pricing, catalog, policies.
2. Scheduling of requests
3. Confidentiality of SP information must be preserved.

Consumer Consumers
s SP SP
Service SP SP Service
Request Response
SP SP

SP Process
SP Request SP SP
2
Decentralized Consortium Interface
1. Agreement on each user request and the ordering of user requests.
2. Service response must be verifiable by end-users. Confidentiality of
response must be preserved.
Decentralized Consortium Interface

SP
SP

Consumers
SP
Private SP
Blockchain
Decentralized Consortium Interface
● How user requests reach the Consortium?
● No single spokesperson for the consortium.
- No single web portal or address available for communication.
● Simple solutions like a broadcast from the consumers to the closed
network will not work.
○ Messages might be lost
○ Messages might arrive out of order.
● Consumers might be byzantine faulty and try
to partition the consortium.
Decentralized Consortium Interface
Required Guarantees:
1. Consortium Interface Safety - Non faulty SPs receive
the same set of consumer requests and in the same
order.

1. Consortium Interface Liveness - All non


faulty consumer requests are eventually received by
the consortium.
Designing the Interface
● Use public blockchain for the interface.
● Any user can join the network and avail services by
issuing transactions.
● Smart contract (having a fixed logical address), act as
the single point of contact.
● Mining process mines blocks with the transactions.
● The network has consensus on each block =>
Consensus on each user request.
● Each block has a fixed ordering of transactions =>
Consensus on order of user requests.
Designing the Interface

Service Service request - Tx Propagation: Block Confirmation:


smart contract
Block Mining:
Request Tx is flooded among Block is mined based Mined block is flooded in
Contract execution
Consumer transaction
the participants on PoW / PoS / other. the network.
s
Transferring Consensus to the Consortium

Servic ?
e SP
reques SP
Consumer t
s
Public SP Private SP
Blockchain Blockchain
Transferring Consensus to the Consortium
Consortium SPs cannot simply pick requests from the
permissionless blockchain and start processing:
1. Some consortium members might not get the mined
block in time and thus cannot participate in its
scheduling.
2. Malicious consortium members may introduce and
schedule invalid consumer requests that are
not mined at all.
3. Consensus protocol like PoW, often goes
through temporary forks. (Network is partitioned into
two or more parts with different accepted blocks.)
Transferring Verifiable Response

Servic
e SP
reques
SP
Consumer
s
t
Service
response
?
SP SP
Public
Blockchain
Private
Blockchain
Transferring Verifiable Response
A single SP cannot simply post a response of the
Consortium back to the users.
1. Consortium response is always based on a consensus
on the same.
2. The consortium consensus has no manifestation
outside the private blockchain.
3. The consortium consensus on response must be
verifiable by the end-users.
4. Confidentiality of the response has to be preserved
while transferring across the public blockchain network.
Transferring Verifiable Response
A single SP cannot simply post a response of the
Consortium back to the users.
1. Consortium response is always based on a consensus
on the same.
How do consensus
2. The consortium we solve this
has problem?
no manifestation
outside the private blockchain.
3. The consortium consensus on response must be
verifiable by the end-users.
4. Confidentiality of the response has to be preserved
while transferring across the public blockchain network.
Blockchain and its applications
Prof. Sandip Chakraborty

Department of Computer Science & Engineering


Indian Institute of Technology Kharagpur

Lecture 60: Blockchain for Decentralized Marketplace


(Part 2)
• Blockchain application for a decentralized marketplace
• Design a blockchain use-case

• Analyzing the requirements

• Consensus on Consensus
Transferring Consensus to the Consortium

Servic ?
e SP
reques SP
Consumer t
s
Public SP Private SP
Blockchain Blockchain
Transferring Verifiable Response

Servic
e SP
reques
SP
Consumer
s
t
Service
response
?
SP SP
Public
Blockchain
Private
Blockchain
Consensus on Consensus
Consensus propagation from public blockchain to private
consortium blockchain

● Each SP also participates in the public blockchain to receive service


requests from consumers.
● When a transaction is committed in the public ledger, it is verified by the
SPs through Simplified Payment Verification (SPV)[8]
● For each service request, the SPs collect
endorsements through Propagation Contract
● Each endorsement goes through BFT consensus.
● When a service request receives k ≥ ⅔ of the SPs’
endorsements, it is marked as confirmed.
Consensus on Consensus
Block Number
B10
Service Transaction Public
request Tx Propagation Blockchain Offset O1
(T1) Consensus T1
Consume Miner Service request Tx
r
Public Ledger SPV (B10,
B0 B1 B9 B10 O1)

T1
SP 1 SP2 SPk
Initialize Propagation
BFT Consensus Contract & Send
endorsement - E(T1)
E(T1)
BFT Consensus
Private Ledger BFT Consensus
E(T1)

PB0 PB1 PB14 PB15 PB16


E(T1) E(T1) E(T1)
EC = 1 EC = 2 EC = k
B10, O1 B10, O1 B10, O1 T1 ready for
scheduling
Verifiable Response Transfer
• Two kinds of information need to be transferred from the consortium to the
consumers:
a. Consortium information such as catalog, pricing, etc.. - not sensitive
b. Request responses - results of scheduling and processing consumer requests
such as a digital document, e.g., access credentials, tickets, invoices, etc. -
sensitive
● Both kinds of data are generated collectively by SPs through
private blockchain’s consensus process.
● Consumers being outside the permissioned network cannot
verify the correctness of the data.
● Separate protocol required for validation of consortium
response by consumers.
Verifiable Response Transfer
● We use the concept of Collective Signing (CoSi) [21]
○ A set of consortium SPs collectively sign a valid data to make it verifiable.
○ We utilize Boneh-Lynn-Shacham (BLS) cryptosystem for aggregating
signatures from individual SPs.
○ A BLS signature for message is computed as:
is a cryptographic hash function.
Is secret key of SP
Aggregated multi signature for n SPs:

[21] Syta, Ewa, Iulia Tamas, Dylan Visher, David Isaac Wolinsky, Philipp Jovanovic, Linus Gasser, Nicolas Gailly, Ismail Khoffi,
and Bryan Ford. "Keeping authorities" honest or bust" with decentralized witness cosigning." In 2016 IEEE Symposium on
Security and Privacy
Verifiable Response Transfer
● Consortium response is accepted as valid only if it has ≥ ⅔ of the SPs’
signatures.
● For preserving confidentiality, a response to a consumer is encrypted
using its public key.
● Signature Collection:
● Multisignature collection is carried out off-chain to improve latency.
● A communication tree is formed along which the singing request
and the signatures are exchanged.
● Each node of the tree aggregates signatures collected from its
descendants.
● Fallback to smart contract based signature collection in case of
denial of service attack by some SP.
Verifiable Response Transfer
Private Ledger
PB0 PB1 PB14 PB15 PB16 PB17 PB18
E(T1) E(T1) E(T1)
Response S(M)
EC = 1 EC = 2 EC = k R1 SC = 1
B10, O1

M = Encrypt(R1)
B10, O1 B10, O1

Initialize Signature
Scheduling Collection Fallback
BFT Consensus
Contract Contract

BFT Consensus
Aggregated
Public signatures SM
Public Ledger Blockchain
SP1
M
Tx
B0 B1 B9 B10 M
Miner SP2 SP3
M
M M
SM M
SP4 SP5 SP6 SP7

If some SPs deny /


Validate Aggregated fail
Signature & Decrypt
* If SP1 fails other SPs initialize the contract after a timeout
Consume
r
Use Case Implementation: Cloud Federation
● Consortium of cloud service providers (CSPs).
● Provide cloud infrastructure resources to end-users (IaaS).
● Implemented a fair scheduling algorithm for allocation of consumer
requests among SPs:
○ Each SP will be allocated the number of consumer requests
proportional to its infrastructure contribution in the federation.
● Test bed implementation using Ethereum and Hyperledger
Fabric, and Hyperledger Burrow.
● Mininet emulation for evaluating scalability.
Use Case Implementation: Cloud Federation

VM
Request

Consume
r VM access
credentials

Cloud federation
consortium
Testbed Setup
Results
Results
Results
Conclusion
● There are interesting research/design problems in the blockchain
space
● You need to think of applying the right technology at the right
place!

● Remember the fundamental questions that we talked about earlier


● Network, participants, assets, transactions
● Keys – how to obtain and share
● Trusted third party – do we have any?
● Why people will join your blockchain network

You might also like