100% found this document useful (1 vote)
464 views489 pages

Blockchain Ebook

Uploaded by

Rohit Kumar Das
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
100% found this document useful (1 vote)
464 views489 pages

Blockchain Ebook

Uploaded by

Rohit Kumar Das
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/ 489

Blockchain Certification Training

Lesson 0: Course Introduction

© Simplilearn. All rights reserved.


Course Objectives

By the end of this course, you will be able to acquire the following skills:

• Describe Blockchain technology and its key concepts


• Explain Bitcoin Transaction Process
• Work with Ethereum deployment tools
• Deploy a private Ethereum Blockchain
• Work with Hyperledger projects
• Deploy a business network using Hyperledger Composer
• Develop and deploy smart contracts on Ethereum test network
• Develop a private Blockchain using Multichain
• Describe the future prospects and real world use cases of Blockchain
Course Outline

Overview of Blockchain Hyperledger

Bitcoin Blockchain Hyperledger Composer

Ethereum Blockchain on Multichain

Deploying Smart Contracts


on Ethereum Network Blockchain Prospects
Prerequisites for This Course

There are no prerequisites for this course. However, prior knowledge of the following technologies
would be helpful:

Linux Fundamentals Node.js Fundamentals

JavaScript
Highlights of This Course

Health Insurance Business


04
Building the Business Network
Network on Hyperledger 01 of a Finance Company

User Identity Verification on


Ethereum 02 05 Getting Started with Private
Ethereum Blockchain

Hands-on Practice with Stock Exchange with


Hyperledger Projects 03 06 Multichain
Thank You
Blockchain
Lesson 1: Overview of Blockchain

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Describe the Blockchain transaction process

Generate a public key and a digital signature

Generate a nonce, a hash code, and a Blockchain block

Work with a distributed system and perform Blockchain transaction


Overview of Blockchain
Blockchain and Its Importance
Blockchain

• Blockchain is a decentralized ledger of all transactions across peer-to-peer network.


• It is a technology that enables Bitcoin and is also applied to many business processes.
• It not only performs transactions but also ensures anonymity and security of the users.
History of Blockchain

Satoshi Nakamoto
created Bitcoin and
Currency transfer and Market development
introduced the Evolution of smart
digital payment system and exploration across
concept of Blockchain contracts
industries

2009 2012-2013 2014-2015 2016-2017

1990 2011-2012 2013-2014 2015-2016


The concept of Cryptocurrency Financial markets and Permissioned
distributed ledgers has deployment in applications using Blockchain network
been around since applications Blockchain beyond solution
1990 cash transactions
Current Banking System

John Bank Kat

Sends $10 to Kat Acts like a third party Receives $9


through a bank and takes
commission of $1
Issues in Banking System

There were few issues in the previous banking system that lead to the rise of Blockchain technology.

Account Hacking Net Frauds

Issues

Financial Crisis High Transaction Cost


Blockchain Solution to the Issues

Blockchain tackled the issues in the previous system with some of its features mentioned below:

Distributed Ledger Decentralized System

Incentives of Validation Features

Consensus Algorithm Cryptography Algorithm


Overview of Blockchain
Blockchain Transaction Process
Blockchain Transaction Process

Transaction is validated by
Transaction is broadcasted the miner

Transaction is
requested
Transaction becomes a part
of the new block created

Transaction is now New block is added to the


completed Blockchain
Steps of Blockchain Transaction

Blockchain transaction works implementing one of the following features in each step:

Cryptography Decentralized Consensus Distributed


Algorithm Network Algorithm Ledger
Overview of Blockchain
Transaction Initiation
Features of Blockchain

Cryptography Decentralized Consensus Distributed


Algorithm Network Algorithm Ledger

It ensures authentication and integrity of the transaction.


Asymmetric Key Cryptography

Encrypts message Decrypts message


using public key using private key
Symmetric Key Cryptography

Encrypts message Decrypts message


using secret key using same secret
key
Digital Signature

Digital Signature

Public Key Private Key

A digital signature provides authentication and validation as normal signatures do.

It ensures the security and integrity of data recorded on the Blockchain.

It uses asymmetric cryptography in which information can be shared using a public key.

Primary keys are linked to users providing digital signatures a quality of nonrepudiation.
Digital Signature Creation

Hash
1100111001 Encryption
Algorithm 1100111001
Hash
Digitally
Private Signed
Key Document
Signer
Network

Hash 1100111001 Signature is


Algorithm valid when
Hash hash values
1100111001 are equal
Decryption 1100111001
Digitally Signed Hash Verifier
Document
Public Key
Assisted Practice Duration: 5 mins

Generation of a Public/Private Key Pair and a Digital Signature

Problem Statement: You are given a task to generate a public key and a digital signature
containing a message.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. Enter the username and
password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/public-private-keys/keys.html

Step 02 Click on the random button to generate public and private key

Step 03 Visit https://anders.com/blockchain/public-private-keys/signatures.html

Step 04 Enter a message, and click on sign button to generate a digital signature

Step 05 Click on verify tab to verify the digital signature created


Overview of Blockchain
Transaction Broadcast
Features of Blockchain

Cryptography Decentralized Consensus Distributed


Algorithm Network Algorithm Ledger

It is a system where miners play an important role in the validation of transaction taking place.
Types of Network

Centralized Network

Decentralized Network
Types of Network

Centralized Network

Decentralized Network
Overview of Blockchain
Transaction Validation
Features of Blockchain

Cryptography Decentralized Consensus Distributed


Algorithm Network Algorithm Ledger

Miners will validate the transaction using mathematical puzzles.


Consensus Protocol

It is a fault-tolerant protocol that is used to achieve the necessary agreement on a single data value or a
single state of network.

It is a set of rules that decides on the contribution of the various participants of the Blockchain.

It ensures that all transactions occurring on the network are genuine and all participants agree on the
consensus of the ledger.
Blockchain Protocols
Features of Consensus Protocol

Efficient Secure

Real-time Reliable Functional


Role of Miner

Validates and processes


transaction

Requests transaction Transaction processed


Miner

Node 1 Node 2
Proof of Work
Proof of Work

Nonce

Hash

Transaction
Nonce

A random number whose value is set so that the hash of the block will contain a run of leading zeros.

Block #248 New Block


Prev Block Hash: Prev Block Hash:
#65A… #78E…
Transaction: Transaction:
Txn 673… Txn 725…
Txn a63… Txn 434…
Random number (guess) : Random number (guess) :
2435681 6873838

#78E…
Assisted Practice Duration: 5 mins

Generation of a Nonce Value

Problem Statement: You are given a task to generate a nonce value.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/block.html

Step 02 Enter some data in the data field, and click Mine

Step 03 Observe the generation of new nonce value


Hash Code

• The code generated by taking an input and converting it to cryptographic output using
mathematical algorithm is hash code.
• H(x) is the hash of x.

Unique Value Fast Production

Data
Security
with Hash

Unpredictable High Transaction Cost


Assisted Practice Duration: 5 mins

Generation of a Hash Code

Problem Statement: You are given a task to generate a hash code.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/hash.html

Step 02 Enter some data in the data field

Step 03 Observe the generation of hash value for the date


Hash Pointer

• Hash pointer is a pointer to the location where information or hash of that information is
stored
• If we retrieve information that the pointer points at, we can get hash of the information
and confirm it to be unchanged
• It requires information of previous hash

H( )

prev: H( ) prev: H( ) prev: H( )

data data data


Proof of Stake

A low cost, low energy consuming algorithm which states that a person can mine and validate transaction
based on how many coins he or she holds.
Proof of Elapsed Time

Consensus algorithm prevents high energy consumption and resource utilization following a lottery
system.

Each participant in the network is required to wait. One who completes the
waiting time is the winner.

Winner
PBFT

Practical Byzantine Fault Tolerance (PBFT) improves the robustness and performance of transaction by
directing peer-to-peer messages with minimal latency.

PRACTICAL BYZANTINE FAULT TOLERANCE

CONFIGURES
DEPLOYED TO AND
AND OPERATES
EXECUTED ON
PEER NODES

BLOCKCHAIN
OPERATOR
SMART CONTRACT

INVOKE
SMART
CONTRACT PEER
Exact network structure depends
on the consensus mechanism.
PBFT has a leader, validating and
non-validating peers

APPLICATIONS Consensus messages flow between the


appropriate peers to ensure that the
CONSENSUS Blockchain SC transactions are kept in
NETWORK Order.
Overview of Blockchain
Block Creation
Blockchain Block Structure
Assisted Practice Duration: 5 mins

Generation of a Blockchain Block

Problem Statement: You are given a task to generate a Blockchain block.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/block.html

Step 02 Input any arbitrary data in the data field, and mine the block

Step 03 Observe the structure of the generated block.


Blockchain Header

Field Description Size


Magic number Value always 0xD9B4BEF9 4 bytes

Block size Number of bytes 4 bytes

Block header Consists of six items 80 bytes

Transaction counter Positive integer VI = VarInt 1-9 bytes

Transaction The non-empty list of Depends on the number


transactions of transactions
Blockchain Identifiers: Block Header

Primary identifier of a block

Digital fingerprint, twice the size of block header

Unique identification of a block

32-byte hash
Blockchain Identifiers: Block Height

Position of the block in Blockchain

The first block is of height 0

Each node dynamically identifies a block


Blockchain Merkle Tree

Data structure used for summarizing and verifying the integrity of large sets of data. It is also known as
Binary Hash Tree.

Merkle Root
HABCD
Hash(HAB + HCD)

HAB HCD
Hash(HA + HB) Hash(HC + HD)

HA HA HC HD
Hash(TxA) Hash(TxB) Hash(TxC) Hash(TxD)
Advantages of Merkle Tree

Less memory required Integrity

Proofs are computed quickly


and easily Advantages

Provides validation of data Less information required


Overview of Blockchain
Transaction Record
Features of Blockchain

Cryptography Decentralized Consensus Distributed


Algorithm Network Algorithm Ledger

Blockchain stores records of each transaction in the distributed ledger.


Evolution of Distributed Ledgers
Distributed Ledger

Ledgers store the copy of transactions that have happened. Every single person of the network has a
copy of the ledger.

John Kat
John = 3 BTC John = 3 BTC
John -> Kat 3 BTC John gives 3 BTC to Kat John -> Kat 3 BTC
Kat -> Peter 2 BTC Kat -> Peter 2 BTC
Peter -> Susan 1 BTC Peter -> Susan 1 BTC

Kat gives 2 BTC to Peter

John = 3 BTC John = 3 BTC

John -> Kat 3 BTC Peter gives 1 BTC to Susan John -> Kat 3 BTC

Kat -> Peter 2 BTC Kat -> Peter 2 BTC

Peter -> Susan 1 BTC Peter -> Susan 1 BTC


Susan Peter
Assisted Practice Duration: 5 mins

Working of a Distributed System

Problem Statement: You are given a task to demonstrate the working of a distributed
system.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/distributed.html

Step 02 Note the hash value of Block 1–Peer A

Step 03 Enter data in the data field of Peer A, click Mine, and note the hash
value

Step 04 Enter data, and mine the other blocks of Peer A

Step 05 Verify if the hash of previous block is same in the next


Features of Blockchain in Transaction Process

The diagrams shows the usage of Blockchain features in every step of the Blockchain transaction process.

Decentralized System Validation by Miner

Cryptographic
Algorithm
Block Creation

Distributed Ledger Proof of Work


Assisted Practice Duration: 5 mins

Working of a Blockchain Transaction

Problem Statement: You are given a task to demonstrate the working of a Blockchain
transaction.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/blockchain.html

Step 02 Enter any data in the data field, and observe the change in hash

Step 03 Change the information in any block, and observe the change in hash
value

Step 04 Observe how the hash values change in the subsequent blocks
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/tokens.html

Step 02 Change any value of the token in any of the blocks

Step 03 Mine the block, and observe change in the hash value
Assisted Practice: Steps

Step 01 Visit https://anders.com/blockchain/coinbase.html

Step 02 Transfer money from Ander’s account to four different accounts

Step 03 Observe the Coinbase transaction, and check if the accounts have money
to transfer
Overview of Blockchain
Types of Blockchain
Types of Blockchain

Public

Bitcoin Ethereum Dash Factom


Private

Ledgers are publicly available to verify or add blocks to the Blockchain

Consortium
Types of Blockchain

Public

Private

Only authorized users can add or verify the blocks, but anyone can view it

Consortium
Types of Blockchain

Public

Hyperledger 1.0 R3 Ripple


Private

Semi-centralized Blockchain in which only predefined set of nodes has


permission to write the block
Consortium
Overview of Blockchain
Blockchain Platforms, Application Components, and Templates
Blockchain Platforms

Based on Proof of Work Pluggable frameworks

Federated consensus
Cross-border payments mechanism
Blockchain Platforms

More than 185 collaborating Backs nano payments


companies

High degree of authority Majority voting consensus


mechanism
Blockchain Application Components

Node Application
Shared Ledger
Each node has to install
Components A ledger is managed inside
and run a computer
the node application
application definitive to
whose contents can be
the ecosystem. viewed once the
01 02
application is running.

04 03
Virtual Machine
Consensus Algorithm
An abstraction of
It provides the rule for how
instruction-operated
the ecosystem will arrive at
machine implemented
a single view in a ledger,
as a part of node
and how it will be
application.
implemented as a part of
node application.
Blockchain Application Templates

Many-to-One One-to-One
Used for applications Used for applications
where a user sets up the which involve financial
contracts for a specific contracts between two
purpose. entities.

Types of Templates
Key Takeaways

You are now able to:

Describe the Blockchain transaction process

Generate a public key and a digital signature

Generate a nonce, a hash code, and a Blockchain block

Work with a distributed system and perform Blockchain transaction


Knowledge Check
Knowledge
Check
In which algorithm is the peer-to-peer message directed with minimal latency?
1

a. Proof of Work

b. Proof of Stake

c. Practical Byzantine Fault Tolerance

d. Proof of Elapsed Time


Knowledge
Check
In which algorithm is the peer-to-peer message directed with minimal latency?
1

a. Proof of Work

b. Proof of Stake

c. Practical Byzantine Fault Tolerance

d. Proof of Elapsed Time

The correct answer is c

PBFT improves the robustness and performance by directing peer-to-peer messages with minimal
latency.
Knowledge
Check What is the code generated by taking an input and converting it to cryptographic
2 output using mathematical algorithm?

a. Pseudo code

b. Hash code

c. ASCII code

d. Binary code
Knowledge
Check What is the code generated by taking an input and converting it to cryptographic
2 output using mathematical algorithm?

a. Pseudo code

b. Hash code

c. ASCII code

d. Binary code

The correct answer is b

Blockchain uses Hash code for mathematical algorithms such as Proof of Work.
Knowledge
Check
What is a miner?
3

a. An algorithm that predicts the next part of the chain

b. A type of Blockchain

c. An application that processes and validates Blockchain transactions

d. A person doing calculations to verify a transaction


Knowledge
Check
What is a miner?
3

a. An algorithm that predicts the next part of the chain

b. A type of Blockchain

c. An application that processes and validates Blockchain transactions

d. A person doing calculations to verify a transaction

The correct answer is c

Miner is an application that performs the validation of the transaction using consensus algorithm.
Knowledge
Check
Which algorithm prevents resource utilization following a lottery system?
4

a. Proof of Work

b. Proof of Stake

c. Proof of Elapsed Time

d. Practical Byzantine Fault Tolerance


Knowledge
Check
Which algorithm prevents resource utilization following a lottery system?
4

a. Proof of Work

b. Proof of Stake

