Blockchain Ebook
Blockchain Ebook
By the end of this course, you will be able to acquire the following skills:
There are no prerequisites for this course. However, prior knowledge of the following technologies
would be helpful:
JavaScript
Highlights of This Course
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
There were few issues in the previous banking system that lead to the rise of Blockchain technology.
Issues
Blockchain tackled the issues in the previous system with some of its features mentioned below:
Transaction is validated by
Transaction is broadcasted the miner
Transaction is
requested
Transaction becomes a part
of the new block created
Blockchain transaction works implementing one of the following features in each step:
Digital Signature
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
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 02 Click on the random button to generate public and private key
Step 04 Enter a message, and click on sign button to generate a digital signature
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
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
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.
#78E…
Assisted Practice Duration: 5 mins
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 02 Enter some data in the data field, and click Mine
• 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.
Data
Security
with Hash
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
• 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( )
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.
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
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 02 Input any arbitrary data in the data field, and mine the block
32-byte hash
Blockchain Identifiers: Block Height
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
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
John -> Kat 3 BTC Peter gives 1 BTC to Susan John -> Kat 3 BTC
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 03 Enter data in the data field of Peer A, click Mine, and note the hash
value
The diagrams shows the usage of Blockchain features in every step of the Blockchain transaction process.
Cryptographic
Algorithm
Block Creation
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 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 03 Mine the block, and observe change in the hash value
Assisted Practice: Steps
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
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
Federated consensus
Cross-border payments mechanism
Blockchain Platforms
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
a. Proof of Work
b. Proof of Stake
a. Proof of Work
b. Proof of Stake
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
Blockchain uses Hash code for mathematical algorithms such as Proof of Work.
Knowledge
Check
What is a miner?
3
b. A type of Blockchain
b. A type of Blockchain
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
a. Proof of Work
b. Proof of Stake
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
Nonce is used to hash the block so that it will contain a run of leading zeros.
Lesson-End Project Duration: 10 mins
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
Bitcoin was the first digital currency that facilitated instant transfer of value
across the world.
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
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
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
• 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
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
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
Ross Joey
Double Spending Problem
Rachel
Joey
Address: 5BTC
Monica
Bitcoin address
The Bitcoin address corresponds to a public
key based on ECDSA(Elliptic Curve Digital
Signature Algorithm) used in Bitcoin
2. Amount
3. Output
1. Input 3BTC
Out Change sent
to sender’s
address
Bitcoin Transactions and Input/Output
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
Ross Joey
Bitcoin Script: An Example (Contd..)
scriptSig, scriptPubKey
Ross Joey
18E14A7B6A30…
Transaction Input scriptSig:
D61967F63C7DD…
OP_DUP
OP_HASH160
Transaction Output scriptPubKey: PubKHash
OP_EQUALVERIFY
OP_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
• Opcodes have the following: constants, flow control, stack, bitwise logic,
arithmetic, crypto, locktime, pseudo-words, reserved words
Evaluating Bitcoin Transaction Script
Wallet Miner
Full 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
There are certain special nodes in the Bitcoin network called seed nodes
which have the list of addresses
Give me the
Seed node address
<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
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
Independent aggregation of
transactions into new blocks
Independent confirmation of
new blocks by each node
▪ 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
Independent aggregation of
transactions into new blocks
Independent confirmation of
Ross
new blocks by each node
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 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)
• 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
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
Independent aggregation of
transactions into new blocks
Independent confirmation of
new blocks by each node
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
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
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
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 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
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
c. It never halves
c. It never halves
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
By default, Bitcoin clients connect to other bitcoin nodes on TCP port 8333.
Lesson-End Project Duration: 10 mins
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
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
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
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
EQ Costs 3 gas
Need 14 gas
Ether
Bitcoin Ether
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
Desktop 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
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
Self-verifying Self-executing
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
Ownership is
undisputed
Settlement is
automated
Digital currency
Smart Contract
Externally Owned
Account
Account
<code>
<code>
<code>
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
a3fa29ce: a3fa29ce:
920 eth 930 eth
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.
Account 100
Account 100
50
30
Ethereum
Ethereum Ecosystem
Types of Ethereum Tools
Ganache Swarm
Parity IPFS
MetaMask Whisper
Geth
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
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
Step 02 cd ganache
The fastest, lightest, and most secure Ethereum client that provides the core infrastructure essentials
for quick and reliable services.
Parity
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
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
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 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
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
IPFS is a decentralized storage system that is not related directly to Ethereum but can be integrated with it.
Swarm vs. IPFS
Status
vs.
Philosophical
Technicalities
Whisper
Drawbacks in Whisper
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
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.
“Inbox”
Instance
Deployment
Compilation to Bytecode
Contract
Source
A command line tool used to write, test, and deploy contracts on any Ethereum network
Truffle
Contract
Creation
Local
Rinkeby
Testing
Deployment
Embark
An environment that allows you to easily develop and deploy decentralized applications
Node
Formed by combining one or more nodes
ENS
Chrome browser mycontract.eth
Geth Your deployed
pointing to your
+ MetaMask contract
(MetaMask) contract deployed
plugin address
Ethereum 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.
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
DAO
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?
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?
b. Smart contracts
c.
d.
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
a. Remix IDE
b. Truffle
c. Embark
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
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
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
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.
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
Invokes contract
Perform
methods for data
deployment
storage
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
Memory Storage
Source files can contain contract definitions including directives and pragma directives.
}
General Value Types
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
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
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.
contract Purchase {
ss
enum State { Created, Locked, Inactive } // Enum
}
Enums: Example Code
function setGoStraight() {
choice = ActionChoices.GoStraight;
}
ss
function getChoice() returns (ActionChoices) {
return choice;
}
Structs are custom defined types that can group several variables.
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
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
ss
return a * (b + 42) + now;
}
}
ss
return a * (b + 42);
}
}
Function Calls and Return Types
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.)
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.
ss
a=5;
}
}
Function Modifiers
ss
y+=1;
}
//when a function returns multiple values we need to parallel assign
(x1,y1) = increment(1,2);
Function Modifiers: Example Code
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
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
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);} }
Abstract contract cannot be compiled and can lack an implementation, but they
can be used as a base contract.
contract Voter {
function Ballot() returns (bytes32);
}
ss
contract Person is Voter {
function Ballot() returns (bytes32) {
Return “yes”;
}
Abstract Contracts: Example Code
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
ss
function setVoter(string _vName, uint _age) public {
vName = _vName;
age = _age;
Voter(_vName, _age); //trigger event
}
Creating Contracts Using New Operator
uint x;
function SampleNew(uint a) payable {
X=a;
}
}
ss
contract New {
SampleNew n= new SampleNew(4);
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
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);
ss
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool
success);
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
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.)
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.)
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
• 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.
4 Mapping Iterator
Smart Contract Design Patterns
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
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
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.
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
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
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
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.)
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
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
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
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
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.
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++
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
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
Source: https://www.hyperledger.org/
Concept of Hyperledger
Used by For
In public Blockchain, each peer has to execute each and every transaction and run consensus
algorithm to validate it.
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
John Kat
Hyperledger Transaction
John
Kat
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.
Sawtooth Lake
Used in supply chain networks
Fabric Used in fishing industry
It’s an enterprise Blockchain platform for building distributed ledger applications and networks. It keeps ledgers
distributed and smart contracts safe.
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
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:
Permissioned
Smart Contract
Ethereum Virtual
Application
Machine
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
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 04 Pull the Docker image, and run the Iroha Docker container
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
API Interoperation
Hyperledger Architecture
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
Consensus is the process by which a network of nodes validates the block of transactions and provides a
guaranteed ordering of transactions.
Safety Liveness
Smart Consensus
Client Consensus Contract (on other peers)
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:
Create a network Create a channel for Install smart Add another Add peer and join it
consortium contracts consortium definition to multiple channels
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
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
a. Proof of Work
b. Proof of Stake
a. Proof of Work
b. Proof of Stake
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
a. Common API
b. Runtime API
Admin and Client API is used to perform business operations and administration tasks.
Lesson-End Project Duration: 30 mins
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
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
1 3 5
● 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
S
Client
Application
D E0 E2
K
A B A
P B
E1 E3
A
A B B
Ordering Service
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
• Maintains one or more ledger and connects to more than one channels
• Assigns events to client application
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
Events
Local
MSP
Fabric Certificate Authority
Fabric-CA
• 5H
HSM
DB LDAP
Hyperledger Composer is a development tool that is used to develop use cases and deploy Blockchain
applications easily.
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
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:
Integrate 5 3 Deploy
4 Test
Business Network Template
Cucumber
Mocha
Testing
Testing
Assisted Practice Duration: 20 mins
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
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 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 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 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
{
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 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
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
a. Single-Channel network
b. Multi-Channel network
c. Both a and b
a. Single-Channel network
b. Multi-Channel network
c. Both a and b
In single channel network, all peers connect to the same system channel. Hence, it maintains the
same ledger.
Lesson-End Project Duration: 30 mins
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
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
The peer-to-peer connection aborts if either of the nodes is not satisfied with
the results.
Permission in Multichain
Connect to network
Write to a stream
Issue assets
Create streams
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 3: Get the address that has permission to create an asset using the first server
Step 5: Verify that the asset is listed using both the servers
Steps to Create Assets in Multichain(Contd.)
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 10: Check asset balances, and view transaction on each server
Multichain Streams
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 3: Publish something, such as your name, to the stream using a key
Step 5: Allow the second server to subscribe to the stream and view its content
Multichain has distributed consensus between identified block validators. There is one
validator per block, working in a round-robin system.
● 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
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 2 Check that the two permitted mining nodes are listed
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 3
• Run the following command to confirm the transfer
of ownership on both the servers:
Step 4 multichain-cli stockexchange gettotalbalances 0
Key Takeaways
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.
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.
Problem Statement: Create a private Multichain with the following modifications in parameters in params.dat file:
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
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?
Initial
Cost
1 A business problem
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
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
Convenient
notification is
sent when
your ballot is
ready
Blockchain Around the World
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
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
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
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
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
Home energy
management with no
central controller
Solution:
● Blockchain can make the royalties calculation fast, transparent, and secure
● Blockchain can provide a tamper-proof and easily auditable database
Travel industry before implementing Blockchain Travel industry after implementing Blockchain
LinkedIn Login
Blockchain in Supply Chain
Order Placed Order Processed Order Packed Order Shipped Order Delivered
Blockchain
record
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
b. Process automation
b. Process automation
a. Automatically tracking the information and verifying it using the smart contract
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
d. Making the data available to auditors to manually verify and correct errors
a. Hyperledger Fabric
c. Ethereum
d. HydraChain
Knowledge
Check
Ujo music is based on which of the following blockchain platforms?
3
a. Hyperledger Fabric
c. Ethereum
d. HydraChain
b. Automation
c. Secure transactions
b. Automation
c. Secure transactions