c. Proof of Elapsed Time

d. Practical Byzantine Fault Tolerance

The correct answer is c

Proof of Elapsed Time increases the efficiency of the process by preventing resource utilization.
Knowledge
Check What is the random number called whose value is set so that the hash of the block will
5 contain a run of leading zeros?

a. Hash code

b. Hash pointer

c. Binary code

d. Nonce
Knowledge
Check What is the random number called whose value is set so that the hash of the block will
5 contain a run of leading zeros?

a. Hash code

b. Hash pointer

c. Binary code

d. Nonce

The correct answer is d

Nonce is used to hash the block so that it will contain a run of leading zeros.
Lesson-End Project Duration: 10 mins

Creating a Blockchain Network

Problem Statement:
You are an employee of Simplilearn and have been asked to create a Blockchain network
to demonstrate the working of Blockchain. You have to perform the following actions:
∙ Create blocks for the existing peer
∙ Create another peer and blocks for the same
∙ Connect the newly created peer with the existing peer

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the
username and password that is generated. Click on the Launch Lab button. On the page
that appears, enter the username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 2: Bitcoin Blockchain

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Explain Bitcoin and ways to procure it

Set up a Bitcoin wallet

Identify where to spend Bitcoin

Describe the transaction structure of Bitcoin Blockchain

Interpret the role of Bitcoin Scripts in transactions

Explain the network and nodes in Bitcoin

Identify the steps involved in Bitcoin mining


Bitcoin Blockchain
Bitcoin and Ways to Acquire Them
Introduction to Bitcoin

Bitcoin was the first digital currency that facilitated instant transfer of value
across the world.

Transaction Management: Two major


1 2
Currency generation:
transferring the coins from operations in regulating the monetary value
one address to another
Bitcoin system
Bitcoin Controlled Supply

Bitcoin supply is limited for the currency


to have value

The rate of block creation is adjusted every


2016 blocks

The number of Bitcoins generated per block


decreases by 50% every 210,000 blocks
Ways to Get Bitcoins

• Create an account on an online exchange


Buying online
• Exchanges are used to buy and sell Bitcoins on your behalf

Business
Analyst • Choose a purchase method

Buying with • Platforms like LocalBitcoins will help you find people near you
cash who are willing to exchange Bitcoins for cash
• There are ATMs that send Bitcoins to your wallet in exchange for cash
Buying Bitcoin from an Exchange

Follow this basic rundown to buy Bitcoin from an exchange:

Choose an exchange by entering your country of residence and then


select from the list of exchanges

Step 1: Choose an exchange


Set up an account on the exchange. Various forms of identification are
required depending upon the exchange
Step 2: Set up account

Connect one or more bank accounts to your exchange account for


Step 3: Connect bank account buying or selling Bitcoins

Step 4: Select amount


Select an amount of Bitcoins to purchase, enter your Bitcoin address,
confirm purchase
Best Bitcoin Exchanges

Coinbase SpectroCoin Indacoin


One of the world’s largest Bitcoin Quick and easy exchange offering Let’s you buy Bitcoins and 700
exchanges more than 20 payment options other coins with Visa & Mastercard

Kraken LocalBitcoins
Best exchange for deposit and An escrow service that helps match
purchase of Bitcoins on same day Bitcoin buyers and sellers
Bitcoin Blockchain
Bitcoin Wallets and Ways to Set Them Up
Wallets

Bitcoins wallets are digital wallets where private keys are used to
access the Bitcoin address and signature for transactions
Types of Bitcoin Wallets

Software Wallets Web Wallets Hardware Wallets

Software wallets are Online wallets are Hardware wallets are


installed on your convenient, because used to store private
computer to store you can access your keys on storage devices
your private keys funds from any device such as USB drives

Brain Wallets Mobile Wallets

Computer creates a Mobile wallets run as


passphrase that user apps storing your
commits to memory private keys to pay
directly from your
phone
Best Bitcoin Wallets

Software Wallets Web Wallets Hardware Wallets Mobile Wallets


Assisted Practice Duration: 15 mins

Bitcoin Wallet

Problem Statement: Set up a web wallet and software wallet for a Bitcoin transaction.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Bitcoin Blockchain
Examples of Where to Use Bitcoins
Spending Bitcoins

Spending Online Spending Offline

• Common household items: There • Food: You can buy food with
are millions of products you can Bitcoins now. There is a coffee
buy using Bitcoins shop in Prague that only accepts
• Gift cards: You can buy gift cards Bitcoins
online using Bitcoins • Travel: Pay for hotel bookings
• Video games: Companies have online using Bitcoins. Also, you
started offering games and other can buy tickets of ships, cruises,
apps in Bitcoins flights
Places to Spend Bitcoins

Overstock.com Shopify stores CheapAir


First big online retailer to An e-commerce platform Choose your flights and
accept Bitcoins where you can pay in pay in Bitcoins for flying
Bitcoins with CheapAir

Expedia eGifter Reeds jewelry Inc.


Expedia provides the A popular gift card site American Jewelers where
option to pay for their hotel accepting Bitcoins as you can purchase jewelry
bookings with Bitcoins payments with Bitcoins

Newegg Dish Microsoft


An electronic retail giant Satellite TV and internet You can use Bitcoins to

that accepts Bitcoin provider that started deposit funds into your
accepting Bitcoin payment Microsoft account
in 2014
Bitcoin Blockchain
Transaction Structure
Transaction in Bitcoin System

Scenario: Ross wants to send 5 BTC to Joey

Here’s how the transaction happens:

Step 1: Joey shares his address with Ross

Step 2: Ross creates a transaction message and adds Joey’s address and 5 BTC to it

Ross then signs the transaction with his private key and shares his public
Step 3: key to the network for signature verification

Step 4: Ross broadcasts the transaction on the Bitcoin network

Ross Joey
Double Spending Problem

Scenario: If Joey uses his BTC in more than one transaction

Rachel

Joey
Address: 5BTC

Monica

Spending the same Bitcoins in more than one transaction is called


double spending problem
Encountering Double Spending in Blockchain

The security measures which prevent double spending in Blockchain:

Transaction details are sent to all or as many nodes


in the network

Blockchain is constantly growing, and each peer


maintains their copy of Blockchain

Blockchain ensures that any modification in the block


will lead to recomputing of the following blocks

Anyone can validate the transactions and this


validation prevents double spending
Blockchain
Network
Pseudonymity in Bitcoin

Pseudonymity is the near-anonymous state in which users have


disguised identities and do not disclose their true identities

• Bitcoin is a permissionless Blockchain where


you don’t need to set up an account
• The public and private keys are generated by
the wallet
• The address acts as an identifier or
pseudonym of a user’s transaction
Bitcoin Addresses

Bitcoin address
The Bitcoin address corresponds to a public
key based on ECDSA(Elliptic Curve Digital
Signature Algorithm) used in Bitcoin

Here is a sample Bitcoin address:


1PHYrmdJ22MKbJevpb3MBNpVckjZHt89hz

A wallet can have many such addresses and


can be used for transactions

Example of a Blockchain wallet


Bitcoin Transactions: UTXOs

UTXO or Unspent Transaction Output is the fundamental building block of Bitcoin.


Bitcoin Transaction Structure

A Bitcoin transaction has three pieces of information:


1. Input: This is a record of which Bitcoin address was used to send the Bitcoins to
receiver in the first place
2. Amount: This is the amount of Bitcoins that sender sends to the receiver
3. Output: This is sent to sender’s address as change

2. Amount

5BTC In Out 2BTC


sender address receiver address

3. Output

1. Input 3BTC
Out Change sent
to sender’s
address
Bitcoin Transactions and Input/Output

Transaction structure in Bitcoin reflects double-entry bookkeeping

TX 1 TX 3
TX 1
Input()
TX 0
Input()
100 BTC
Input() Output1()
Output1()

Output1() Output2()

Output2() TX 4
TX 2
Input()
Input()
Output1()
Output1()
Example of a Bitcoin Transaction
Bitcoin Blockchain
Scripts in Bitcoins
Bitcoin Script: Features

All Bitcoin transactions have scripts embedded into their inputs and outputs

• Bitcoin Script is a stack-based programming language like Forth


• A list of instructions are recorded with each transaction
• Operations in Bitcoin are composed of opcodes
• Bitcoin Script describes how the person can access the Bitcoins if
they want to spend them
• Bitcoin Script is turing incomplete
Bitcoin Script: An Example

Scenario: Joey verifies the transaction is initiated by Ross

1 Transaction from Ross is initiated ( )

Ross Joey
Bitcoin Script: An Example (Contd..)

Bitcoin transfers scripts instead of signature and the public key

scriptSig, scriptPubKey

Ross Joey

Joey can spend the Bitcoins only if both the scripts


return true after execution
Bitcoin Script Construction

18E14A7B6A30…
Transaction Input scriptSig:
D61967F63C7DD…

OP_DUP
OP_HASH160
Transaction Output scriptPubKey: PubKHash
OP_EQUALVERIFY
OP_CHECKSIG

Unlocking Script Locking Script


(scriptSig) (scriptPubKey)

<sig> <PubK> DUP HASH160 <PubKHash> EQUALVERIFY CHECKSIG

Unlock script is Lock script is found in a transaction output and is the encumbrance
provided by the that must be fulfilled to spend the output
user to resolve the
encumbrance
Bitcoin Script Instructions

• Bitcoin scripting language is small


• It consists of 256 opcodes out of which 15 are disabled and 75 are reserved
• Each instruction is given one byte

• Opcodes have the following: constants, flow control, stack, bitwise logic,
arithmetic, crypto, locktime, pseudo-words, reserved words
Evaluating Bitcoin Transaction Script

A step-by-step execution of the


combined script which will prove
this is a valid transaction
Evaluating Bitcoin Transaction Script(Contd..)

Since the script returns true, the


transaction is valid
Bitcoin Blockchain
Bitcoin Nodes and Network
Bitcoin Network

• Bitcoin is an ad-hoc network with random topology


• The protocol runs on TCP 8333
• All the nodes are treated equally in Bitcoin network
• New nodes can join the network anytime, and the
nonresponsive nodes are removed after 3 hours
Bitcoin Network Node

Nodes in the Bitcoin network may take on different roles


depending on the functionality they support

A full Bitcoin node is a collection of four


functions:

Wallet Miner

Full Node

Full Blockchain Network routing node


Types of Bitcoin Nodes
Network Network Pool
Full Stratum
Routing Routing Miner Miner
Blockchain Node Server
Node Node

Contains a full Blockchain database Contains a wallet and a network Contains a mining function without a
and network routing node on the node on the Bitcoin p2p protocol Blockchain but with a Stratum protocol
Bitcoin p2p network without a Blockchain node or other pool mining protocol nodes

Wallet

Walle
t

Gateway routers connecting the Bitcoin


Contains a wallet, miner, full Blockchain Contains a mining function with a full Contains a wallet and a network node
p2p network to nodes running other
database, and network routing node on copy of the Blockchain and a Bitcoin p2p on the Stratum protocol without a
protocols such as pool mining or
the Bitcoin p2p network network routing node Blockchain
Stratum nodes
Network Network
Full Full
Wallet Miner Routing Miner Routing Stratum
Node
Blockchain Blockchain Wallet Node
Node
Joining Bitcoin Network

There are certain special nodes in the Bitcoin network called seed nodes
which have the list of addresses

Give me the
Seed node address

Joining nodes ask for the list of


addresses from the seed node
Joining Bitcoin Network

In response to the node’s request to join the network, the


seed node sends them the address list

<Address
list>

Seed node
Joining Bitcoin Network

The joining node picks up an address from the list and joins the network

Seed node

Newly joined
node
Joining Bitcoin Network

The newly joined nodes then get the most recent Blockchain from its peers

Seed
Seednode
node

Receives an
updated copy of
Blockchain
Bitcoin Blockchain
Mining in Bitcoin Blockchain
Bitcoin Mining Process

Bitcoins are created by the process of mining

Following are the steps in Bitcoin mining: 04

03 Independent selection by
every node of the chain with
02 Independent confirmation most cumulative computation
of new blocks by each node
01 Independent aggregation of
transactions into new
Autonomous check of blocks
every transaction
Bitcoin Mining Process

Autonomous check of every


transaction

Independent aggregation of
transactions into new blocks

Independent confirmation of
new blocks by each node

Independent selection by every


node, of the longest chain

▪ Each Bitcoin node that gets the transaction will initially verify the transaction
▪ Every node confirms each transaction against a long agenda of criteria
Bitcoin Mining Process

Transactions that can further be relayed:

Autonomous check of every


transaction

Independent aggregation of
transactions into new blocks

Independent confirmation of
Ross
new blocks by each node

Independent selection by every


node, of the longest chain
Bitcoin Mining Process

Miner nodes aggregate the transactions in a candidate block

TX1 TX2 … Tx3

Transaction
Autonomous check of every Mining pool
transaction nodes

Independent aggregation of
transactions into new blocks TX1 TX3 … Tx6
TX1 TX4 … Tx5

Independent confirmation of
new blocks by each node
TX1 TX2 … Tx3

Independent selection by every


node, of the longest chain
• Each node fabricates a pool of valid, however, unconfirmed transactions known as the
transaction pool, memory pool or mempool
• Unlike other nodes, miner node will then aggregate these transactions into a candidate block
Bitcoin Mining Process

As miner node is mining, it


While miner node was searching
Miner node is listening for receives block (say 273816)
for a solution to block (273816) ,
transactions trying to mine a new through the Bitcoin network. The
it was also collecting transactions
block and also listening for blocks arrival of this block signifies the
in preparation for the next block
Autonomous check of every discovered by other nodes end of the competition for the
(273817)
block
transaction

Independent aggregation of
transactions into new blocks Upon receiving block (273816) and
validating it, miner node will also Whatever transactions remain in
By now it has collected a few
check all the transactions in the the memory pool are
hundred transactions in the
Independent confirmation of memory pool and remove any unconfirmed and are waiting to
memory pool
that were included in block be recorded in a new block
new blocks by each node (273816)

Independent selection by every


node, of the longest chain Miner node immediately
constructs a candidate for block The block becomes valid only if
(273817). This block is called a the miner succeeds in finding a
candidate block because it is not solution to the proof of work
yet a valid block, as it does not algorithm
contain a valid proof of work
Bitcoin Mining Process

Miner nodes start solving the mining puzzle:

• Mining node constructs the block header using the following fields: version, Merkle root,
Autonomous check of every previous block hash, difficulty target, nonce
transaction
• The goal is now to find a value for the nonce that results in a block header hash that is less
Independent aggregation of than the difficulty target
transactions into new blocks
Block N-1 Block N Block N+1
Independent confirmation of
new blocks by each node Header Hash Header Hash Header Hash

Independent selection by every Version Merkle Root Version Merkle Root Version Merkle Root

node, of the longest chain


Hash of Block N-2 Hash of Block N-1 Hash of Block N

Difficulty Difficulty Difficulty


Nonce Nonce Nonce
target target target
Bitcoin Mining Process

Autonomous check of every


transaction New
New
Block
Block
Independent aggregation of Miner has
successfully mined
transactions into new blocks New the block
Block
Independent confirmation of
new blocks by each node
New
Independent selection by every Block
node, of the longest chain New
Block
Bitcoin Mining Process
Since miners use their valuable resources to validate the block, they
are given a monetary award

Autonomous check of every


transaction

Independent aggregation of
transactions into new blocks

Independent confirmation of
new blocks by each node Electricity Computational Monetary Reward
Work
Independent selection by every
node, of the longest chain

• Successful miner is rewarded with newly created Bitcoins


• The block reward is halved every 210,000 blocks or every four years
Bitcoin Mining Process

Autonomous check of every


transaction
• In Bitcoin’s consensus mechanism, each new block is
Independent aggregation of
transactions into new blocks
validated independently by every node on the network
which ensures that only valid blocks are propagated on
Independent confirmation of
new blocks by each node
the network

• Nodes validate the block by checking it against a long list


Independent selection by every
node, of the longest chain of criteria that must be met
Bitcoin Mining Process

Assembling and selecting chains of blocks:

Autonomous check of every


transaction

Independent aggregation of
transactions into new blocks

Independent confirmation of
new blocks by each node

Independent selection by every


node, of the longest chain

In the network shown above, once the node(in orange color) validates the block, it assembles
the chain by connecting the block in the existing Blockchain
Bitcoin Mining Process

Bitcoins are thus assembled in the longest chain

Autonomous check of every


transaction

Independent aggregation of • By choosing the greatest difficulty chain, all nodes in the long run accomplish a wide
transactions into new blocks consensus
• Brief errors between chains are settled in the long run as more proof of work is included
Independent confirmation of
broadening one of the conceivable chains
new blocks by each node
• Mining nodes vote with their mining power by picking which chain to extend by mining the
Independent selection by every next block
node, of the longest chain
Key Takeaways

You are now able to:

Explain the term Bitcoin and ways to procure them

Set up a Bitcoin wallet

Identify where to spend Bitcoin

Describe the transaction structure of Bitcoin Blockchain

Interpret the role of Bitcoin Scripts in transactions

Explain the network and nodes in Bitcoin

Identify the steps involved in Bitcoin mining


Knowledge Check
Knowledge
Check
How many Bitcoins will ever be created in the network?
1

a. Unlimited

b. 77340109

c. 21000000

d. 210000000
Knowledge
Check
How many Bitcoins will ever be created in the network?
1

a. Unlimited

b. 77340109

c. 21000000

d. 210000000

The correct answer is c

Bitcoin supply is controlled to have a value, hence the Bitcoin protocol is hardbound to have a
maximum supply of 21000000 BTC.
Knowledge
Check
What is a Bitcoin address?
2

a. Hash of a public key

b. Hash of private key

c. Hash of public key and private key together

d. A random hash code


Knowledge
Check
What is a Bitcoin address?
2

a. Hash of a public key

b. Hash of private key

c. Hash of public key and private key together

d. A random hash code

The correct answer is a

A Bitcoin address is a 160-bit hash of the public portion of a public/private ECDSA key pair.
Knowledge
Check
Which of these is not a part of block Metadata?
3

a. Version

b. Merkle Root

c. Nonce

d. Block Header
Knowledge
Check
Which of these is not a part of block Metadata?
3

a. Version

b. Merkle Root

c. Nonce

d. Block Header

The correct answer is d

Block header is the resultant hash of the combination of version, merkle root, nonce, previous
block hash.
Knowledge
Check
How often does a block reward halve?
4

a. After 100,000 blocks or eight months

b. Every 210,000 blocks or every four years

c. It never halves

d. Every 25,000 blocks or six months


Knowledge
Check
How often does a block reward halve?
4

a. After 100,000 blocks or eight months

b. Every 210,000 blocks or every four years

c. It never halves

d. Every 25,000 blocks or six months

The correct answer is b

Reward schedule was set in the Bitcoin protocol at the time of genesis which says that the reward
started at 50 BTC halves every 210,000 blocks.
Knowledge
Check
Which port is used by Bitcoin clients to connect to other Bitcoin nodes?
5

a. TCP 8080

b. TCP 8200

c. TCP 8333

d. TCP 992
Knowledge
Check
Which port is used by Bitcoin clients to connect to other Bitcoin nodes?
5

a. TCP 8080

b. TCP 8200

c. TCP 8333

d. TCP 992

The correct answer is c

By default, Bitcoin clients connect to other bitcoin nodes on TCP port 8333.
Lesson-End Project Duration: 10 mins

Generate a Bitcoin Wallet

Problem Statement:
You are an employee of Simplilearn and have been asked to create a Bitcoin wallet for the
company. You have to perform the following actions:
• Generate a single wallet
• Generate a paper wallet with a passphrase
• Check wallet details

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the
username and password that is generated. Click on the Launch Lab button. On the page
that appears, enter the username and password in the respective fields, and click Login.
Lesson-End Project Duration: 10 mins

Work with BitPay Wallet

Problem Statement:
You are an employee of Simplilearn and have been asked to create a BitPay wallet
account for the company and use it to test Bitcoins. Download the BitPay wallet to get test
Bitcoins in your wallet.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the
username and password that is generated. Click on the Launch Lab button. On the page
that appears, enter the username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 3: Ethereum

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Describe Ethereum and its concepts

Install Geth and Ganache on your computer

Use MetaMask and connect it with Ganache

Install and use Mist Wallet


Ethereum
Ethereum and Its Concepts
Ethereum

Ethereum is a decentralized platform that runs the smart contracts without any downtime, fraud, and
third-party interference and also has its own cryptocurrency called Ether.
Features of Ethereum

Secured Community Corporate Friendly

Assets Fast Uncensored


Gas in Ethereum

Gas is the fundamental block of Ethereum ecosystem that is paid for every operation performed on
Ethereum Blockchain.

Its price is expressed in ether, and the miner decides whether to refuse the transaction process or not
based on the expected gas price.
Gas in Ethereum
Transaction to call function
‘doMath’

gasPrice
300 Network

doMath Function
gasLimit
20
ADD Costs 3 gas

SUBTRACT Costs 5 gas

MULTIPLY Costs 5 gas

EQ Costs 3 gas

Need 14 gas
Ether

Ether is a necessary element needed for operating the Ethereum platform.

• An incentive that the client of the


platform pays to execute requested
operations ETHER

• It ensures that the developers write The crypto-fuel


error-free codes, because for the Ethereum
unnecessary codes will increase the network
cost
Bitcoin vs. Ether

Bitcoin Ether

Uses secure hash algorithm (SHA-256) Uses ethash algorithm

Used for purchasing goods and services Used for making decentralized apps

$8500 is the price at the moment $520 is the price at the moment

A currency created to compete against the A token created for facilitating smart
gold and flat currencies contracts

Transaction speed is measured in minutes Transaction speed is measured in seconds


Ethereum Wallets

The place to securely store the ether is called wallets.

Desktop Wallet

Paper Wallet Mobile Wallet

Hardware Wallet
Ethereum Virtual Machine

Ethereum Virtual Machine (EVM) is an engine which executes translation code. Smart contracts are
compiled into bytecode which an EVM can read and execute.

Value Value

Received 5
Pays 5 ETH EVM Wallet Wallet
ETH

Data Distributed Network Data


Ethereum Languages

Contracts are compiled into EVM bytecode and deployed to Ethereum Blockchain for execution.

Solidity Serpent
Similar to C and JavaScript Similar to Python

LLL Mutan
Low-level Lisp-like Language Go-based language

Vyper Julia
Derived from Python Intermediate language for
different EVMs
Ethereum
Types of Ethereum Accounts
Externally Owned Accounts (EOA)

EOA is an account controlled by a private key that has the ability to send Ethers and messages from it.
Smart Contract

A code running on top of the Blockchain containing the set of rules for the nodes to agree upon so that
they interact with each other.

Automatic
Simplest form of
agreement
decentralization
enforcement

Higher degree of Turns legal obligations


security into automated processes

Eliminates the need Lowers transaction


for third-party cost
Characteristics of Smart Contract

Self-verifying Self-executing

Cost Saving Tamper Resistant


Process of Smart Contracts

An optional contract between A trigger event like an Regulators can use the
the parties is written as a code expiration date or a strike price Blockchain to understand the
into the Blockchain. The is hit, and the contract executes activities in the market while
individuals involved are itself according to the coded maintaining the privacy of an
anonymous, but the contact is terms individual’s position
made through a public ledger
Smart Contract: Example

Matches buyer with seller


Contract receives assets
Contract distributes assets

Selling house Buying house

Ownership is
undisputed
Settlement is
automated

Digital currency

Digitized land deed


EOA vs. Smart Contract

Smart Contract
Externally Owned
Account
Account
<code>
<code>
<code>

Nonce Balance CodeHash StorageRoot Nonce Balance CodeHash StorageRoot


Ethereum
Ethereum Mining
Ethereum Mining

Ethereum makes use of Proof of Work mechanism to ensure security.


The algorithm used is Ethash.

1 ETH 1 ETH

3 1 2 2
ETH ETH ETH ETH
Bob and Alice’s
Bob Alice Bob Alice
transaction is
combined with Miners will The miner Alice receives
Bob attempts what occurred validate the creates a new 1 ETH after
to send Alice 1 in the last block with new block and is transaction is
ETH block set of rewarded for it validated
instructions
Ethereum Mining

Previous State Next State

a3fa29ce: a3fa29ce:
920 eth 930 eth

bd2ba9b1: Transaction bd2ba9b1:


30 eth 20 eth
To:
a3fa19ce
From:
Bd2ba9b1

Value:
10 eth
State Storage

The states are assembled into a state tree that is linked to the account and the block.

The Ethereum includes state roots that store the root hash of the hash tree which represents
the system state when the block was created.

Block 180993 Block 180994


Prev Hash State root Tx root Receipt root Prev Hash State root Tx root Receipt root

Account 100
Account 100

50

30
Ethereum
Ethereum Ecosystem
Types of Ethereum Tools

Geth Mist Wallet

Ganache Swarm

Parity IPFS

MetaMask Whisper
Geth

Multipurpose command line tool that runs an Ethereum node implemented in Go

John’s Mac OS Ying’s Linux OS John’s Windows OS


Geth Geth Geth
San Francisco Shanghai Nairobi

Rama’s Linux OS Hugo’s Linux OS


Geth Geth
Bangalore Rio De Janeiro

Isabella’s Mac OS Mary’s Mac OS Lee’s Linux OS


Geth Geth Geth
Rome London Singapore

Ethereum Blockchain Network


Assisted Practice Duration: 10 mins

Installation of Geth

Problem Statement: You are given a task to install Geth on your computer.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Perform the following commands to install Geth:

Step 01 sudo apt-get install software-properties-common

Step 02 sudo add-apt-repository -y ppa:ethereum/ethereum

Step 03 sudo apt-get update

Step 04 sudo apt-get install ethereum


Ganache CLI

Ganache CLI is a fast and customizable Blockchain emulator which allows to make calls to Blockchain
without running the actual Ethereum node.
Assisted Practice Duration: 10 mins

Installation of Ganache

Problem Statement: You are given a task to install Ganache on your computer.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Perform the following commands to install Ganache:

Step 01 git clone


https://github.com/trufflesuite/ganache.git

Step 02 cd ganache

Step 03 npm install

Step 04 npm start


Parity

The fastest, lightest, and most secure Ethereum client that provides the core infrastructure essentials
for quick and reliable services.
Parity

Parity Console Parity Geth Your Geth Node

Geth Geth Geth Console

Parity Browser Parity Parity Geth Mist Browser

Ethereum Blockchain Network


MetaMask

MetaMask turns Google Chrome into a browser that allows the users to send and receive transactions
and also to fetch data from the Blockchain.
MetaMask Accounts

Parity Chrome Browser +


Parity Geth
MetaMask Owned MetaMask Plugin

Geth Chrome Browser +


Geth
MetaMask Owned MetaMask Plugin

Geth Chrome Browser +


Parity Parity
MetaMask Owned MetaMask Plugin

Ethereum Blockchain Network


Assisted Practice Duration: 15 mins

Transfer Ethers Using MetaMask

Problem Statement: You are given a task to connect MetaMask to Ganache and transfer
Ethers from one account to another.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Add MetaMask extension on Google Chrome

Step 02 Create two accounts on MetaMask

Step 03 Connect MetaMask to Ganache

Step 04 Send Ethers from one account to another


Unassisted Practice Duration: 10 mins

MetaMask Ether Faucet

Problem Statement: You are given a task to add Ethers to your MetaMask account using
Ether Faucet.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.

Note: This practice is not graded. It is only intended for you to apply the knowledge you have
gained to solve real-world problems.
Unassisted Practice: Steps

Step 01 Open MetaMask, and select Ropsten Test Network

Step 02 Click Deposit to add Ethers

Step 03 Under Test Faucet, click Get Ether

Step 04 Click request 1 ether from faucet

Step 05 Wait for the transaction to complete (one Ether will be added to your
account)
Unassisted Practice: Output
Mist Wallet

End-user interface for Ethereum that is developed for browsing and using Dapps

01 02
Sending and receiving
transactions Storing Ether

Applications
Creating multi-signature Deploying Smart
wallets Contracts
03 04
Mist Wallet
Assisted Practice Duration: 15 mins

Install and Use Mist Wallet

Problem Statement: You are given a task to install and use Mist Wallet on your computer.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Visit https://github.com/ethereum/mist/releases

Step 02 Download Mist wallet, and run the exe file

Step 03 Create two accounts

Step 04 Send Ethers from one account to another


Swarm

Distributed storage platform

Content distribution service

Native base layer service

Provides sufficient decentralization and redundant storage of Ethereum records to distribute


Blockchain data as well as Dapp codes
InterPlanetary File System (IPFS)

IPFS is a decentralized storage system that is not related directly to Ethereum but can be integrated with it.
Swarm vs. IPFS

Swarm and IPFS differs on the given parameters:

Status

vs.
Philosophical

Technicalities
Whisper

An identity-based communication protocol for Dapps to interact with each other

Drawbacks in Whisper

Low-level API Low bandwidth Uncertain Unreliable for


latency tracing packets
Ethereum Frameworks

Web3.js Eth.js

Types of Frameworks
Web3.js

The key connection between Ethereum network and Dapp that allows to compile, deploy, and interact
with smart contracts

compile using standalone solc

Compiling, deploying, solc


and interacting with npm pkg
solidity contracts
1.
or solidity code
compile
solidity code web3 Local Ethereum
compile using web3 complier Node’s Solc
Dapp compiled byte code
return solidity bytecode

2. generate ABI, communicate


deploy contract from bytecode, with Ethereum
and execute contract functions network to deploy
and interact with
Local Ethereum contracts
web3 make RPC Node. Ex. Geth
requests
Eth.js

A highly optimized, lightweight JS utility for Ethereum based on web.js

All the unnecessary characters are removed from the source code, and the code is reduced to 160 KB
Ethereum Development Environment

Remix IDE

Truffle

Embark
Remix IDE

A browser-based compiler and IDE that enables users to debug transactions and build Ethereum
contracts with Solidity language.

In-Browser Fake Network

“Inbox”
Instance

Deployment
Compilation to Bytecode

Contract
Source

In-Browser Fake Network


Remix IDE
Truffle

A command line tool used to write, test, and deploy contracts on any Ethereum network

Smart contract lifecycle


Automated contract testing
management

Scriptable deployment Powerful interactive console


and migrations
Truffle

Truffle

Contract
Creation

Local
Rinkeby
Testing

Deployment
Embark

An environment that allows you to easily develop and deploy decentralized applications

Performs automatic Performs test driven deployment


deployment of contracts with contracts using JavaScript

Keeps track of deployed Manages different chains like


contracts Embark testnet, private net, and livenet

Easily manages complex systems Redeploys the contracts if


of interdependent contracts any changes are done
Ethereum Networks

A node is a machine running as an Ethereum client


Node
Node

Used to store the data and transfer money

Node
Formed by combining one or more nodes

Each node contains a copy of the Blockchain Node


Node
Types of Network
Ethereum Ecosystem

Geth console Parity browser

Mist browser Geth Parity Parity

ENS
Chrome browser mycontract.eth
Geth Your deployed
pointing to your
+ MetaMask contract
(MetaMask) contract deployed
plugin address

Ethereum Network

Your contract ABI hosted on


Swarm Webapp + Web3.js hosted on
IPFS

Swarm Swarm Swarm


IPFS IPFS IPFS

Swarm Swarm Swarm


IPFS IPFS IPFS

Swarm Network Swarm Network

Ethereum Ecosystem
Ethereum
Ethereum DAPPs and DAOs
Ethereum Decentralized Application(DAPP)

Decentralized application is an application that is used on networks with trustless protocols to avoid a
single point of failure.

Uses Ethereum as Not governed by


development central server
platform

Uses There is no master


cryptographically copy of Dapp
encoded blocks
Advantages of Ethereum DAPPs

Improved stability No downtime

Higher reliability No third-party integration

Automatic credentials
Privacy and security
assigned
Examples of DAPPs
Decentralized Autonomous Organization(DAO)

DAOs are organizations designed to hold assets and use the voting system to distribute them. DAOs
exist entirely on Blockchain and are governed by the consensus protocols.

D
DAO APP

NETWORK

PEER DECISION MAKERS


Process of DAO

DAO

A DAO should be created to keep


transparency in voting
Country holds an election and wants This is ensured by embedding predefined
to prevent fraud in voting conditions in the code

Every vote is processed on the Ethereum


People eligible to vote are assigned voting
Blockchain. It ensures transparency by
tokens
allowing everything to run in a decentralized
way People start voting
Key Takeaways

You are now able to:

Describe Ethereum and its concepts

Install of Geth and Ganache on your computer

Use MetaMask and connect it with Ganache

Install and use Mist Wallet


Knowledge Check
Knowledge
Check
What is gas in Ethereum?
1

a. The cost of generating a correct block hash

b. A way of pricing transactions based on their computational complexity

c. A measurement of how many nodes are attached to the network

d. The amount of power the network requires to hash the transaction


Knowledge
Check
What is gas in Ethereum?
1

a. The cost of generating a correct block hash

b. A way of pricing transactions based on their computational complexity

c. A measurement of how many nodes are attached to the network

d. The amount of power the network requires to hash the transaction

The correct answer is b

Its price is expressed in ether, and the miner decides whether to refuse the transaction process or
not based on the expected gas price.
Knowledge
Check Which Ethereum account contains the set of rules for the nodes to agree upon so that
2
they interact with each other?

a. Externally Owned Account

b. Smart contracts

c.

d.
Knowledge
Check Which Ethereum account contains the set of rules for the nodes to agree upon so that
2
they interact with each other?

a. Externally Owned Account

b. Smart contracts

c.

d.

The correct answer is b

Smart contract contains the set of rules and can turn legal obligations into automated processes.
Knowledge
Check
Which development environment performs automatic deployment of contracts?
3

a. Remix IDE

b. Truffle

c. Embark

d. None of the above


Knowledge
Check
Which development environment performs automatic deployment of contracts?
3

a. Remix IDE

b. Truffle

c. Embark

d. None of the above

The correct answer is c

Embark is a development environment that performs automatic deployment and also keeps track
of deployed contracts.
Knowledge
Check Which Ethereum tool allows user to send and receive transactions using Google
4
Chrome?

a. Geth

b. Ganache

c. Swarm

d. MetaMask
Knowledge
Check Which Ethereum tool allows user to send and receive transactions using Google
4
Chrome?

a. Geth

b. Ganache

c. Swarm

d. MetaMask

The correct answer is d

MetaMask turns Google Chrome into a browser that allows the users to send and receive
transactions and also to fetch the data from the Blockchain.
Lesson-End Project Duration: 10 mins

Transfer Bonus Using MetaMask

Problem Statement:
You are an employee of Simplilearn and have been asked to transfer 100 Ethers from
Simplilearn account to your personal account as a part of your performance bonus. You
have to perform the following actions:
• Create two accounts, one Simplilearn account and the other one as your personal
account. Connect both with Ganache
• Transfer 100 ETH from Simplilearn account to your account

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the
username and password that is generated. Click on the Launch Lab button. On the page
that appears, enter the username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 4: Deploying Smart Contracts on Private Ethereum Network

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson you should be able to:

Set up private Ethereum Blockchain

Write Solidity programming codes

Develop and deploy smart contracts on Ethereum test network

Build an Ethereum based property transfer application

Create a marketplace application on Ethereum network


Deploying Smart Contracts on Private Ethereum Network
Private Ethereum Blockchain
Steps to Develop Private Blockchain

1 2 3 4
Install Go-Ethereum Configure new Initialize the private Create new
and Puppeth genesis block node accounts

7 6 5
Perform Create an
Start mining ethers transactions autonomous
internally private Blockchain
Genesis Block

Genesis is the first block in the chain, and it is the only block without a predecessor.

Example of Genesis.json file


Assisted Practice Duration: 15 mins
Private Ethereum Network

Problem Statement: Your organization has asked you to create a private Ethereum network developing and
deploying decentralized business applications. Develop a private Ethereum Blockchain Network.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password that
is generated. Click on the Launch Lab button. On the page that appears, enter the username and password in
the respective fields, and click Login.
Deploying Smart Contracts on Private Ethereum Network
Ethereum Smart Contracts
Smart Contract Life Cycle

Solidity code is compiled to a bytecode and is deployed to the network of nodes. Deployed code can be
interacted by calling functions using contract’s address.

Blockchain Network

Compile Deploy Interact


Solidity
Code ABI Address Functions
Bytecode 0x45d3…. Events
Smart Contract Development

Stores the ABI


Create Solidity
and contract
smart contract
address

Passes the .sol file Passes the address and


the ABI of the contract

Compile using Returns the contract Instantiates the


address and the ABI
Solidity compiler contract

Using the bytecode invokes Passes all the parameters


deployment via Web3js for the contract method

Invokes contract
Perform
methods for data
deployment
storage

Signs and passes ether to


perform the operation

Private Ethereum Blockchain Node


Assisted Practice Duration: 10 mins
Smart Contract Development Environment

Problem Statement: Set up a development environment for developing and deploying Solidity smart
contracts..

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password that
is generated. Click on the Launch Lab button. On the page that appears, enter the username and password in
the respective fields, and click Login.
Deploying Smart Contracts on Private Ethereum Network
Solidity Programming
Introduction to Solidity

● Solidity is an Ethereum smart contract language


● It is an object-oriented high-level language
● The syntax of Solidity is similar to JavaScript
● It is designed to enhance the Ethereum Virtual Machine (EVM)
● Solidity is a statically-typed scripting language where processes are
verified at compile-time
Comparison between Memory and Storage in Solidity

Memory Storage

• It is used to hold temporary


• All the contract state variables
values
reside in storage
• It is erased between external
• It is persistent between function
function calls and is cheaper to
calls and quite expensive to use
use
Layout of a Solidity Smart Contract

Source files can contain contract definitions including directives and pragma directives.

pragma Solidity ^0.4.18 //version pragma declares the


version of the compiler to be used to avoid breaking
changes introduced on future versions
contract HelloWorld{

}
General Value Types

General value types are always passed by values.

pragma Solidity ^0.4.18


contract ValueTypes{
uint x; // uint is mostly used for currency value or amount or Unix timestamp
int constant variable1 = 8; // int of 256 bit with constant value 8
int256 constant variable2 = 8; // same effect as line above, here the 256 is
explicit
uint constant VERSION_ID = 0x123A1; // A hexadecimal value stored in a constant
with 'constant', compiler replaces each occurrence with actual value
uint8 b;
int64 c;

ss
uint248 e;
int x = int(b); // Type casting
bool b = true; // or can also be declared by 'var b = true;' for inferred typing
address public owner; // Addresses - holds 20 byte/160 bit Ethereum addresses
byte a;
bytes2 b; // Bytes available from 1 to 3. byte is same as bytes1
bytes32 c;
string n= “hello”; // strings are stored in UTF8 in double quotes
}
Arrays

Arrays in Solidity can be of a fixed or dynamic size.

pragma Solidity ^0.4.0;

contract C {
function f(uint len) {
string[5] name; // array of fixed size 5 of type String
uint[] dynamicArray // dynamic array of type uint

ss
uint[] memory a = new uint[](7); // allocating memory array
bytes memory b = new bytes(len);
// Here we have a.length == 7 and b.length == len
a[6] = 8;
}
}
Arrays: Example Code

pragma Solidity ^0.4.0;

contract ArrayExample {
bytes32[5] Names;
bytes32[] examples;
uint[] myArray;
function test() constant returns (uint[]){

ss
string[5] memory inlineArray = ["You", "can", "init", "like", "this"];
uint[][5] memory multidem; // multidimensional array
myArray.push(123);
examples.push("Matt");
Names[0] = "Matt";
return myArray;
}
Enums

Enums are one way to create a user-defined type in Solidity. They are explicitly
convertible to and from all integer types, but implicit conversion is not allowed.

pragma Solidity ^0.4.0;

contract Purchase {

ss
enum State { Created, Locked, Inactive } // Enum
}
Enums: Example Code

pragma Solidity ^0.4.0;


contract test {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;

function setGoStraight() {
choice = ActionChoices.GoStraight;
}

ss
function getChoice() returns (ActionChoices) {
return choice;
}

function getDefaultChoice() returns (uint) {


return uint(defaultChoice);
}
}
Structs

Structs are custom defined types that can group several variables.

pragma Solidity ^0.4.18;


contract VotingContract {
struct Voter { // Struct
uint weight1, weight2, weight3;
bool voted;

ss
address delegate1, delegate2, delegate3, delegate4;
uint vote1, vote2, vote3, vote4, vote5;
uint height1, height2, height3 //structs can have upto 16
members. Exceeding the limit might result in error [stack too deep]
} }
Mapping
Mapping are declared as Mapping( _Keytype => _ValueType )
• _KeyType can be any type except for a dynamically sized array, a contract, an enum, and
a struct
• _ValueType can be any type, including mappings

pragma Solidity ^0.4.18;


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

function update(uint newBalance) {


balances[msg.sender] = newBalance;
}
}

ss
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}
}
Mapping: Example Code

contract MyContract {
struct Data {
uint a;
uint b;
}
mapping (uint => Data) public items;
function MyContract() {

ss
items[0] = Data(1,2);
items[1] = Data(3,4);
items[2] = Data(5,6);
delete items[1];
}
}
Function Declaration in Solidity

Examples of function declaration using pure and view keywords:

pragma Solidity ^0.4.16;


contract C { function f(uint a, uint b) public view returns (uint)
//a function declared as view cannot modify the state
{

ss
return a * (b + 42) + now;
}
}

pragma Solidity ^0.4.16;


contract C {
function f(uint a, uint b) public pure returns (uint)
{//a function declared as pure cannot read or modify the state

ss
return a * (b + 42);
}
}
Function Calls and Return Types

pragma Solidity ^0.4.0;


contract FunctionCall {
// Constructor calls are also a function calls and are defined like this
function FunctionCall(uint param1) {
// Initialize state variables here
}
// you can create a contract object with a name & then use it inside the
function calls like this
Miner m;

ss
function setMiner(address addr) {
m = Miner(addr); // type casted the addr to Miner type and stored in m
}//function setMiner(Miner _m) { m = _m; } is also correct
// Now you can use the Miner's function which is info to sent
// some ether with optionally specifying the gas like this
function callMinerInfo() {
m.info.value(10).gas(800)();
}
Function Calls and Return Types (Contd.)

function someFunction(uint key, uint value) {


// Do something }
function demoFunction() {
// named arguments
someFunction({value: 2, key: 3}); }
//also note that variable names are optional in parameters & in returns
function someFunction2(uint key, uint) returns (uint){

ss
return key; // Do something} }
contract Miner{
//The modifier payable has to be used for info,
// because otherwise, we would not be able to
//send Ether to it in the call m.info.value(10).gas(800)()
function info() payable returns (uint ret) {
return 42; } }
Fallback Function

Fallback functions are unnamed functions. These are triggered when the function signature does not
match with any of the available functions in Solidity contract.

pragma Solidity ^0.4.18;


contract FallbackExample {
function() payable {

ss
a=5;
}
}
Function Modifiers

Modifiers enable you to control the behavior of your smart contract.

function sayHello() public view returns(string) {

function multiply(uint a, uint b)private pure returns (uint) {


return a*b;
}
function increment(uint x, uint y) returns (uint x, uint y) {
x+=1;

ss
y+=1;
}
//when a function returns multiple values we need to parallel assign
(x1,y1) = increment(1,2);
Function Modifiers: Example Code

pragma Solidity ^0.4.18;

contract FunctionModifiers{
address public creator;
function FunctionModifiers(){
creator= msg.sender; }

Modifier onlyCreator(){

ss
if(msg.sender!=creator){
throw;
}
_; // resumes the function execution wherever the access modifier is used
}
function killContract() onlyCreator{ //this function will not execute if
an exception occurs
self-destruct(creator); }}
Inheritance

Inheritance is similar to any other object-oriented programming language. The new


contract inherits the functionality of the base class.

Contract A{
uint a;
function getA() public view returns(uint) {
returns a;
}
}

ss
contract B is A {
uint b;
function getBsumA() public view returns(uint) {
return b+a;
}
}
Inheritance: Example Code

pragma Solidity ^0.4.18;

contract fun {
address person;
function fInherit(){
person = msg.sender;
}
}
contract Solidity is fun{ //’is’ keyword is used for Inheritance
function kill(){

ss
self-destruct(person);} }

contract smartcontract is fun, Solidity //Multiple Inheritance


{
String public PersonName;
function smartcontract(String _name){
UserName = _name;
}
}
Abstract Contracts

Abstract contract cannot be compiled and can lack an implementation, but they
can be used as a base contract.

pragma Solidity ^0.4.18;

contract Voter {
function Ballot() returns (bytes32);
}

ss
contract Person is Voter {
function Ballot() returns (bytes32) {
Return “yes”;
}
Abstract Contracts: Example Code

pragma Solidity ^0.4.18;

contract abstractContract {
function foo(uint i) returns(uint j);
}

ss
contract newContract is abstractContract{
function foo(uint i) returns(uint j){
j=3*i;
}
}
Events

Events allow the use of EVM logging for calling front-end callbacks inside the Dapps
interface for the users to listen to the events.

contract Coin {
//Your smart contract properties...
// Sample event definition: use 'event' keyword and define the
parameters
event Sent(address from, address to, uint amount);

ss
function send(address receiver, uint amount) public {
//Some code for your intended logic...
//Call the event that will fire at browser (client-side)
Sent(msg.sender, receiver, amount);
}
}
Events: Example Code

pragma Solidity ^0.4.18;


event Voter(
string name,
uint age /* we have passed 2 types that represent name and age. When the
event is successfully returned in the UI, these values can be accessed */
);

ss
function setVoter(string _vName, uint _age) public {
vName = _vName;
age = _age;
Voter(_vName, _age); //trigger event
}
Creating Contracts Using New Operator

A contract can create a new contract using the new keyword.

Pragma Solidity 0.4.18


Contract SampleNew{

uint x;
function SampleNew(uint a) payable {
X=a;
}
}

ss
contract New {
SampleNew n= new SampleNew(4);

function createdSample(uint arg) {


SampleNew newD = new SampleNew(arg);
SampleNew newD2 = (new).value(amount)(arg);
}
}
Globally Available Variables and Functions

Following are the variables and functions that always exist in the global namespace:

• Block.blockhash(uint blockNumber): returns (bytes32): hash of the given block- only works for 256 most
recent blocks excluding current
• Block.coinbase (address): current block miner’s address
• Block.difficulty (uint): current block difficulty
• Block.GasLimit(uint): current block GasLimit
• Block.number (uint): current block number
• Block.timestamp (uint): current block timestamp as seconds since unix epoch
• msg.data(bytes): complete calldata
• msg.sender(address): sender of the message call (current call)
• msg.sig(bytes4): first four bytes of the message (current call)
• msg.value (uint): number of wei sent with the message
• now (uint): current block timestamp (alias for block.timestamp)
• tx.gasprice(uint): gas price of the transaction
• tx.origin(address): sender of the transaction (full call chain)
ERC20 Token

ERC stands for Ethereum Requests for Comments, and 20 stands for a unique ID
number to distinguish this standard from others

function transferFrom(address from, address to,


contract TokenContractFragment {
uint tokens) public returns (bool success) {
mapping(address => uint256) balances;
balances[from] =
mapping(address => mapping (address =>
balances[from].sub(tokens);
uint256)) allowed;
allowed[from][msg.sender] =
function balanceOf(address tokenOwner) public
allowed[from][msg.sender].sub(tokens);
constant returns (uint balance) {
balances[to] = balances[to].add(tokens);
return balances[tokenOwner];
Transfer(from, to, tokens);
}
return true;
ss

ss
function transfer(address to, uint tokens)
}
public returns (bool success) {
function approve(address spender, uint tokens)
balances[msg.sender] =
public returns (bool success) {
balances[msg.sender].sub(tokens);
allowed[msg.sender][spender] = tokens;
balances[to] = balances[to].add(tokens);
Approval(msg.sender, spender, tokens);
Transfer(msg.sender, to, tokens);
return true;
return true;
}
} //code continued in the second box
}
ERC20 Token: Standard Interface

contract ERC20Interface {
function totalSupply() public constant returns (uint);

function balanceOf(address tokenOwner) public constant returns (uint balance);

function allowance(address tokenOwner, address spender) public constant returns


(uint remaining);

function transfer(address to, uint tokens) public returns (bool success);

ss
function approve(address spender, uint tokens) public returns (bool success);

function transferFrom(address from, address to, uint tokens) public returns (bool
success);

event Transfer(address indexed from, address indexed to, uint tokens);

event Approval(address indexed tokenOwner, address indexed spender, uint tokens);


}
Assisted Practice Duration: 15 mins
Create a Smart Contract to Issue Your Own Digital Token

Problem Statement: Working as a software professional in a financial organization, you are required to
develop a tradable token with a fixed supply that can be utilized as a currency, share, or an asset. Develop a
smart contract to design and issue your own digital token.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password
that is generated. Click on the Launch Lab button. On the page that appears, enter the username and
password in the respective fields, and click Login.
Smart Contract to Issue Your Own Cryptocurrency

pragma solidity ^0.4.16;


interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address
_token, bytes _extraData) external; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);

ss
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
Smart Contract to Issue Your Own Cryptocurrency(Contd.)
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);

ss
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool
success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;}
Smart Contract to Issue Your Own Cryptocurrency(Contd.)

function approve(address _spender, uint256 _value) public


returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}

function approveAndCall(address _spender, uint256 _value, bytes _extraData)

ss
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
Smart Contract to Issue Your Own Cryptocurrency(Contd.)

function burn(uint256 _value) public returns (bool success) {


require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);

ss
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
Deploying Smart Contracts on Private Ethereum Network
Solidity Smart Contract Design Patterns
Important Smart Contract Design Notes

• Obfuscation: All variables are publicly viewable on Blockchain. So, anything that is private needs to be
obfuscated

• Storage optimization: Smart contract should be carefully developed because writing to Blockchain is
expensive as data is stored forever

• Cron job: Contracts must be manually called to handle time-based scheduling

• Cost of Gas: Almost every instruction in a smart contract costs gas, so always write a cost-effective smart
contract
Smart Contract Design Patterns

Design patterns are proven to be the go-to solution in addressing Ethereum smart
contract design challenges.

Following are common design patterns:

Contract Self Destruction 1 2 Factory Contract

Withdrawal 5 3 Name Registry


Pattern

4 Mapping Iterator
Smart Contract Design Patterns

Self destruction contract is used for terminating a contract, which means


removing it forever from the Blockchain.

contract SelfDesctructionContract {
public address owner;
public string someValue;
Self Destruction Contract modifier ownerRestricted {
require(owner == msg.sender);
_;
Factory Contract }
// constructor
function SelfDesctructionContract() {
Name Registry owner = msg.sender;

ss
}
// a simple setter function
Mapping Iterator function setSomeValue(string value){
someValue = value;
}
Withdrawal Pattern // you can call it anything you want
function destroyContract() ownerRestricted {
suicide(owner);
}
}
Smart Contract Design Patterns

Factory contracts are used to develop and deploy child contracts. The addresses of these child
contracts are stored in the factory and can be extracted whenever necessary.

contract CarShop {
address[] carAssets;
function createChildContract(string brand, string model) public
Self Destruction Contract payable {
// insert check if the sent ether is enough to cover the car asset
address newCarAsset = new CarAsset(brand, model, msg.sender);
Factory Contract carAssets.push(newCarAsset);
}
function getDeployedChildContracts() public view returns (address[]) {
Name Registry return carAssets;

ss
}
}
Mapping Iterator contract CarAsset {string public brand;
string public model;
address public owner;
Withdrawal Pattern function CarAsset(string _brand, string _model, address _owner)
public {
brand = _brand;
model = _model;
owner = _owner;
} }
Smart Contract Design Patterns
Name registry is useful when your contract is dependent on multiple contracts. By using name registry
pattern, you can keep the address of one contract instead of all the addresses.

contract NameRegistry {
struct ContractDetails {
address owner;
address contractAddress;
Self Destruction Contract uint16 version;
}
mapping(string => ContractDetails) registry;
Factory Contract function registerName(string name, address addr, uint16 ver) returns
(bool) {
// versions should start from 1
Name Registry require(ver >= 1);

ss
ContractDetails memory info = registry[name];
Mapping Iterator require(info.owner == msg.sender);
// create info if it doesn't exist in the registry
if (info.contractAddress == address(0)) {
Withdrawal Pattern info = ContractDetails({
owner: msg.sender,
contractAddress: addr,
version: ver
});
}
Smart Contract Design Patterns

Self Destruction Contract else {


info.version = ver;
info.contractAddress = addr;
Factory Contract }
// update record in the registry
registry[name] = info;
Name Registry

ss
return true;
}
function getContractDetails(string name) constant returns(address,
Mapping Iterator uint16) {
return (registry[name].contractAddress, registry[name].version);
}
Withdrawal Pattern }
Smart Contract Design Patterns

Mappings cannot be iterated, but it is possible to implement a data


structure with mappings.

contract MappingIterator {
mapping(string => address) elements;
string[] keys;
function put(string key, address addr) returns (bool) {
Self Destruction Contract bool exists = elements[key] != address(0)
if (!exists) {
keys.push(key);
Factory Contract }
elements[key] = addr;
return true;
Name Registry }

ss
function getKeyCount() constant returns (uint) {
return keys.length;
Mapping Iterator }
function getElementAtIndex(uint index) returns (address)
{
Withdrawal Pattern return elements[keys[index]];
}
function getElement(string name) returns (address) {
return elements[name];
}
}
Smart Contract Design Patterns

The goal of withdrawal pattern is to keep track of balances internally and force each user to
withdraw their funds immediately.

Self Destruction Contract contract WithdrawalContract {


mapping(address => uint) buyers;
function buy() payable {
Factory Contract require(msg.value > 0);
buyers[msg.sender] = msg.value;
}
Name Registry

ss
function withdraw() {
uint amount = buyers[msg.sender];
require(amount > 0);
Mapping Iterator buyers[msg.sender] = 0;
require(msg.sender.send(amount));
}
Withdrawal Pattern }
Deploying Smart Contracts on Private Ethereum Network
Solidity Smart Contract Use Cases
Assisted Practice Duration: 20 mins

Solidity Smart Contract to Develop Property Transfer System

Problem Statement: You are given a project to remove the third-party dependency for transferring the
ownership of a property from one individual to another. Create a smart contract for decentralized property
transfer system.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password that is
generated. Click on the Launch Lab button. On the page that appears, enter the username and password in the
respective fields, and click Login.
Assisted Practice: Property Transfer

Match buyer with seller


Exchange
Contract receives
assets
Possible Solution: Blockchain can be used for Contract distributes
assets
accelerating the process of property transfer.
Seller Buyer
A digital record with permanent audit trail can be
instituted, which allows the government to easily
access the chain of data corresponding to that
property.
Registry
This creates transparency in the system and reduces Ownership is
frauds. Clearance and undisputed
settlement is
automated
Assisted Practice: Guidelines For Property Transfer

You need to build a smart contract which is capable of handling property transfer with below cases:

1. Insert some dummy properties to replicate the real world. These properties shall have basic characteristics
such as address, location, floors
2. Check the ownership of property before transferring it to the other owner
3. Include as many general parameters as possible to keep the smart contract almost replicating the real-world
transaction
4. After the successful transfer of the property, you need to ensure that the old owner is not able to send the
property again
5. Finally, the new owner must be able to send the freshly received property to any owner(address)
Property Transfer: Smart Contract

pragma solidity ^0.4.18;


contract PropertyTransfer {
address public DA;
uint256 public totalNoOfProperty
function PropertyTransfer() {
DA = msg.sender;
}
modifier onlyOwner(){
require(msg.sender == DA);
_;}
struct Property{
string name;
bool isSold;
}
mapping(address => mapping(uint256=>Property)) public propertiesOwner;
mapping(address => uint256) individualCountOfPropertyPerOwner;
event PropertyAlloted(address indexed _verifiedOwner, uint256 indexed _totalNoOfPropertyCurrently,
string _nameOfProperty, string _msg);
event PropertyTransferred(address indexed _from, address indexed _to, string _propertyName, string
_msg);
function getPropertyCountOfAnyAddress(address _ownerAddress) constant returns (uint256){
uint count=0;
Property Transfer: Smart Contract(Contd.)

for(uint i =0; i<individualCountOfPropertyPerOwner[_ownerAddress];i++){


if(propertiesOwner[_ownerAddress][i].isSold != true)
count++;
}
return count;
}
function allotProperty(address _verifiedOwner, string _propertyName)
onlyOwner
{
propertiesOwner[_verifiedOwner][individualCountOfPropertyPerOwner[_verifiedOwner]++].name =
_propertyName;
totalNoOfProperty++;
PropertyAlloted(_verifiedOwner,individualCountOfPropertyPerOwner[_verifiedOwner], _propertyName,
"property allotted successfully");
}
function isOwner(address _checkOwnerAddress, string _propertyName) constant returns (uint){
uint i ;
bool flag ;
for(i=0 ; i<individualCountOfPropertyPerOwner[_checkOwnerAddress]; i++){
if(propertiesOwner[_checkOwnerAddress][i].isSold == true){
break;
}
Property Transfer: Smart Contract(Contd.)

flag = stringsEqual(propertiesOwner[_checkOwnerAddress][i].name,_propertyName);
if(flag == true){
break;
}
}
if(flag == true){
return i;
}
else {
return 999999999;
}}
function stringsEqual (string a1, string a2) constant returns (bool){
return sha3(a1) == sha3(a2)? true:false;
}
function transferProperty (address _to, string _propertyName)
returns (bool , uint )
{
uint256 checkOwner = isOwner(msg.sender, _propertyName);
bool flag;
Property Transfer: Smart Contract(Contd.)

if(checkOwner != 999999999 && propertiesOwner[msg.sender][checkOwner].isSold == false){


propertiesOwner[msg.sender][checkOwner].isSold = true;
propertiesOwner[msg.sender][checkOwner].name = "Sold";
propertiesOwner[_to][individualCountOfPropertyPerOwner[_to]++].name = _propertyName;
flag = true;
PropertyTransferred(msg.sender , _to, _propertyName, "Owner has been changed." );
}
else {
flag = false;
PropertyTransferred(msg.sender , _to, _propertyName, "Owner doesn't own the property." );}
return (flag, checkOwner);
}}
Unassisted Practice Duration: 20 mins
Decentralized Marketplace Application

Problem Statement: Centralized marketplace has issues about trusting the transacting participants. People
tend to trust sellers with reputation in the market, which makes it hard for the new sellers to do business.
Develop a smart contract for decentralized marketplace application.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password
that is generated. Click on the Launch Lab button. On the page that appears, enter the username and
password in the respective fields, and click Login.

Note: This practice is not graded. It is only intended for you to apply the knowledge you have gained to solve
real-world problems.
Unassisted Practice: Simple Marketplace Guidelines

The simple marketplace application expresses a workflow for a transaction between an


owner and a buyer.

Application Roles
Owner: A person who wants to sell in the marketplace.
Buyer: A person who wants to buy from the marketplace.

States
Item Available: Indicates that an owner has made the item they want to sell available in the
marketplace.
Offer Places: Indicates that a seller has made an offer to buy the item listed by an owner.
Accepted: Indicates that the owner has accepted the buyer's offer for the item.
Unassisted Practice: Simple Marketplace Guidelines(Contd.)

Workflow details

• Workflow starts at Item Available when an owner makes an item available for sale
• Buyer can then make an offer. This causes the state change Offer Placed
• If owner agrees to buyer’s offer then owner accepts the offer and the workflow reaches successful state
• If the owner rejects the offer state changes to itemAvailable indicating that the item is still up for sale
• The transition between the ItemAvailable and the OfferPlaced states can continue until the owner is satisfied
with the offer made

Application Roles
• Owner (O) TF: MakeOffer
• Buyer (B) AR: B TF:
Item Offer AcceptOffer
Available
Accept
Placed AIR: O
Legend
TF: MakeOffer
• TF: Transaction Function
AIR: O
• AR: Allowed Role Success State
• AIR: Allowed Instance Role
The state transition diagram below shows the
interactions among the states in this workflow
Steps for Creating a Simple Marketplace

Step 1: Open remix IDE using the browser


Step 2: Create a new file in the IDE and write the solidity smart contract
Step 3: Run the following command in a terminal to start ganache for testing and deploying your smart contract:
ganache-cli
Step 4: Now you need to start block explorer. To start block explorer, get into the directory where it is installed
and run the following command: npm start
Step 5: Click on the run tab in the remix IDE to set the environment to web3 provider. A drop-down dialog box will
appear, click ok.
Step 6: Click deploy button to deploy the contract on to your test Blockchain
Step 7: Check for the contract deployment in ganache-cli terminal
Step 8: Interact with the contract using the contract functions
A Simple Marketplace: Smart Contract
Code for step 2

pragma solidity ^0.4.20;


contract WorkbenchBase {
event WorkbenchContractCreated(string applicationName, string workflowName, address
originatingAddress);
event WorkbenchContractUpdated(string applicationName, string workflowName, string action,
address originatingAddress);
string internal ApplicationName;
string internal WorkflowName;

function WorkbenchBase(string applicationName, string workflowName) internal {


ApplicationName = applicationName;
WorkflowName = workflowName;
}
function ContractCreated() internal {
WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender);
}
function ContractUpdated(string action) internal {
WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender);
}
}
A Simple Marketplace: Smart Contract(Contd.)
Code for step 2

contract SimpleMarketplace is WorkbenchBase('SimpleMarketplace', 'SimpleMarketplace')


{
enum StateType {
ItemAvailable,
OfferPlaced,
Accepted
}
address public InstanceOwner;
string public Description;
int public AskingPrice;
StateType public State;
address public InstanceBuyer;
int public OfferPrice;
function SimpleMarketplace(string description, int price) public
{
InstanceOwner = msg.sender;
AskingPrice = price;
Description = description;
State = StateType.ItemAvailable;
ContractCreated();
}
A Simple Marketplace: Smart Contract(Contd.)
Code for step 2

function MakeOffer(int offerPrice) public


{
if (offerPrice == 0)
{
revert();
}

if (State != StateType.ItemAvailable)
{
revert();
}
if (InstanceOwner == msg.sender)
{
revert();
}
InstanceBuyer = msg.sender;
OfferPrice = offerPrice;
State = StateType.OfferPlaced;
ContractUpdated('MakeOffer');
}
A Simple Marketplace: Smart Contract(Contd.)
Code for step 2

function Reject() public


{
if ( State != StateType.OfferPlaced )
{
revert();
}
if (InstanceOwner != msg.sender)
{
revert();
}
InstanceBuyer = 0x0;
State = StateType.ItemAvailable;
ContractUpdated('Reject');
}
function AcceptOffer() public
{
if ( msg.sender != InstanceOwner )
{
revert();
}
State = StateType.Accepted;
ContractUpdated('AcceptOffer');
}}
Key Takeaways

You are now able to:

Set up private Ethereum Blockchain

Write Solidity programming codes

Develop and Deploy smart contracts on Ethereum test network

Build an Ethereum based property transfer application

Create a marketplace application on Ethereum network


Knowledge Check
Knowledge
Check
Which of the following is not a part of genesis.json file?
1

a. Gas

b. GasLimit

c. Nonce

d. Mixhash
Knowledge
Check
Which of the following is not a part of genesis.json file?
1

a. Gas

b. GasLimit

c. Nonce

d. Mixhash

The correct answer is a


Gas is calculated at the time of transaction. It is not a part of genesis file.
Knowledge
Check Smart contracts hold the potential not only to execute automated processes but also
to restrict behavior.
2

a. True

b. False

c.

d.
Knowledge
Check Smart contracts hold the potential not only to execute automated processes but also
to restrict behavior.
2

a. True

b. False

c.

d.

The correct answer is a


Smart contract can restrict behavior using function modifiers.
Knowledge
Check
Which of these programming languages is used for writing Ethereum smart contracts?
3

a. Python

b. Serpent

c. JavaScript

d. C++
Knowledge
Check
Which of these programming languages is used for writing Ethereum smart contracts?
3

a. Python

b. Serpent

c. JavaScript

d. C++

The correct answer is b


Serpent is used to write Ethereum smart contracts.
Knowledge
Check Which of these enables you to hold and secure ether and other crypto-assets built on
Ethereum as well as write, deploy, and use smart contracts?
4

a. Geth

b. Web3.js

c. Truffle

d. Mist Wallet
Knowledge
Check Which of these enables you to hold and secure ether and other crypto-assets built on
Ethereum as well as write, deploy, and use smart contracts?
4

a. Geth

b. Web3.js

c. Truffle

d. Mist Wallet

The correct answer is d


Mist wallet is a browser used to write, deploy, and use smart contract. It is also used to store
Ethereum-based crypto-assets.
Lesson-End Project Duration: 60 mins
Smart Contract for Banking Application

Problem Statement:
Write a simple bank smart contract in solidity that allows users to do the following:
∙ Deposit money into their account
∙ Withdraw money from their account
∙ Check balance
After a contract is created, deploy the contract on Ropsten network.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the
username and password that is generated. Click on the Launch Lab button. On the page
that appears, enter the username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 5: Hyperledger

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Describe Hyperledger and its architecture

Set up Hyperledger Sawtooth environment and perform transactions with it

Set up Hyperledger Iroha network and perform transactions with it

Interpret permissioned Blockchain and its consensus model


Hyperledger
Hyperledger and Its Importance
Hyperledger

“Hyperledger is an open source


collaborative effort created to
advance cross-industry
blockchain technologies. It is a
global collaboration, hosted by
The Linux Foundation,
including leaders in finance,
banking, Internet of Things,
supply chains, manufacturing,
and technology.”

Source: https://www.hyperledger.org/
Concept of Hyperledger

Hyperledger is not a Blockchain, a company, or a cryptocurrency.

Hyperledger is a software used to create one’s own personalized Blockchain service.

Used by For

Software Developers Company


Restrictions in Public Blockchain

In public Blockchain, each peer has to execute each and every transaction and run consensus
algorithm to validate it.

Not Scalable Not Confidential

Public Blockchain
Solution To The Restrictions

On Hyperledger network, only parties directly related to the transaction deal are updated on the
ledger, thus maintaining privacy and confidentiality.

Organization Payment
Supply contracts Distribution
verification verification

Only John and Kat know about the


deal

John Kat
Hyperledger Transaction

Initiate Process Membership Services Verification


Plans to send message to Kat Validates Kat’s address Results generated by both the parties
are sent to consensus cloud for
verification

John

Kat

App Query Hyperledger Process Ends


Looks for Kat’s address in Hyperledger connects both Once the transaction is
the network parties directly related to the verified from the consensus
deal cloud, Kat receives the
message
Linux Family

Hyperledger is a part of the umbrella project under Linux Foundation where a community of developers work on
open source projects.

Acumos AI

Node.js Dronecode

Hyperledger AllJoyn
Hyperledger
Hyperledger Projects
Hyperledger Umbrella Strategy

Hyperledger nurtures a lot of Blockchain frameworks and technologies under the umbrella strategy.

The Linux Foundation’s


Hyperledger Umbrella Strategy

Sawtooth Lake
Used in supply chain networks
Fabric Used in fishing industry

Used to run Ethereum smart contracts Burrow

Iroha Used in mobile application organization


Used as a decentralized identity database Indy
Sawtooth

It’s an enterprise Blockchain platform for building distributed ledger applications and networks. It keeps ledgers
distributed and smart contracts safe.

Application layer Private networks with


and core system Sawtooth permissioning
separation features

Parallel transaction Ethereum contract


execution compatible with Seth

Pluggable consensus Event system


algorithm
Assisted Practice Duration: 20 mins

Credits Exchange Using Sawtooth

Problem Statement: Simplilearn wants its participants to exchange credits. You are an
employee of Simplilearn and have been asked to set up a Sawtooth environment for this.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Set up the Sawtooth environment

Step 02 Create a participant, and sign in as existing participant

Step 03 Create an asset and a holding

Step 04 Create and accept an offer

Step 05 Chain the offers and transfer the credits directly


Hyperledger Fabric

• Allows consensus and membership services to be plug-and-play


• Leverages container technologies to host smart contracts
• Is used extensively in supply chain networks

01 02
Data protection and Confidential
consistency transaction

Benefits
No cryptocurrency Programmable
03 04
Burrow

It’s a permissioned Blockchain node built for a multi-chain universe that executes smart contracts following the
Ethereum specification. It consists of the following components:

Consensus Engine Application Blockchain


Interface (ABCI)

Permissioned
Smart Contract
Ethereum Virtual
Application
Machine

Application Binary API Gateway


Interface (ABI)
Iroha

It’s a distributed-ledger platform with open-source code written in C++, created with financial use-cases in mind.

Trusted

Simple Secure

Client-centric Portable
Source: https://iroha.tech/
Assisted Practice Duration: 20 mins

Set Up Iroha Network

Problem Statement: You are given a task to set up an Iroha network on your computer and
perform a transaction.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Install Docker, Ubuntu, and create a sample Docker network

Step 02 Add PostgreSQL to the network, and create a blockstore

Step 03 Download Iroha code from https://github.com/hyperledger/iroha --


depth=1

Step 04 Pull the Docker image, and run the Iroha Docker container

Step 05 Run Iroha, and attach Docker container to the terminal

Step 02 Launch the Iroha-CLI tool, and login as admin@test

Step 03 Perform a transaction


Indy

It’s a distributed ledger built for decentralized identity that provides tools, libraries, and reusable components for
creating digital identities rooted on Blockchain.
Hyperledger
Hyperledger Architecture
Hyperledger Blockchain Network Participants
Performs B2B
transactions

Blockchain
User

Performs Certificate Accesses security


Regulator
oversight Authority certifications

Creates Blockchain Traditional Stores access


applications Developer Database to data

Blockchain Traditional Stores access


Operates the
Development Processing to logic
Blockchain network
Network Platform
Hyperledger Architecture Components

Consensus layer Smart contract layer

Communication layer Data storage abstraction

Identity and policy services Crypto abstraction

API Interoperation
Hyperledger Architecture

APIs, SDKs, CLIs

Membership Blockchain Transactions Chaincode

Membership Blockchain Services Chaincode


Services Services
Registration Consensus Distributed Secure
Manager Ledger Container
Identity
Management
Ledger Secure
P2P Protocol
Auditability Storage Registry

Event Stream

Services
Hyperledger
Permissioned Blockchain and Its Consensus Model
Permissioned Blockchain

Permissioned Blockchain maintains an access control layer and allows certain actions to be performed only by a
few identifiable participants. It is also called Private Blockchain.

Legally accountable
Transaction Settlement
validators

Suitable for off-


chain assets
Permissioned vs. Permissionless Blockchain

Characteristics Permissioned Permissionless

Open and transparent


Access Approved members only
access

Performance Faster Slower

Consensus Proof-of-Stake Proof-of-Work

Transaction cost Low High

Stability Highly stable Limited stability

Only members have full Same access level for all


Access control access participants

Trust Trusted environment Trust-free environment


Hyperledger
Consensus and Its Interaction with Architectural Layers
Consensus

Consensus is the process by which a network of nodes validates the block of transactions and provides a
guaranteed ordering of transactions.

Confirms accuracy of all Agrees on the order and


transactions in a block precision of execution

Depends on smart contract layer to verify


the exact order of transaction
Source: https://www.hyperledger.org/
Consensus Properties

Safety Liveness

Guarantees the same Every submitted transaction


sequence of input and output is received by each non-
of each node faulty node
Activities Performed to Reach Consensus

Transaction Order Transaction Validation

• Enables confidentiality of • Contains business logic to


the transactions make the transaction valid
• Increases the efficiency of • Ensures the confirmation of
transactions policies and contracts specified
for the transaction
• Checks for syntax and logic
errors
Consensus Model for Permissioned Blockchain

Smart Consensus
Client Consensus Contract (on other peers)

Transactions sent for application


Speculatively apply
Return a proof of accuracy and/or the transactions
change set

( If transactions have been


Order transactions
successfully applied)
Broadcast ordered list of transactions, the proof of
accuracy, and the change sets
Send requests
Verify transactions
Return correct block of transaction

Commit block of transactions


Notify client about events

Client Consensus Smart Consensus


Contract (on other peers)
Hyperledger
API and Network Topology in Hyperledger
API

It enables clients and applications to interface to the Blockchains.

Admin and Client API Common API


Used to perform Used to obtain information
business operations and about connected networks
administration tasks

Runtime API
Used to perform all
transaction operations
Network Topology

Network topology is a technical infrastructure that provides smart contract services and ledger to applications.
Listed below are the components of network topology:

Ledger Smart contracts

Peer nodes Ordering services

Channels Fabric Certificate Authorities


Steps to Create a Hyperledger Network

Create a network Create a channel for Install smart Add another Add peer and join it
consortium contracts consortium definition to multiple channels

Define a Join peers to Optimize the network Add new


consortium channels channel
Network Topology

S4 S4 S5 S5

A1 A2 A3 P1 P2 P3
1
1 1 2 L1 L1 1 2
L2 2
L2
RD

O 0 0 NP1
1 2

C1

C2
CA1 CA2
RA RB RB RC

CA3 CA4 1 CP1 2 CP2


N
Key Takeaways

You are now able to:

Describe Hyperledger and its architecture

Set up Hyperledger Sawtooth environment and perform transactions with it

Set up Hyperledger Iroha network and perform transactions with it

Interpret permissioned Blockchain and its consensus model


Knowledge Check
Knowledge
Check
What is Hyperledger?
1

a. A cryptocurrency

b. A Blockchain

c. A company

d. A software
Knowledge
Check
What is Hyperledger?
1

a. A cryptocurrency

b. A Blockchain

c. A company

d. A software

The correct answer is d

Hyperledger is a software used to create one’s own personalized Blockchain service.


Knowledge
Check
Which consensus algorithm does permissioned Blockchain use?
2

a. Proof of Work

b. Proof of Stake

c. Proof of Elapsed Time

d. Practical Byzantine Fault Tolerance


Knowledge
Check
Which consensus algorithm does permissioned Blockchain use?
2

a. Proof of Work

b. Proof of Stake

c. Proof of Elapsed Time

d. Practical Byzantine Fault Tolerance

The correct answer is b

Consensus algorithm makes use of Proof of Stake algorithm to perform the transaction.
Knowledge
Check
Which API is used to perform administration tasks?
3

a. Common API

b. Runtime API

c. Admin and Client API

d. None of the above


Knowledge
Check
Which API is used to perform administration tasks?
3

a. Common API

b. Runtime API

c. Admin and Client API

d. None of the above

The correct answer is c

Admin and Client API is used to perform business operations and administration tasks.
Lesson-End Project Duration: 30 mins

Transform the Supply Chain

Problem Statement: The traditional seafood supply chain industry has illegal, unreported, and
unregulated fishing practices. You are required to bring traceability and accountability to the supply
chain through the power of Hyperledger Sawtooth technology.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 6: Hyperledger Composer

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Describe Hyperledger Fabric and Hyperledger Composer

Set up a development environment using Hyperledger Composer

Create, deploy, and test a business network


Hyperledger Composer
Hyperledger Fabric and Its Concepts
Hyperledger Fabric

Hyperledger Fabric is a permissioned Blockchain system used for developing applications. It allows unknown
identities to participate in the network enrolled through Member Service Provider (MSP).
Issues in Hyperledger Fabric

Unmanageable Unscalable

Privacy Versioning
Hyperledger Fabric Model

Assets 1 2 Chaincode

Security
and 5 3 Ledger
Membership Services

4 Channels
Creating Hyperledger Fabric Network

Create channels

Configure and start


peer nodes 4

1 3 5

Configure and start Install Chaincode Join channels and


ordering service initiate Chaincode in
the channels
Chaincode

● Chaincode is a program that initiates and manages the ledger state through transaction
● It runs in a secured Docker container
● It handles the business logic agreed to by the members of the network
Ordering Service

The ordering service packages transactions into the blocks that are delivered to the peers. The
communication with the services is done via channels.

Ordering Service
Channels

Channels are shared across an entire network and are permissioned for a specific set of participants.

E0

E1

Ordering Service
Single-Channel Network

• All peers connect to the same system channel


• All peers maintain the same ledger and have the same Chaincode

S
Client
Application
D E0 E2
K
A B A
P B

E1 E3
A
A B B
Ordering Service

Hyperledger Fabric Network


Multi-Channel Network

• All peers are not connected to the same system channel


• All peers do not have the same Chaincode

S
Client
Application
D E0 E2
K
Y Z A P
P B
S
Client
D E1 E3
Application
K
Y
A B B
Ordering Service

Hyperledger Fabric Network


Fabric Peer

• Maintains one or more ledger and connects to more than one channels
• Assigns events to client application

Channels Peer Chaincode

Events Local
MSP

0 1 2 3
Ledger
Blockchain WorldState
Client Application

• Uses Fabric SDK to connect to peers over channels and receive events from them
• Can be written in different languages like Node.js, Go, Java, and Python

Client SDK Channels


Application (HFC)

Events

Local
MSP
Fabric Certificate Authority

• Used within Fabric network for issuing long-term identity


• Provides authentication and security

Fabric-CA

• 5H

HSM
DB LDAP

Root Certificate High Authenticate Secure


Authority Availability Enroll ID,
secret
Hyperledger Composer
Hyperledger Composer and Its Features
Hyperledger Composer

Hyperledger Composer is a development tool that is used to develop use cases and deploy Blockchain
applications easily.

Data integration Quickly reusable

Supports pluggable Simple models


Blockchain protocols
Assisted Practice Duration: 10 mins

Set Up Development Environment Using Hyperledger Composer

Problem Statement: Simplilearn wants to create and deploy a business network. You are
given a task to set up the development environment using Hyperledger Composer for this.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Install NVM

Step 02 Install the CLI tools

Step 03 Install Playground

Step 04 Set up your IDE

Step 05 Install Hyperledger Fabric


Blockchain Business Network

It is a decentralized network that is used to transfer business assets securely and efficiently with the help of
distributed ledgers. The network is deployed in the following steps:

Model 1 2 Access Control

Integrate 5 3 Deploy

4 Test
Business Network Template

Assets Transaction Access Query


Use composer to create a business network
Participants Functions Control Definitions
Transactions Rules definition, which comprises of Model (.cto),
Script (.js), ACL (.acl) and Query (.qry) files
Model File Script File Access Control Query File
.cto .js .acl .qry

Package up your Business Network


Business Network Archive Definition and export it as an Archive
.bna (.bna file) to deploy it somewhere

Hyperledger Fabric Web Browser / Node.js


Use ID cards (which include connection profiles and
Cloud / Local Online credentials) to deploy your business network
definition to a distributed ledger
Testing Business Network

There are four ways of testing a business network:

Standard Unit Testing Functional Verification


Testing

Cucumber
Mocha
Testing
Testing
Assisted Practice Duration: 20 mins

Create, Deploy, and Test a Business Network

Problem Statement: Simplilearn wants to create, deploy, and test a sample business
network for the organization that will define the participants, transactions, assets, and the
events of the organization. Develop a business network for this.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username
and password that is generated. Click on the Launch Lab button. On the page that appears,
enter the username and password in the respective fields, and click Login.
Assisted Practice: Steps

Step 01 Generate a business network definition

Step 02 Install the CLI tools

Step 03 Create the business network administrator

Step 04 Deploy the business network

Step 02 Perform Cucumber testing


Unassisted Practice
Duration: 20 mins
Deploy a Car Auction Business Network

Problem Statement: In a car auction, the price of your car is set by the company itself. Therefore, there is
always a mediating or commission fee involved. Instead, we can create an interactive decentralized
auction network where the highest bidder gets the car.
Access: Click on labs tab on your LMS. Note the username and password. Click on the Launch Lab button.
Enter the username and password to access the lab.
Note: This practice is not graded. It is only intended for you to apply the knowledge you have gained to
solve real-world problems.
Use Case Solution

Step 1 Create a new participant in the Auctioneer participant registry

Step 2

Step 3
{
"$class": "org.acme.vehicle.auction.Auctioneer",
"email": "[email protected]",
Step 4 "firstName": "Jenny",
"lastName": "Jones"
}
Step 5

Step 6
Use Case Solution

Step 1 Create two participants in the Member participant registry

Step 2 {
"$class": "org.acme.vehicle.auction.Member",
"balance": 5000,
Step 3 "email": "[email protected]",
"firstName": "Amy",
"lastName": "Williams"
}
Step 4
{
"$class": "org.acme.vehicle.auction.Member",
Step 5 "balance": 5000,
"email": "[email protected]",
"firstName": "Billy",
Step 6 "lastName": "Thompson"
}
Use Case Solution

Step 1 Create a new asset of vehicle owned by [email protected] in the Vehicle


asset registry

Step 2

Step 3
{
"$class": "org.acme.vehicle.auction.Vehicle",
"vin": "vin:1234",
Step 4 "owner":
"resource:org.acme.vehicle.auction.Member#[email protected]"
}
Step 5

Step 6
Use Case Solution

Step 1
Create a vehicle listing for car vin:1234 in the VehicleListing asset registry

Step 2

{
Step 3 "$class": "org.acme.vehicle.auction.VehicleListing",
"listingId": "listingId:ABCD",
"reservePrice": 3500,
Step 4 "description": "Arium Nova",
"state": "FOR_SALE",
"vehicle":
"resource:org.acme.vehicle.auction.Vehicle#vin:1234"
Step 5
}

Step 6
Use Case Solution

Submit an Offer transaction


Step 1

{
Step 2 "$class": "org.acme.vehicle.auction.Offer",
"bidPrice": 2000,
"listing":
Step 3 "resource:org.acme.vehicle.auction.VehicleListing#listingId:ABCD",
"member":
"resource:org.acme.vehicle.auction.Member#[email protected]"
}
Step 4
{
"$class": "org.acme.vehicle.auction.Offer",
Step 5 "bidPrice": 3500,
"listing":
"resource:org.acme.vehicle.auction.VehicleListing#listingId:ABCD",
Step 6 "member":
"resource:org.acme.vehicle.auction.Member#[email protected]"
}
Use Case Solution

Step 1 End the transaction

Step 2

Step 3
{
"$class": "org.acme.vehicle.auction.CloseBidding",
Step 4 "listing":
"resource:org.acme.vehicle.auction.VehicleListing#listingId:ABCD"
}
Step 5

Step 6
Key Takeaways

You are now able to:

Describe Hyperledger Fabric and Hyperledger Composer

Set up a development environment using Hyperledger Composer

Create, deploy, and test a business network


Knowledge Check
Knowledge
Check
Which of the following is a program that initiates a transaction?
1

a. Ordering service

b. Fabric peer

c. Client application

d. Chaincode
Knowledge
Check
Which of the following is a program that initiates a transaction?
1

a. Ordering service

b. Fabric peer

c. Client application

d. Chaincode

The correct answer is d


Chaincode is a program that initiates the transaction and manages the ledger state.
Knowledge
Check
In which channel network do all peers maintain the same ledger?
2

a. Single-Channel network

b. Multi-Channel network

c. Both a and b

d. None of the above


Knowledge
Check
In which channel network do all peers maintain the same ledger?
2

a. Single-Channel network

b. Multi-Channel network

c. Both a and b

d. None of the above

The correct answer is a

In single channel network, all peers connect to the same system channel. Hence, it maintains the
same ledger.
Lesson-End Project Duration: 30 mins

Deploy an Animal Tracking Business Network

Problem Statement:
The government farming regulators are not able to track the locations of all animals and their
movements between farms. You are supposed to create and deploy a business network to solve the
problem. The business network should define the following:
• Participants: farmers and regulator
• Assets: animal, business, and field
• Transactions: AnimalMovementDeparture, AnimalMovementArival, and SetupDemo

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Thank You
Blockchain
Lesson 7: Blockchain on Multichain

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Create and deploy your first private Blockchain using Multichain

Create an asset in Multichain

Publish data to the stream

Perform mining in Multichain using round-robin consensus


scheme
Create private stock exchange on Multichain
Blockchain on Multichain
Overview of Multichain
Introduction to Multichain

Multichain technology is a simple yet powerful platform for creating and


deploying private Blockchain for enterprise.
Objectives of Multichain

To ensure the visibility of To ensure stability


Blockchain’s activity within and control over
the chosen participants transactions

To enable secure To store transactions


mining without proof related only to
of work participants
Multichain Architecture

In Multichain, every node has a separate application programming


interface (API) to connect to each user interface(UI).

UI(Basic)

JSON-RPC API

JSON-RPC API
Wallet API API Wallet API API

Node 1 Node 2

Multichain
Assets Stream permission Multisig
Assisted Practice Duration: 10 mins
Create a Private Blockchain

Problem Statement: Develop and deploy a private Blockchain for a financial institution.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Steps to Create Multichain

Step 01 Create a new Blockchain with a name of your choice

Step 02 Check the Blockchain’s default settings in params.dat file

Step 03 Initialize the Blockchain

Step 04 Connect to the Blockchain using the second server

Step 05 Add connection permission to the address of the first server

Step 06 Reconnect using the second server


The Hand-Shaking Process

Hand-shaking in Multichain occurs when two nodes or hubs connect.

Each node presents its public


address on the permitted list
1

Each node checks if other’s address exists on


2 its version of permitted list

A challenge message is sent by each


3
node to the other node

4 The other node has to sign the message with the


private key of the presented address

The peer-to-peer connection aborts if either of the nodes is not satisfied with
the results.
Permission in Multichain

Multichain provides the following permission:

Connect to network

Send and receive transactions

Write to a stream

Issue assets

Create streams

Add blocks to chain

Change permission by consensus


Features of Assets in Multichain

Do not require Provide flexible


smart contracts metadata

Allow permissioned follow-on Create and accept atomic multi-


issuance of an existing asset asset exchanges

Help in checking the related


Allow multisignature for
transactions by subscribing to an
escrow payments
asset
Assisted Practice Duration: 7 mins
Create an Asset in Multichain

Problem Statement: A financial institution has asked you to create an asset that can be utilized as a
currency for trading. Create an asset, and send it between the nodes.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Steps to Create Assets in Multichain

Step 1: Switch to interactive mode

Step 2: Check for permission assigned to the wallet’s address

Step 3: Get the address that has permission to create an asset using the first server

Step 4: Create a new asset

Step 5: Verify that the asset is listed using both the servers
Steps to Create Assets in Multichain(Contd.)

Step 6: Check asset balances using both the servers

Step 7: Send some units of the asset to the second server’s wallet using the first server

Step 8: Grant permission to the address of second server’s wallet to send and receive the asset

Step 9: Send asset to the address

Step 10: Check asset balances, and view transaction on each server
Multichain Streams

● Multichain streams enable a Blockchain to be used as a general purpose append-only database


● They provide an abstraction for Blockchain use cases on general data retrieval, timestamping, and archiving

Streams can be used to implement three types of databases on a chain:

01 A key-value database or document store, in the style of NoSQL

02 A time series database, which focuses on the ordering of entries

03 An identity-driven database where entries are classified according to their author


Assisted Practice Duration: 10 mins
Create Streams in Multichain

Problem Statement: Raw data stored on a Blockchain is visible to every node connected to the chain.
However, the financial institution you are working for wants to reveal their confidential data to the
selected members. Create streams in Multichain to resolve the confidentiality problem.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Steps to Create Streams in Multichain

Step 1: Create a stream for data storage and retrieval

Step 2: Check permission of the stream

Step 3: Publish something, such as your name, to the stream using a key

Step 4: Check if the stream is visible on another server

Step 5: Allow the second server to subscribe to the stream and view its content

Step 6: Allow the second server to publish to the stream

Step 7: Check the stream contents


Consensus in Multichain

Multichain has distributed consensus between identified block validators. There is one
validator per block, working in a round-robin system.

The following are the features of consensus in Multichain:

01 Only permissioned nodes are allowed to mine

02 Distributed consensus has mining diversity

03 There is no proof of work or cryptocurrency


Mining in Multichain

● Multichain restricts the number of blocks that may be created by the same
miner within a given time frame
● Multichain uses a parameter called mining diversity, which defines the
strictness in the mining system
● Mining in Multichain uses a randomized round-robin system for block adders
● Mining diversity can be between 0–1
Assisted Practice Duration: 10 mins
Perform Mining in Multichain

Problem Statement: Create a block validation process in a permissioned Multichain Blockchain.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.
Steps for Mining in Multichain

Step 1 Grant mining permission to both the nodes

Step 2 Check that the two permitted mining nodes are listed

Set mining-turnover to maximum to allow all the


Step 3
nodes to create a block

Step 4 Set run-time parameters

Check current block height and information of last few


Step 5
blocks
Multichain Flexibility

Multichain provides a fair level of flexibility:

It has more than 45 Blockchain parameters

It has an option to change permission by consensus

It has unified JSON-RPC API for applications

It allows nodes to be added or removed from the network


Multichain: Speed and Scalability

Can have millions of addresses, Can process unlimited


assets, and streams transactions or stream items

Has the block time of 2 Allows any number of


seconds nodes in network

Includes signature verification


and transaction processing
Unassisted Practice Duration: 20 mins
Stock Exchange on Multichain Platform

Problem Statement: The stock exchange model is centralized, slow, and expensive. Hence,
optimization is required. Develop a Multichain based stock exchange market, which makes the system
decentralized, simple, efficient, fast, transparent, and secure.

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and
password that is generated. Click on the Launch Lab button. On the page that appears, enter the
username and password in the respective fields, and click Login.

Note: This practice is not graded. It is only intended for you to apply the knowledge you have gained to
solve real-world problems.
Steps to Create Multichain based Stock Exchange

Step 01 Create a private Blockchain

Step 02 Connect to the Blockchain

Step 03 Create assets

Step 04 Transfer assets to the peer


Steps to Create Stock Exchange on Multichain

• Run the following command using the first


Step 1 server: multichain-util create stockexchange

Step 2 • Run the following command to initialize the


Blockchain:
Step 3 multichaind stockexchange –daemon

(The server will start, and a message will appear


Step 4
saying “genesis block found”)
Steps to Create Stock Exchange on Multichain

• Run the following command using the second server


Step 1 to connect to this Blockchain:
multichaind stockexchange@[ip-address]:[port]

Step 2 • Run the following command using the first server to


add permission for the new address:
Step 3 multichain-cli stockexchange grant <walletaddress>
connect

Step 4 • Run the following command and try reconnecting


using the second server:
multichaind stockexchange -daemon
Steps to Create Stock Exchange on Multichain

• Run the following command using the first


server to get the address that has the
permission to create an asset pool:
multichain-cli stockexchange listpermission
Step 1 issue

Step 2 • Run the following command to create the


company shares:
multichain-cli stockexchange issue <peer-
Step 3
address> SimpliLtd 1000 0.01
(1000 are the units, and they are divisible by
Step 4 0.01)

• Run the following command using either of the


servers to confirm the listing of the asset:
multichain-cli stockexchange listassets
Steps to Create Stock Exchange on Multichain

Step 1 • Run the following command to transfer some


shares to the second server:
multichain-cli stockexchange sendassettoaddress
Step 2 <second_node_address> SimpliLtd 501

Step 3
• Run the following command to confirm the transfer
of ownership on both the servers:
Step 4 multichain-cli stockexchange gettotalbalances 0
Key Takeaways

You are now able to:

Create and deploy your first private Blockchain using Multichain

Create an asset in Multichain

Publish data to the stream

Perform mining in Multichain using round-robin consensus


scheme
Create private stock exchange on Multichain
Knowledge Check
Knowledge
Check
Multichain ensures that Blockchain activities are visible to all the participants.
1

a. True

b. False

c.

d.
Knowledge
Check
Multichain ensures that Blockchain activities are visible to all the participants.
1

a. True

b. False

c.

d.

The correct answer is b


Multichain ensures that the visibility of Blockchain’s activity is within the chosen participants.
Knowledge
Check
Multichain has a general API, which is used by each node to connect to an application.
2

a. True

b. False

c.

d.
Knowledge
Check
Multichain has a general API, which is used by each node to connect to an application.
2

a. True

b. False

c.

d.

The correct answer is b


Multichain doesn’t have a general API. Each node has a separate API to connect to UI.
Knowledge
Check
Which of the following is not applicable to Multichain?
3

a. Multi-way atomic asset exchanges

b. Permissioned follow-on issuance

c. Need for smart contracts

d. Flexible asset metadata


Knowledge
Check
Which of the following is not applicable to Multichain?
3

a. Multi-way atomic asset exchanges

b. Permissioned follow-on issuance

c. Need for smart contracts

d. Flexible asset metadata

The correct answer is c

There is no need for smart contracts in Multichain.


Knowledge
Check
Which of the following is true about Multichain?
4

a. Multichain cannot have millions of addresses, assets, streams

b. Transaction verification doesn’t include signature verification

c. Multichain has block time as low as 10 seconds

d. Multichain allows unlimited nodes in the network


Knowledge
Check
Which of the following is true about Multichain?
4

a. Multichain cannot have millions of addresses, assets, streams

b. Transaction verification doesn’t include signature verification

c. Multichain has block time as low as 10 seconds

d. Multichain allows unlimited nodes in the network

The correct answer is d

Multichain can have any number of nodes in the network.


Lesson-End Project Duration: 20 mins
Create Private Multichain Blockchain

Problem Statement: Create a private Multichain with the following modifications in parameters in params.dat file:

1. Basic chain parameters


Provide chain description = “you can provide description to your blockchain”
2. Global permissions
Set “Anyone-can-connect= true”
3. Native Blockchain currency
Set “Initial-block-reward= 286730“(Set any value of your choice)
Set “Minimum relay fee= 130”

Access: Click on the Labs tab on the left side panel of the LMS. Copy or note the username and password that is
generated. Click on the Launch Lab button. On the page that appears, enter the username and password in the
respective fields, and click Login.
Thank You
Blockchain
Lesson 8: Blockchain Prospects

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you will be able to:

Identify the use cases of Blockchain in healthcare industry

Identify the use cases of Blockchain in government organization

Identify the use cases of Blockchain in finance industry

Identify the use cases of Blockchain in other industries worldwide


Blockchain Prospects
Uses of Blockchain
Do We Need Blockchain?
Should more
than one
participant be
Can a
able to
traditional
update the
database
data? Do you
technology need to
meet your keep the
needs?
data
private?

Do all the
updaters
trust each
other?
Do you need Do you need to
redundant copies control the
in multiple permissions for
distributed Blockchain
computers? software?

Would all the


participants
trust the third
party?

You might need a You might need a


You don’t need a Permissioned Public Blockchain
Blockchain (fast Blockchain (medium (slow transaction
transaction speed) transaction speed) speed)
Challenges in Blockchain

Initial
Cost

Integration with Energy


Legacy Systems Consumption

Public Privacy and


Perception Security
Identifying a Blockchain Use Case

A good Blockchain use case should have the following:

1 A business problem

2 An identifiable business network

3 A need for trust


Blockchain Prospects
HealthCare Use Cases
Patient Data Management

User agrees to share health data. Researchers wish to access data. For
Health wallet creates pseudonymous Shared ledger each record, they check conditions of
address and stores as smart contract smart contracts to determine if the
on Blockchain. It gives permission for use is allowed. If so, then access the
certain release under specifications. data, record transaction on
Blockchain, and make micropayment
to individuals health wallet.

Pseudonymous
EMR health data

User’s address: 1EGJKBejcsbwqubwiPWsejndns

Healthcoin payment is converted to money, which is used in health savings


account(HSA) or to purchase medical services
Drug Traceability

The manufacturer sends The wholesaler sends the The pharmacist delivers the
the drugs to the wholesaler drugs to the pharmacist drug to the patient

The manufacturer The wholesaler verifies The pharmacist verifies The patient verifies the
produces the drug and marks the origin of the product the origin of the product origin of the product
it with an unique code

The transaction between The transaction between The transaction between


A hash is produced the pharmacist and the
the manufacturer and the the wholesaler and the
wholesaler is added to the pharmacist is added to the patient is added to the
Blockchain Blockchain Blockchain
The information is stored
on the Blockchain
Blockchain Prospects
Government Use Cases
Blockchain in Voting

The certification from the ID The voter has


verifier is paired with blinded been authorized
The ID verifier 1 token and sent to the registrar, to cast a ballot by
requesting signature of approval the ID verifier and
certifies that the
for a certain ballot type the registrar
ID is unique,
which authorizes
the ID key to The registrar signs the Using vote key, the
vote on a certain 2 blinded token and sends it voting booth UI
back to the voting booth generates ballot
ballot type
for the voter to
cast their vote

The voting booth then sends


a signed, unblinded token
3 with a vote key to the
registrar, requesting certain
ballot type

The registrar sends back a


certificate of authority for the
4
voting key

Convenient
notification is
sent when
your ballot is
ready
Blockchain Around the World

Russia South Korea India Singapore USA


Sberbank partnered Dayli Financial IndiaChain is a pilot Singapore General Services
with Russia’s Federal Group(DFG) is project by the government has Administration of
Antimonopoly developing a government of India. initiated project Ubin USA is interested to
Service(FAS) to Blockchain based It utilizes Blockchain for clearing and use Blockchain for
implement document ecosystem called technology for settling payments financial
transfer and storage ICON. It will allow digitization and and securities management,
using Blockchain government, validation of procurement, supply
universities, hospitals, educational degree chain management,
securities, and banks certificates and many other
to interact without industries.
third-party networks
Tax Processing: GST without Blockchain

A GST invoice is Buyer pays the bill Information of


payment is recorded
issued by the seller with GST
on GST portal

Additional payment is Final tax goes to the Seller pays to the


adjusted government supplier
Tax Processing : GST with Blockchain

A GST invoice is Buyer pays the Bill Seller pays to the


issued by the seller with GST suppliers

Smart contract adjusts Final tax goes to the


the tax calculation government
during the payment
Blockchain in Real Estate: OpenLaw Core

Real Estate Using OpenLaw Core


Blockchain in Land Registry: Exonum

Citizen Service-Hall Centralized Database Paper Certificate


Initiates a request or Notary Risk of data Risk of loss,
manipulation damage, or forgery

Up times
to 400 faster
Current registration and
verification of extracts
takes up to three days. Fixing in a Chain Electronic
With Exonum, it can be Certificate
done within several Guarantee of further Public data can be
seconds. immutability changed only by the
owner
Blockchain Prospects
Finance Use Cases
Blockchain in KYC

Centralized database requires heavy cost and effort: Blockchain saves cost, time, and effort:

Less or no
Data incurs need for data
costs for security
security of data

The customer Intermediary


submits KYC stores data in
documents to the centralized
the bank database The customer The bank
uploads KYC accesses KYC
data to the data from the
Blockchain Blockchain

The bank Other


forwards KYC institutions seek
documents to the intermediary
the for KYC data Other institutions
centralized causing verify KYC already
intermediary repetitive KYC performed by bank
checks
Blockchain in Trade Finance
Upon purchase, the agreement
of sale between the importer In real time, the import bank will have
and the exporter is shared capability to review purchase
agreement, draft terms of credit, and
with the import bank using a
smart contract on the submit obligation to pay to the export
bank
Blockchain
1 2

Goods will be inspected by After receiving the obligations,


third parties and the custom the exporter will digitally sign The export bank will review the
agents in the exporting country
and their actions will have a
Blockchain-equivalent letter of provided payment obligation and 3
credit within the smart once approved, a smart contract
digital signature of approval on contract to initiate shipment will be generated on the
the smart contract Blockchain to cover terms and
conditions and lock-in obligations

5 4

During transit, goods will Upon delivery, importer will Using provided acknowledgement,
6 be transported from digitally acknowledge receipt of
goods and trigger payment
smart contract will automate
payment from importer to
country A to country B
exporter via a smart contract

7 8
Blockchain in the Mortgage Industry

Current Mortgage Process:


Blockchain in the Mortgage Industry (Cont.)

Mortgage process using Blockchain

1
Node

3
2
Mortgage Solutions
Buyer 4
5 6 1 7
Broker firm
10
8 Node Node Node

9 6a
5

7
Buyer’s bank Node Title search company
6b

11

12

municipality
Seller’s bank
Blockchain distributed ledger nodes
Seller
Blockchain in Loan Management

Loan management before implementing Blockchain

Before Process

Financial
Identity Check past Collateral Risk Loan Loan Loan Write-off
information Underwriting Approval
Verification loan records validation assessment rating classification recovery bad loans
verification

There is Loans are restructured to Process is


Process is subject to
lack of reduce reported and non-
repeated by willful
Processes are maintained standardiz Process is based on limited performing assets
each bank, defaulters
separately by each bank, ation and information available to
sometimes increasing
with little scope for scope for the underwriter There is no scope of
for each loan loss of assets
information sharing double sharing defaulter
application and write-off
spending information across banks
Blockchain in Loan Management (Cont.)

Loan management after implementing Blockchain

After Blockchain application Process Improvement Process

Smart Information Smart Information Smart Smart


Identity sharing collaterals sharing contracts property

Share the Cryptographically signed


Foster collateral immutable loans records. Smart property used for
identity valuation Restructuring entails approval effective collateral
Shared information provides Shared information and
verificatio information, from distributed network management across
access to richer information consensus assure
n is done for well-informed decision and efficient governance banks and faster
using making eliminate and transparency in Foster identification of risky transfer of collateral
smart the scope of underwriting customers is possible with ownership in case of
identity double high debt repayment lost recovery
spend capacity

Identity Check past Financial Collateral Risk Loan Loan Loan Write-off
verification loan records information valuation rating Underwriting Approval classification recovery bad loans
assessment
verification
Blockchain Prospects
Other Worldwide Use Cases
Blockchain in e-Estonia

Blockchain in e-Estonia is used for the


following:
• Securing health records by writing every
update
• Maintaining all transactions of stock
exchange
• Storing birth certificates, business
e-estonia.com
contracts, and marriage registrations
Blockchain in Energy Markets: Gridchain
Transmission network
Community minigrid buys
settles all payments
and sells power and settles
peer-to-peer
payments without central
controller
AND
Secure distributed
asset registries

Carbon tax collected


directly from
appliances

Home energy
management with no
central controller

Carbon market with fraud- Shared and


proof distributed registry autonomous vehicle
payments

Distribution grid balances


EV charging
supply and demand with no
payments
central controller
settlements
Blockchain in Media: Ujo Music
Problems:
● Comprehensive database of music copyright doesn’t exist
● Royalty amount takes longer than usual to reach the music makers

Solution:
● Blockchain can make the royalties calculation fast, transparent, and secure
● Blockchain can provide a tamper-proof and easily auditable database

Ethereum based Decentralized music platform: ujomusic.com


Blockchain in Travel: LockTrip

Travel industry before implementing Blockchain Travel industry after implementing Blockchain

John books $3 $15 - $20 $1


a hotel Credit card Booking site Management
online company software

Actual amount paid for the


property
$81
Hotel
Blockchain in Identification: uPort
Identification process before implementing
Identification process after implementing Blockchain
Blockchain

LinkedIn Login
Blockchain in Supply Chain

Order Placement: Traditional approach

Order Placed Order Processed Order Packed Order Shipped Order Delivered

Customer A member of sales The shipping Your order Customer gets


places an team receives the clerk picks the gets boxed satisfied and
order on the order and order and and shipped to submits the
website dispatches it to proceeds for your address product review
the shipping shipment on the website
department
Blockchain in Supply Chain

Order placement using Blockchain smart contracts

1. Certificate of 1. Shipment date 1. Order number 1. Receive date 1. Receive date


origin 2. Order number 2. Shipment number 2. Pick date 2. Order number
2. Batch numbers 3. HSS code 3. Equipment 3. Packaging 3. Invoice number
1. Certificate of 1. Shipment date 4. Temperature number specifications 4. Customer id
3. Production
origin 2. Order number 5. Barcode 4. Temperature 4. Packaging barcode 5. Temperature
data
2. Batch numbers 3. HSS code 5. Temperature
3. Processing data 4. Barcode

Blockchain
record

1. Match supplier, order, 1. Match supplier, order, 1. Match supplier,


invoice, and shipment invoice, and shipment order, invoice,
Blockchain
2. Quality check against 2. Quality check against and shipment
smart contract
specifications specifications 2. Update inventory
3. Pay supplier 3. Update inventory levels levels
4. Pay supplier 3. Pay supplier
Blockchain for Network Security: Korea Telecom

Software(Data provider) Software(Data user)

Encrypted data Encrypted data


transmission transmission

1. Registration of data attributes Data exchange 1. Registration of data attributes


and ID information and ID information
Blockchain
2. Setting of access rights Access control, 2. Setting of access rights
trace management,
data recovery
3. Automation of processes 3. Automation of processes

Data access
Blockchain Data registration
Authentication Authentication Blockchain
permission permission
traceability traceability
Blockchain API Blockchain API
Wide area network
App generating API App using API
Corporate System User
Key Takeaways

You are now able to:

Identify the use cases of Blockchain in healthcare industry

Identify the use cases of Blockchain in government organization

Identify the use cases of Blockchain in finance industry

Identify the use cases of Blockchain in other industries worldwide


Knowledge Check
Knowledge
Check Which of the following advantages are provided by the blockchain based solution for
trade logistics?
1

a. Tamper proof and digitally signed documents

b. Process automation

c. Real time visibility and analytics

d. All of the above


Knowledge
Check Which of the following advantages are provided by the blockchain based solution for
trade logistics?
1

a. Tamper proof and digitally signed documents

b. Process automation

c. Real time visibility and analytics

d. All of the above

The correct answer is d


Blockchain provides tamper proof, digitally signed documents, process automation, real time
visibility, and analytics for trade logistics.
Knowledge
Check
The blockchain can address the errors in the current supply chain by:
2

a. Automatically tracking the information and verifying it using the smart contract

b. Only verifying the information using the smart contract

c. Only tracking the information

d. Making the data available to auditors to manually verify and correct errors
Knowledge
Check
The blockchain can address the errors in the current supply chain by:
2

a. Automatically tracking the information and verifying it using the smart contract

b. Only verifying the information using the smart contract

c. Only tracking the information

d. Making the data available to auditors to manually verify and correct errors

The correct answer is a


Blockchain can address the errors by automatically tracking the information and verifying it using
the smart contract.
Knowledge
Check
Ujo music is based on which of the following blockchain platforms?
3

a. Hyperledger Fabric

b. Hyperledger Sawtooth Lake

c. Ethereum

d. HydraChain
Knowledge
Check
Ujo music is based on which of the following blockchain platforms?
3

a. Hyperledger Fabric

b. Hyperledger Sawtooth Lake

c. Ethereum

d. HydraChain

The correct answer is c


Ethereum is used by Ujo music to build flexible and modular licensing systems.
Knowledge
Check
Which of the following is not a valid example of identity fraud?
4

a. Someone opens a social account using your social history

b. Someone accesses online shopping website using your personal information

c. Academic institute accesses its students’ current academic record

d. A banker uses your banking details for his own purpose


Knowledge
Check
Which of the following is not a valid example of identity fraud?
4

a. Someone opens a social account using your social history

b. Someone accesses online shopping website using your personal information

c. Academic institute accesses its students’ current academic record

d. A banker uses your banking details for his own purpose

The correct answer is c


Academic institute accessing their student’s current academic record does not fall under the fraud
identity example.
Knowledge
Check Which of the following features in Blockchain can allow proper management of
patient consent?
5

a. Digitally signed messages

b. Automation

c. Secure transactions

d. Tamper-proof data storage


Knowledge
Check Which of the following features in Blockchain can allow proper management of
patient consent?
5

a. Digitally signed messages

b. Automation

c. Secure transactions

d. Tamper-proof data storage

The correct answer is a


Digitally signed messages provide an approval from the patients to access and manage their
personal data.
Thank You

You might also like