0% found this document useful (0 votes)
75 views265 pages

Litecoin Testnet Faucet Overview

The document provides an overview of blockchain technology and related concepts, including Bitcoin, cryptocurrency wallets, miners, and decentralized applications (DApps). It covers various terms and definitions such as NFTs, DAOs, Ethereum, and the blockchain trilemma, along with examples and explanations of their significance. Additionally, it discusses the hype surrounding blockchain technology and notable events like the auction of Beeple's NFT artwork.

Uploaded by

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

Litecoin Testnet Faucet Overview

The document provides an overview of blockchain technology and related concepts, including Bitcoin, cryptocurrency wallets, miners, and decentralized applications (DApps). It covers various terms and definitions such as NFTs, DAOs, Ethereum, and the blockchain trilemma, along with examples and explanations of their significance. Additionally, it discusses the hype surrounding blockchain technology and notable events like the auction of Beeple's NFT artwork.

Uploaded by

Pratyush Gupta
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

Blockchain Technology

and Systems
(SEZG569/SSZG569)
BITS Pilani Dr. Ashutosh Bhatia
Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

QUIZ, HYPE & FACTS


BITS Pilani
Pilani Campus

QUIZ
Q0

What is BITCOIN

a) A Cryptocurrency
b) A decentralized peer-to-peer network
c) A public transaction ledger
d) All

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q1

Who created Bitcoin?

Satoshi Nakamoto
Satoshi Nakamoto is the name used by the presumed
pseudonymous person or persons who developed bitcoin,
authored the bitcoin white paper, and created and deployed
bitcoin's original reference implementation. As part of the
implementation, Nakamoto also devised the first blockchain
database. Nakamoto was active in the development of bitcoin
up until December 2010. Many people have claimed, or have
been claimed, to be Nakamoto.
source: [Link]

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q2

Where do you store your cryptocurrency?

Crypto Wallets

In the cryptocurrency ecosystem, the term


“wallet” refers to software, online or offline,
that allows a cryptocurrency owner to
access their cryptocurrency holdings.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q3

What is a miner?

Computers that validate and


process blockchain transactions

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q4

Where can you buy cryptocurrency?

• A private transaction
• An exchange
• A Bitcoin ATM

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q5

What is a blockchain?

a) A distributed ledger on a peer to peer network


b) A type of cryptocurrency
c) An exchange
d) A centralized ledger

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q6

What is a DApp?

A decentralized application that is


developed over blockchain platform

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q7

What is the term for when


a blockchain splits?
Fork
A bitcoin hard fork refers to a radical change to the
protocol of bitcoin's blockchain that effectively
results in two branches, one that follows the
previous protocol and one that follows the new
version. It is through this forking process that
various digital currencies with names similar to
bitcoin have been created, including bitcoin cash
and bitcoin gold. Bitcoin cash remains the most
successful hard fork of the primary cryptocurrency;
as of June 2021, it is the eleventh-largest digital
currency by market cap.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q8

What incentivizes the miners to give


correct validation of transactions?

A block Reward in form of Bitcoins

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q9

What is a hash function?

Takes an input of any length and returns a


fixed-length string of numbers and letters

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q10

What does IPFS stand for?

Interplanetary File System


The InterPlanetary File System (IPFS) is a protocol and peer-
to-peer network for storing and sharing data in a distributed file
system. IPFS uses content-addressing to uniquely identify each
file in a global namespace connecting all computing devices.[4]

InterPlanetary File System - Wikipedia

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q11

What is the maximum number of


bitcoins that can be created?

21 million

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q12

What was the highest the


Bitcoin price ever reached?

₹ 54,404,923

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q13

What is Altcoin?

Altcoins are cryptocurrencies other than Bitcoin.


Altcoin - Bitcoin Wiki

• Binance Coin (BNB)


• Cardano (ADA)
• Chainlink (LINK)
• Ether (ETH)
• Litecoin (LTC)

As of today, over 5000 of these "alternative" currencies have been created


worldwide.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q14

What is meme coin?


A meme coin (also spelled memecoin) is
a cryptocurrency that originated from
an Internet meme or has some other humorous
characteristic.[1] It may be used in the broadest
sense as a critique of the cryptocurrency.
In late 2013, Dogecoin was released after
being created as a joke on the Doge meme
by software engineers. This sparkled the
creation of several subsequent meme coins. In
October 2021, there were about 124 meme
coins circulating in the market. Notable
examples include Dogecoin and Shiba Inu,[2]
Meme coin - Wikipedia

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q15

What is This?

Dogecoin (/ˈdoʊ(d)ʒkɔɪn/ DOHJ-koyn or DOHZH-


koyn,[2] code: DOGE, symbol: Ð) is a cryptocurrency created by
software engineers Billy Markus and Jackson Palmer, who decided to
create a payment system as a "joke", making fun of the wild
speculation in cryptocurrencies at the time.[3] It is considered both the
first "meme coin", and, more specifically, the first "dog coin". Despite
its satirical nature, some consider it a legitimate investment prospect.

Doge (meme) - Wikipedia

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q16

What is Stablecoins?

Cryptocurrency but usually centralized and


pegged with some fiat money or asset class

Stablecoins are cryptocurrencies where the price is


designed to be pegged to a cryptocurrency, fiat money,
or to exchange-traded commodities (such as precious
metals or industrial metals).[1]

Stablecoin - Wikipedia

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q17

What is Token?
Token is a unit of value issued by a tech or crypto start-up, intended to
be a piece in the ecosystem of their technology platform or project.
Tokens are supported by blockchains. They only physically exist in the
form of registry entries in said blockchain. Initially, most tokens were
based on the ERC20 protocol by Ethereum.

Tokens are different from bitcoins and altcoins in that they are not mined
by their owners nor primarily meant to be traded (although they may be
traded on exchanges if the company that issued them becomes
valuable enough in the eyes of the public), but to be sold for fiat or
cryptocurrency in order to fund the start-up's tech project.

Token Definition – Cryptocurrency – BitcoinWiki

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q18

What is MetaVerse and Omniverse?

Facebook is changing its name to Metaverse to highlight the


vision of a future that will be lived in the cyberspace (along with
life in the physical space). Augmented Reality and Virtual
Reality, along with sensors, displays, artificial intelligence and
Digital Twins, are the enabling technologies.

Metaverse vs Omniverse – IEEE Future Directions

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q19

What is Sandbox and Dreamland

The Sandbox is a sandbox game for mobile phones and Microsoft


Windows, developed by gamestudio Pixowl and released on May
15, 2012. It was released for PC on Steam on 29 June 2015. The
brand was acquired by Animoca Brands in 2018, and its name
used for a blockchain-based 3D open world game.

SAND is an ERC-20 Ethereum-powered utility token that will


be the medium of exchange within The Sandbox. Facilitates
the purchase or sale of LANDs or game ASSETs (LANDs are
portions of the Metaverse open to player ownership, while
ASSETs are tokens created by players).

Metaverse vs Omniverse – IEEE Future Directions

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q20

What is NFT?
A non-fungible token (NFT) is a and non-interchangeable unit of data
stored on a blockchain, a form of digital ledger. NFTs can be associated
with reproducible digital files such as photos, videos, and audio. NFTs
use a digital ledger to provide a public certificate of authenticity or proof
of ownership, but do not restrict the sharing or copying of the underlying
digital files. The lack of interchangeability (fungibility) distinguishes NFTs
from blockchain cryptocurrencies, such as Bitcoin.

Non-fungible token - Wikipedia

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q21

What is (DAO) ?

A company or group of like-minded entities that operate based on the


rules set forth in a smart contract. DAOs are used to transform business
logic into software logic recorded on a blockchain. A company whose
funds are locked in a multisignature wallet that is controlled by a smart
contract is an example of a DAO. In that same example, board of
directors decisions might be voted on, recorded, and effected through a
smart contract rather than by holding physical board meetings.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q22

What is ETHEREUM ?
Ethereum is a decentralized Blockchain 2.0 chain. It was the first major
smart contract platform and has widespread support from Fortune 500
companies through the Ethereum Enterprise Alliance (EEA).

Ethereum currently uses a Proof-of-Work (PoW) consensus algorithm,


but future changes to the protocol will update it to a more scalable
algorithm, most likely based on Proof-of-Stake (PoS).

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q23

What is HASHRATE ?
The rate at which a particular machine can perform a specific hashing
function. Hashrate is similar to general CPU speed, but where
processor speed is measured based on the number of arbitrary
instructions a machine can carry out per second, hashrate is measured
based on the number of times a machine can perform that specific
function per second, allowing application-specific integrated circuits
(ASIC) to have a much higher hashrate than a processor with the same
clock speed.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q24

What is MAINNET ?

The largest blockchain network a specific protocol runs, or the most


valuable chain as decided by the community. Mainnets are typically
where real value is derived and represent the truest intent of the core
developers.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q25

What is ORACLE ?

Services that connect real-world data with blockchain applications.


Oracles are necessary to provide input that cannot be independently
verified, such as temperature measurements. Oracles typically rely on
the security of a trusted source rather than the security of trustlessness.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q26

What is SOLIDITY ?

A smart contract programming language built for the Ethereum Virtual


Machine. Syntactically it resembles C++ and Javascript and compiles to
eWASM.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q27

What is SOLIDITY ?

A smart contract programming language built for the Ethereum Virtual


Machine. Syntactically it resembles C++ and Javascript and compiles to
eWASM.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q28

What is TOKENIZATION ?

The concept of translating business strategies, goods, or services into


discrete, tradeable units that are recorded on a blockchain or other
system.

Physical goods can be tokenized by associating their unique identifiers


with on-chain references.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q29

What is TOKENIZATION ?

The concept of translating business strategies, goods, or services into


discrete, tradeable units that are recorded on a blockchain or other
system.

Physical goods can be tokenized by associating their unique identifiers


with on-chain references.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q30

What Is a "51% Attack"?

A 51% attack refers to a malicious actor (or group acting in concert),


controlling over 50% of the total mining power of the blockchain network
and disrupting the integrity of the blockchain.

An example of a 51% attack happened in January 2019 on the


Ethereum Classic blockchain.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Q31

ZERO-KNOWLEDGE (ZK) PROOF

A mathematical representation of an assertion whose output value can


be determined without the input information.

Zero-knowledge proofs are used to prove that an actor is in possession


of certain information without actually revealing that information. They
are especially useful in cryptocurrencies because they can be used to
show that a transaction is valid without revealing the sender, recipient,
or amount of the transaction. ZK research is still in its infancy.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q32

What Is the Blockchain Trilemma?

The blockchain trilemma is a


concept coined by Vitalik
Buterin that proposes a set of
three main issues —
decentralization, security and
scalability — that developers
encounter when building
blockchains, forcing them to
ultimately sacrifice one
"aspect" for as a trade-off to
accommodate the other two.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Beeple’s, Everydays ” The
First 5000 Days” – $69 Million
Beeple’s Everydays, the
First 5000 days is
basically one of the most
iconic NFT sales that
ever happened in the
history of the NFT world.
It not only broke the
world record but also
made. Beeple, one of
the richest artists in
the world.

The artwork was auctioned at NFT platform, Christies on March 11, 2021.
Bascially, the Everydays 5000 consists of Beeple’s entire collection of 5000 artworks
that he created since May 1, 2007. The bid on this artwork started with $100 but it
soon rose to millions ultimately settling for $69 Million dollars.
36 MOST EXPENSIVE NFTs EVER SOLD (Ranked) - NFT's Street ([Link])

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


BITS Pilani
Pilani Campus

HYPE
Gartner Hype Cycle
• The Gartner Hype Cycle is a graphical representation of
the perceived value of a technology trend or innovation—and its
relative market promotion.
• The cycle can help you understand how the perceived value of a
given technology evolves over the course of its maturity lifecycle.

Deep neural networks

Speech recognition
Predictive
analytics

4D printing Blockchain

Introduction to the
Gartner Hype Cycle –
BMC Software | Blogs BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Hype Cycle for Emerging
Technologies, 2016

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Hype Cycle for Emerging
Technologies, 2017

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Hype Cycle for Emerging
Technologies, 2018

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Hype Cycle for Blochchain
Technologies 2020

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Hype Cycle for Blockchain 2021:
More Action than Hype

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


BITS Pilani
Pilani Campus

Trends and Facts


Google Trends: Cryptocurrency,
Blockchain ans Machine Learning

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


BITCOIN Growth

BITS Pilani, Pilani Campus


Etherium Growth

BITS Pilani, Pilani Campus


Cryptocurrency Market Cap

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Key adoption drivers
• Mainstream adoption of Bitcoin, including El Salvador’s adoption of Bitcoin
as legal tender in June 2021.
• Payment network, banking and social network adoption of distributed ledger
technologies (DLTs) for money movement, with the expected deployment of
central bank digital currencies (CBDCs) being a key influencer.
• Decentralized finance (DeFi) applications offer substantially greater financial
rewards than traditional finance. Centralized firms like hedge funds already
take advantage of this.
• Tokenization of assets, including explosive growth of NFTs and DeFi tokens,
and the promise of tokens linked to physical assets in the future.
• Blockchains such as Binance, Cardano, and Solana offering viable cost-
effective alternatives to Ethereum chain transactions.
• Monumental progress in blockchain interoperability, including gateways and
abstraction middleware, already used today by DeFi applications.
• Blockchain migration from the proof-of-work (POW) consensus method (still
used for Bitcoin) to more energy-efficient consensus methods such as proof
of stake (PoS). The ongoing upgrade of Ethereum leads this trend.
Still, the picture is not all rosy. There are
plenty of challenges
• Adoption of permissioned blockchains is moving much
more slowly. Some use cases — especially around
supply chain and authenticated provenance — are
benefiting from ledger technology. However, most users
are stuck trying to align use cases to the technology.
• Global regulations and accounting standards need
clarification before most enterprises adopt
cryptocurrency
• China continues to clamp down on crypto activities as
they work on making their own CBDC the world’s
dominant currency.
Blockchain Technology
(BITS F452)
BITS Pilani Dr. Ashutosh Bhatia, Dr. Kamlesh Tiwari
Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

Introduction to Crypto and


Cryptocurrency
LECTURE OUTLINE

Crypto Background
 Hash Functions
 Digital Signatures and its Applications
Introduction to cryptocurrency
 Basic digital cash

BITS Pilani, Pilani Campus


Hash Functions

 Takes arbitrarily length of string as input


 Produces a fixed sized output
 Efficiently Computable

 Security Properties
o Collision Free
o Hiding
o Puzzle friendly

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Hash Properties 1: Collision
Resistant

BITS Pilani, Pilani Campus


How to find a collision?

 Try 2130 randomly chosen inputs and assuming that hash


output is 256 bits, 99.8% chance that two of them will collide

 This works, no matter what the hash function is. (Birthday


Paradox)

 However, 2130 is a so large number and any computer ever


made by the humanity was trying to find a collision since the
beginning of the universe till now, the probability of it finding a
collision is infinitesimally small.

BITS Pilani, Pilani Campus


How to find a collision?

 Try 2130 randomly chosen inputs and assuming that hash


output is 256 bits, 99.8% chance that two of them will collide

 This works, no matter what the hash function is. (Birthday


Paradox)

 However, 2130 is a so large number and any computer ever


made by the humanity was trying to find a collision since the
beginning of the universe till now, the probability of it finding a
collision is infinitesimally small.

BITS Pilani, Pilani Campus


Birthday Paradox

Find the probability that at-least two people in a room have the same
birthday

Event A: at least two people in the room have the same birthday
Event A’ : No people in the room have the same birthday

Thus to achieve 128 bit security against collision attacks, hashes of length at-least
256 is required
BITS Pilani, Pilani Campus
Is there a better way?

 For some possible Hash functions, YES


 Example H(x) = x mod 2256

 For others we don’t know one

 No Hash Function is proven to be collision resistant

BITS Pilani, Pilani Campus


Application: Hash as a message
digest

 If we know that H(x) = H(y)


it is safe to assume that x = y

 To recognize a file that we saw before


just remember its hash

 Useful as the hash is small

BITS Pilani, Pilani Campus


Hash Property 2: Hiding

 We want something like this


given H(x) it is infeasible to find x.

 The problem is that this property can not be true in the stated
form if the number of possible input values is small

 Hiding: A hash function H is hiding if: when a secret value r is


chosen from a probability distribution that has high min-
entropy, then given H(r | x) it is infeasible to find x.

 High min-entropy means that the distribution is very spread out


and no particular value is chosen with negligible entropy.

BITS Pilani, Pilani Campus


Application: Commitment

We want to ”seal a value” in the envelop


and ”open the envelop” later

Commit to a value and reveal it later

BITS Pilani, Pilani Campus


Commitment API

(com, key) := commit(msg)


match := verify(com, key, msg)

To seal msg in envelop


(com, key) := commit(msg), then publish com

To open envelop
publish key, msg

Anyone can use verify() to check the message

BITS Pilani, Pilani Campus


Commitment API

(com, key) := commit(msg)


match := verify(com, key, msg)

Security Properties
Hiding: Given com, infeasible to find msg
Binding: Infesible to find msg != msg’ s.t.
verify(commit(msg), msg’) = true

BITS Pilani, Pilani Campus


Commitment API

commit(msg) := (H(key | msg), key))


`where key is a random 256 bit value

verify(com, key, msg) = (H(key | msg) == com)

Security Properties
Hiding: Given H(key | msg), infeasible to find msg
Binding: Infeasible to find msg != msg’ s.t.
H(key | msg) == H(key | msg’)

BITS Pilani, Pilani Campus


Hash Property 3: Puzzle friendly

For every possible out put value y,

if k is chosen randomly from a distribution with


high min entropy,

then it is infeasible to find x such that H(k | x) = y

BITS Pilani, Pilani Campus


Application: Search Puzzle

BITS Pilani, Pilani Campus


SHA 256 hash function

Theorem: If c (the compression function) is collision-free than


SHA-256 is collision free
Blockchain Demo ([Link])
BITS Pilani, Pilani Campus
Hash Pointer

 Hash Pointer is :
pointer to where some information is stored
cryptograhic hash of the information

 If we have a hash pointer, we can


ask to get the info back
verify that it has not changed

BITS Pilani, Pilani Campus


Key Idea
Build Data Structures with Hash Pointers

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Linked List

A blockchain is a linked list that is built using hash pointers instead of pointers

BITS Pilani, Pilani Campus


Linked List: Tampering Detection

BITS Pilani, Pilani Campus


Binary Tree With Hash Pointers:
Merkle Tree

[Link]

BITS Pilani, Pilani Campus


Proof of Membership in a Merkle
Tree

BITS Pilani, Pilani Campus


Advantages of Merkle Tree

BITS Pilani, Pilani Campus


The storage problem

• Client wants to store a file on the server


• File has a name F and data D
• Client wants to retrieve F later

BITS Pilani, Pilani Campus


The storage: Basic Protocol

• Client sends F with Data D to server


• Server stored (F, D)
• Client deletes D
• Client requests F from server
• Server returns D
• Client has recovered D

BITS Pilani, Pilani Campus


The storage protocol
Against Adversaries
• What if server is adversial and returns D’ != D

• Trivial solution
• Client does not delete D
• Whenever server return D’ client can compare
D and D’

What is client does not have memory to store data for


a long time?

BITS Pilani, Pilani Campus


The storage : Hash based
protocol
• Client send file F with Data D to the server
• Server stores (F,D)
• Client stored H(D), deletes D
• Client requests F from server
• Server returns D’
• Clinet compares H(D) = H(D’)

BITS Pilani, Pilani Campus


The storage : File chunks

• What if client wants to retrieve the 19007th byte of the file


• Must download the whole file
• Merkle tree to rescue.

BITS Pilani, Pilani Campus


Merkle Tree:

• Splits file into chunks (say 1 KB)

BITS Pilani, Pilani Campus


Merkle Tree:

• Hash each chunk using cryptographic hash function

Arrows show direction of hash function application

BITS Pilani, Pilani Campus


Merkle Tree:

• Combine them to create a binary tree


• Each node stores the hash of the concatenation of their
children

BITS Pilani, Pilani Campus


Merkle Tree:

BITS Pilani, Pilani Campus


Proof of inclusion

BITS Pilani, Pilani Campus


Proof of inclusion

BITS Pilani, Pilani Campus


Proof of inclusion

BITS Pilani, Pilani Campus


Proof of inclusion

• Prover sends chunks


• Prover sends siblings along path connecting leaf to
MTR
• Verifier computes hashes along the path connecting
leaf to MTR
• Verifier checks that computer root is = MTR
• The proof of inclusion is O(logn)
• If adversay can present proof-of-inclusion for incorrect
leaf then we can break the hash function

BITS Pilani, Pilani Campus


Merkle Tree Protocol
(Optional)
MT-Construct(D)

// Constructs a Merkle Tree with given Data D


//Return the Merkle tree root

If |D| = chunk size then


MT-Construct(D) = H(D)
Else
MT-Construct(D) = H(MT-Construct(D1) || MT-
Construct(D2), where D = D1 || D2

BITS Pilani, Pilani Campus


Merkle Tree Protocol
(Optional)

BITS Pilani, Pilani Campus


Merkle Tree Protocol
(Optional)

BITS Pilani, Pilani Campus


Merkle Tree Applications

• Bitcoin uses Merkle Tree to store the transactions


• Bit-Torrent uses Merkle tree to exchange file
• Etheriun Blockchain uses Merkle-Patricia tries for
storage and transactions

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Digital Signatures
What we want from Digital
Signatures?

Only you can sign but any one can verify.


Signature is tied to a particular document

Can’t be cut and paste to another document.

BITS Pilani, Pilani Campus


API for digital signatures

(sk ; pk ) := generateKeys(keySize)
sk : secret signing key
pk : Public verification key

sig := sign(sk ; message)

isValid : = verify(pk ; message; sig)

BITS Pilani, Pilani Campus


Requirements for Signatures

Valid Signatures Verify


verify(pk ; message; sign(sk ; message)) == true

Can’t forge signatures


Adversary who, knows pk , gets to see the signature of his own
choice, can’t produce a verifiable signature on another message.

BITS Pilani, Pilani Campus


Practical Stuff ...

Algorithms to generate keys need to be randomized


So, we need a good source of randomness

Limit of message size


fix: use Hash(message) rather than message.

Fun Trick: Sign a hash pointer


Signature covers the whole structure

BITCOIN uses ECDSA standard for Digital Signatures

BITS Pilani, Pilani Campus


Useful trick: Public key ==
Identity
If you see sig such a verify(pk; msg; sig) == true

Think of it as
pk says “[msg]”

To speak for pk you must know sk

BITS Pilani, Pilani Campus


Decentralized Identity
Management

Anybody can make a new identity at anytime


make as many as you want

No central point of coordination

These identities are called “addresses” in Bitcoin

BITS Pilani, Pilani Campus


Privacy

Addresses not directly connected to real world identity

But observer can link together an address’s activity over


time

BITS Pilani, Pilani Campus


Blockchain Technology
(BITS F452)
BITS Pilani Dr. Ashutosh Bhatia, Dr. Kamlesh Tiwari
Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

A simple Cryptocurrency
Useful trick: Public key ==
Identity
If you see sig such a verify(pk; msg; sig) == true

Think of it as
pk says “[msg]”

To speak for pk you must know sk

BITS Pilani, Pilani Campus


Decentralized Identity
Management

Anybody can make a new identity at anytime


make as many as you want

No central point of coordination

These identities are called “addresses” in Bitcoin

BITS Pilani, Pilani Campus


Privacy

Addresses not directly connected to real world identity

But observer can link together an address’s activity over


time

BITS Pilani, Pilani Campus


GoofyCoin

Goofy, can create new coins

BITS Pilani, Pilani Campus


GoofyCoin

A coin’s owner can spend it

BITS Pilani, Pilani Campus


GoofyCoin

A recipient can pass the coin again

BITS Pilani, Pilani Campus


GoofyCoin

Double Spending Problem

BITS Pilani, Pilani Campus


ScroogeCoin

ScroogeCoin: Solving Double Spending Problem

Scrooge publishes a history of all the transactions in form


of a append only ledger (blockchain

Optimization: put multiple transactions in the same block

BITS Pilani, Pilani Campus


ScroogeCoin

CreateCoin Transaction create a new coin

BITS Pilani, Pilani Campus


ScroogeCoin

A Paycoin transaction consumes some coins and creates


new coins of the same value

Valid if

 Consumed coins are valid


 Not already consumed
 total value out = total value in
 signed by owners of all consumed coins

BITS Pilani, Pilani Campus


ScroogeCoin

Problem with the scrooge coin


Coins can’t be transferred, subdivided or combined

but you can get the same effect by using transactions to


sub divide:
create a new transaction, consume your coin and pay
out two new coins to yourself.

BITS Pilani, Pilani Campus


ScroogeCoin

Crucial Question
Can we de-scoogify the currency and
operate without a trusted third party

We need to figure out:


How every one agree upon a single
public block chain

How every one agree upon which


transactions are valid

How to assign IDs to coins in a


decentralized manner.

BITS Pilani, Pilani Campus


Blockchain Technology
(BITS F452)
BITS Pilani Dr. Ashutosh Bhatia, Dr. Kamlesh Tiwari
Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

Decentalized Cryptocurrency
ScroogeCoin

Crucial Question
Can we de-scoogify the currency and
operate without a trusted third party

We need to figure out:


How every one agree upon a single
public block chain

How every one agree upon which


transactions are valid

How to assign IDs to coins in a


decentralized manner.

BITS Pilani, Pilani Campus


Decentralization is not all-or-
nothing

Email: Decentralized protocol but dominated by


centralized webmail services

BITS Pilani, Pilani Campus


Aspects of Decentralization in BITCOIN

• Who maintains the ledger?


• Who has authority over which transactions are valid?
• Who creates new Bitcoins?
• Who determines how the rules of the system change?
• How do Bitcoins acquire exchange value?

Beyond the protocol: Exchange, wallet, software and


service providers

BITS Pilani, Pilani Campus


Aspects of Decentralization in BITCOIN

• Peer to Peer Network


• Open to anyone, low barrier to entry
• Currently there are several thousands of bitcoin nodes

• Mining
• open to anyone but inevitable concentration of power
often seem as undesirable.

• Updates to Software
• Core developers trusted by the community, have great
power
BITS Pilani, Pilani Campus
BITCOIN’s Key Challenge

Key technical challenge of decentralized ecash : Distributed


Consensus

or: How to decentralize ScroogeCoin

BITS Pilani, Pilani Campus


Why Consensus Protocol ?

Traditional Motivation
Reliability in Distributed Systems

Distributed Key-Value Store enables various applications


DNS, Public-Key Dictionary, Stock Trades

BITS Pilani, Pilani Campus


Defining Distributed
Consensus

There is a fix number of nodes or processes and each


of these has some input value

Protocol terminates and all correct nodes decide on the


same value

This value must have been proposed by some correct


node

BITS Pilani, Pilani Campus


BITCOIN is a P2P system

At any given time

• All nodes have sequence of blocks of transactions that


they have consensus on

• Each node has a set of outstanding transactions that they


have heard about

BITS Pilani, Pilani Campus


How Consensus could work in
BITCOIN

BITS Pilani, Pilani Campus


How Consensus could work in
BITCOIN

BITS Pilani, Pilani Campus


How Consensus could work in
BITCOIN

OK to select any valid block, even of proposed by only one node

BITS Pilani, Pilani Campus


Why Consensus is hard

Nodes may crash


Nodes may be malicious

Network is imperfect
• Not all pair of nodes connected
• Faults in network
• Latency

No notion of Global Time

BITS Pilani, Pilani Campus


Many impossibility results

• Byzentine generals problem

• Fischer-Lynch-Paterson (FLP) result says that you can't


do agreement in an Asynchronous Message
Passing system if even one crash failure is allowed,
unless you augment the basic model in some way, e.g.
by adding randomization or failure detectors.

BITS Pilani, Pilani Campus


Byzantine Generals Problem
(Optional)
• Generals = Computer Components

• The abstract problem…


– Each division of Byzantine army is directed by its own general.
– There are n Generals, some of which are traitors.
– All armies are camped outside enemy castle, observing enemy.
– Communicate with each other by messengers.
– Requirements:
• G1: All loyal generals decide upon the same plan of action
• G2: A small number of traitors cannot cause the loyal generals to adopt a
bad plan
– Note: We do not have to identify the traitors.

BITS Pilani, Pilani Campus


Some well known protocols

Example: Paxos

Nerver produces inconsistent result but can get


stuck.

BITS Pilani, Pilani Campus


BITCOIN consensus theory
and practice

BITCOIN consensus works better in practice than in theory

Theory is still catching up

BUT theory is important, can help predict unforeseen


attacks.

BITS Pilani, Pilani Campus


Some things BITCOIN does
differently

• Introduces incentives
• Possible only because it’s a currency

• Embraces randomness
• Does away with the notion of specific end point
• Consensus happen over a long time scale

BITS Pilani, Pilani Campus


BITCOIN consensus algorithm

Keep in mind that BITCOIN does this without


having any long term identities which is different
from classical distributed system.

Why don’t BITCOIN node have identities

Identity is hard in P2P system – Sybil Attack

Psedoanonymity is a goal of BITCOIN

BITS Pilani, Pilani Campus


Key Idea: Implicit Consensus

In each round a random node is picked

This node proposes a next block in the chain

Other nodes implicitly accept/reject this block


• By either extending it
• Or ignoring it and extending the chain from the earlier
block

Every block contains the hash of the block it extends

BITS Pilani, Pilani Campus


Consensus algorithm
simplified

1. New transactions are broadcast to all nodes

2. Each node collects new transactions into a block

3. In each round a random node gets to broadcast its block

4. Other nodes accept the block only if all the transaction in


the block are valid (unspent, valid signatures)

5. Nodes express their acceptance of the block by including


its hash in the next block they create.

BITS Pilani, Pilani Campus


What can a malicious node do

BITS Pilani, Pilani Campus


From Bob the merchants point
of View
Hear About CA -> B
transaction in the
blockchain first time
(1 confirmation)

Double
Spending
Attempt
Hear About CA -> B
transaction over P2P
network
(0 confirmation)

BITS Pilani, Pilani Campus


From Bob the merchants point
of View

• Double spending probability decreases exponentially with number of


confirmation
• Most common heuristic is wait for 6 confirmations

BITS Pilani, Pilani Campus


Recap

Protection against invalid transactions is cryptographic but


enforced by consensus

Protection against double spending is purely by consensus

You are never 100% sure that a transaction is in consensus


branch

Guarantee is probabilistic

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Incentives and Proof of Work


Assumption of honesty is
problematic
Can we give nodes incentives for behaving honestly.
Can we
reward the
nodes who
created
these
blocks

Can we penalize the


node who created
this block

BITS Pilani, Pilani Campus


Incentive 1 : Block Reward

Creator of block get to


Special coin-creation transaction in the block
Choose receipt address of this transaction

Value is fixed currently : 6.25 BTC halves every 4 year

If the block end up on the long term consensus branch

BITS Pilani, Pilani Campus


Finite Supply of BITCOINs

BITS Pilani, Pilani Campus


Incentive 2: Transaction Fee

Creator of a transaction can make its output value less than


to its input value

Remainder is the transaction fee and it goes to the block


creator

Purely voluntary like a tip

BITS Pilani, Pilani Campus


Remaining Problems

How to pick a random node?

How to avoid a free-for-all due to rewards?

How to prevent the Sybil attack?

BITS Pilani, Pilani Campus


Blockchain Technology
(BITS F452)
BITS Pilani Dr. Ashutosh Bhatia, Dr. Kamlesh Tiwari
Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

Proof of Work
Remaining Problems

How to pick a random node?

How to avoid a free-for-all due to rewards?

How to prevent the Sybil attack?

Are of these problems are related and have same solution :


Proof of Work

BITS Pilani, Pilani Campus


Proof of Work

To approximate selecting a random node


select node in proportion to a resource that no one can
monopolize (we hope)

• In proportion to computing power : Proof-of-Work


• In proportion to ownership: Proof-of-stake

Idea: allow nodes to compete with each other using their


computing power that implies the nodes automatically
being picked in that proportion

BITS Pilani, Pilani Campus


Equivalent views of POW

1. Select nodes in proporation to computing power

2. Let nodes compete for right to create blocks

3. Make it moderately hard to create new identities


protection against Sybill attack

BITS Pilani, Pilani Campus


Hash Puzzles

To create block, find nonce (a random


nonce
value) such that
Prev_h
Tx
H(nonce || prev_hash || tx || tx || ... || tx) <
Tx
target
Output space of hash

Target
Space If hash function is secure:
Only way to succeed is to try enough nonces until
you get lucky

BITS Pilani, Pilani Campus


POW property 1: difficult to
compute

As of Feb 2022 the bitcoin difficulty is 26.69 x 1012


hashes

It requires approximately 2.7 x 1015 hashes to create one


BITCOIN

Only some nodes bother to compete - minors

BITS Pilani, Pilani Campus


POW property 2:
parameterizable cost
Nodes automatically re-calculate the target every two weeks
Goal average time between blocks = 10 minutes

Each 2016-block interval is known as a difficulty epoch. At the


beginning of every epoch the Bitcoin network recalculates the
Current Target.
If if you put a fixed amount of H/W for mining the rate at which you find
the block depends upon the total computer power available with
others

Prob (Alice wins the next block) = fraction of


global hash power she controls

BITS Pilani, Pilani Campus


• Distribution of Bitcoin mining by
country

BITS Pilani, Pilani Campus


BITCOIN Global Hashrate

BITS Pilani, Pilani Campus


Key Security Assumptions

Attacs infeasible if majority of minors


weighted by hash power follow the protocol

This will ensure a more than 50% chance


that the next node is proposed by a honest
node

BITS Pilani, Pilani Campus


BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
Blockchain Technology

Introduction to Ethereum

Ashutosh Bhatia
BITS Pilani
[Link]@[Link]
Overview

 What is Ethereum
 Compared to Bitcoin
 Components of a public Blockchain
 Ethereum: A general purpose blockchain
 Ethereum components
 Ethereum and Turing Completeness
What is Ethereum
 Often described as “World wide computer operating under consensus”
 Computer Science Perspective
 Ethereum is a deterministic, but practically unbounded state machine, consisting of a
globally accessible singleton state and a virtual machine that applies changes to that
state according to consensus rules.
 Practical Perspective
 Open source, globally decentralized computing infrastructure that executes programs
called smart contracts and uses blockchain to synchronize and store the system’s
state change along with a cryptocurrency called ether, to meter and constrain
resource costs
 Developer Perspective
 A platform that enables developers to built decentralized applications with build-in
business logic, providing availability, auditability, transparency and neutrality, and
reducing certain counterparty risks.
Ethereum Vs BITCOIN (Commonalities)
• Open Blockchains: Trustless, Immutable, Uncensorable, No central
point of failure
• Decentralized Identify: Pseudo anonymous identify using public key
• Consensus algorithm: POW based Byzantine Fault tolerant
consensus algorithm (mining power proportional to the computer
power)
• Cryptographic primitives: use of cryptographic primitives such as
digital signatures and hashes, and a digital currency (ether).
• P2P Network: peer-to-peer network connecting participants
Ethereum Vs BITCOIN (Differences)

BITCOIN Ethereum
1. A blockchain for cryptocurrency 1. General purpose programmable
2. Asset: Bitcoins as currency blockcahin
• Primary purpose of the blockchain 2. Asset: Ether as utility currency
3. Simple and robust • Fund computations
4. primitive scriptive language, not Turing 3. Complex and feature rich
complete 4. Turing complete scripting language
5. UTXO-based 5. Account based
Birth of Ethereum
• Conceived at a time when people recognized the power of Bitcoin model
• Trying to move beyond cryptocurrency:
• a similar model with more generalized applications
• Developers Confusion:
• Either build on top of BITCOIN by trying to find
workarounds and live with the constraints imposed by
the transaction type, data types and size of the data
storage. Design anything else needed as off-chain, which
could completely negate the very reason of using the
blockcahins
• In December 2013, a young programmer and
BITCOIN enthusiast, Vitalik Burterin started sharing a
white paper outline the idea behind Ethereum
[Link] [Link]
Birth of Ethereum
• A few dozen people saw the early draft and offered feedback helping
Vitalink to evolve the proposal.
• Gavin Wood, a computer programmer was
one of the first people to reach out Vitalink
and offered his C++ programming skills in the
creation of Ethereum.
• Vitalink on Galvin contribution to Ethereum

[Link]
Ethereum’s Four Stages of Development
• Block #0 : Frontier—The initial stage of Ethereum, lasting from July 30, 2015, to
March 2016.
• Block #200,000: Ice Age—A hard fork to introduce an exponential difficulty increase, to motivate a
transition to PoS when ready.
• Block #1,150,000 Homestead—The second stage of Ethereum, launched in March
2016.
• Block #1,192,000 DAO—A hard fork that reimbursed victims of the hacked DAO contract and
caused Ethereum and Ethereum Classic to split into two competing systems.
• Block #2,463,000 Tangerine Whistle—A hard fork to change the gas calculation for certain I/O
heavy operations
• Block #2,675,000: Spurious Dragon— A hard fork to address more DoS attack vectors, and another
state clearing. Also, a replay attack protection mechanism.
• Block #4,370,000 Metropolis Byzantium—Metropolis is the third stage of Ethereum
• Serenity Ethereum 2.0, also known as Serenity or ETH 2.0, is an upgrade to Ethereum
on a number of levels. Its primary objective is to increase Ethereum's capacity for
transactions, reduce fees and make the network more sustainable.
Ethereum: A general-purpose Blockchain
• Unlike BITCOIN which tracks the state transitions for “Currency
Ownership”, the Etthreum tracks the state transition of general
purpose data expressible as key-value pair

• Similar to RAM model of a computer it stored both code and


data and uses blockchain to track the changes in this in stored
data.

• Like a general purpose computer, etherum can load the code in the state machine,
run that code and storing the resulting state change in the blockchin

• Two critical differences with general purpose computers


Governed by rules of consensus.
State is distributed globally.
Ethereum is Turing Complete
• In 1936 Alan Turing created a mathematical model for the computer consisting of
a state machine that manipulates symbols by reading an writing on a sequential
memory (Tape)
• Using this model he provided a proof to the question “Whether all problems are
solvable” (universal computability)
• He proved that there are classes of problems that are uncomptable, specially the
halting problem
• A system is said to be Turing complete if it can be used to simulate a Turing
machine.

Ethereum groundbreaking contribution is to combine a general purpose computing


architecture of a stored program computer with a decentralized blockchain thre by
creating a distributed single state world computer.
Ethereum’s Components
• P2P Network: Etherreum runs on Ethereum main network, which is
addressable on TCP port 30303 and runs a protocol called DEVp2p
DevP2P General Features
• Establishes secure P2P VPN over internet
• Connection is established through UDP or TCP protocol with remote devP2P, virtualy
anywhere

• Provides LAN over internet


• When network redirect is used, local network packets for outgoing peers are captured,
transferred through devP2P to remote peer, and there they are provided to the system just
as they have arrived from network cable.

• Share screen, data, files


• You can fire up tools to view remote desktop through firewalls, transfer files and data.

• Forwards ports.. Sends files and messages.. Redirects network..


• After connection is established, there are 1024 channels to use.
Use them to SendMessage, SendFile, StartForwading.
EVM
• state transitions are
processed by the EVM
a stack based virtual
machine that executes
byte code.
• EVM programs called
“smart contracts” are
written in high level
programming
language and
compiled to byte code
for execution in EVM.
Stack based computer
• A stack based computer do not use address field in instruction.

To evaluate a expression first it is


converted to revere Polish Notation i.e.
Post fix Notation.

• Example
• Expression: X = (A+B)*(C+D)
• Postfixed : X = AB+CD+*
Why Stack based Machine
• Traditionally, virtual machine implementers have favored stack-based
architectures over register-based due to 'simplicity of VM
implementation'
• Ease of writing a compiler back-end
• executables for stack architecture are invariably smaller than
executables for register architectures.
Why EVM and not a JVM
• complex and voluminous : a single java method can have a size up to 64KB so such
VM or language isn't space saving.
• useless features and security concerns: Network access, I/O stream, File W/R etc =>
big security issues.
• think of it, you can write a code which ping (of death) another machine or access protected files or
even steal the miner's private keys.
• file "write/read" feature could break the whole system's security. so we'll need to get rid of all
these features, which is a hard task to achieve for a licensed VM.
• We need to remember that a Blockchain VM should be isolated without the capacity to
communicate with the external environment.
• Imagine you have a Java bytecode with a rand(), what would be the result and how to
reach the consensus then?.
• Weak DDoS resistance : how to set a gas-like system in a complex VM like Java VM? .
• JAVA VM is a licensed Sun product, so you can't customize it to integrate it to the
Ethereum's environment
• (for example how would you calculate gas cost to avoid Dos attacks?)? to overcome this problem
you need to write your own Java VM which is a complex task read
Ethereum’s Components: Data Structures
• Ethereum database is stored locally on each node as a database (usually
Google’s LevelDB), which contains transactiions and system state in a serialized
hased data structure called Merkle Patricia Trie (MPT).
• Basically, MPT is a combination of Patricia trie and Merkle tree, with few
additional optimizations that fit the characteristics of Ethereum.
• Patricia trie is a data structure which is also called Prefix tree, radix tree or trie.
• Trie uses a key as a path so the nodes that share the same prefix can also share
the same path.
• This structure is fastest at finding common prefixes, simple to implement, and
requires small memory.
• Thereby, it is commonly used for implementing routing tables, systems that are
used in low specification machines like the router.
Patricia Trie: Example
• A trie for keys "A", "to", "tea", "ted", "ten", "i", "in", and "inn". Each
complete English word has an arbitrary integer value associated with it.
Merkle Tree
Merkle tree is a tree of hashes. Leaf nodes store data. Parent nodes contain their
children’s hash as well as the hashed value of the sum of their children’s hashes.
Since all the nodes except for leaf nodes contain a hash, the Merkle tree is also
known as a hash tree.
Prefix, Merkle and Petricia Tree
Merkle Patricia Trie
The Merkle Patricia Trie defines three types of nodes

• Branch – a 17-item node [𝑖0,𝑖1, ...,𝑖15, 𝑣𝑎𝑙𝑢𝑒]


• Extension – A 2-item node [𝑝𝑎𝑡ℎ, 𝑣𝑎𝑙𝑢𝑒]
• Leaf – A 2-item node [𝑝𝑎𝑡ℎ, 𝑣𝑎𝑙𝑢𝑒]
Merkle Patricia Trie
1. All the keys have the same prefix 1111 and
for this reason the extension node is
created as a root

2. Then the keys start to differ, which is


captured by creating the branch node. This
node branches for characters at the same
position of all keys. In particular, branches
are created for characters ‘0’, ‘2’, and ‘𝐹 ’.

3. The key having solely ‘1111’ terminates


here, which means that the value for this
key is stored in this branch node.

4. Rest of the keys form leaf nodes as there is


no more branching. The leaf nodes store
suffixes of each key and store values for the
keys as well.
Ethereum encoded merkle petricia Tree
Recursive Length Prefix
HP: Hex Prefix Encoding
Merkle Patricia Trie
• In the MPT, there is
one more type of
nodes apart from the
branch nodes and the
leaf nodes. They are
extension nodes.

• An extension node is
an optimized node of
the branch node.
State Trie Architecture
The Ethereum State Trie has four types:
1. world state trie,
2. transaction trie
3. transaction receipt trie
4. and account storage trie.

Each state trie is constructed with Merkle Patricia Trie and only root
node (top node of state trie) is stored in block to spare storage.
Blocks in Ethereum
• We can find that a block 𝐵 contains a header 𝐻, transactions 𝑇 and
ommers, sometimes referred to as uncles 𝑈 :
𝐵 = (𝐻,𝑇 ,𝑈 )
Block Header
• parentHash The Keccak 256 bit hash of the parent block. This field connects blocks in a chain.
• ommersHash The Keccak 256 bit hash of list of ommers.
• beneficiary An account address of a user who mined this block and receives reward.
• stateRoot The Keccak 256 bit hash of a root of the World State Trie.
• receiptsRoot The Keccak 256 bit hash of a root of the Transaction Receipt Trie.
• transactionsRoot The Keccak 256 bit hash of a root of the Transaction Trie.
• logsBloom A filter relating logs hashes with the log records.
• difficulty A scalar value corresponding to an effort that has to be undertaken to mine this block.
• number A scalar value equivalent to an ordinal number of this block. Every new block in the chain gets a number
increased by one.
• gasLimit A scalar value containing an accumulated gas limit required to process all transactions in this block.
• gasUsed A scalar value containing an accumulated real consumed gas to process all transactions in this block.
• extraData A free form, 32 bytes or less long byte array, containing any additional data.
• mixHash The Keccak 256 bit hash confirming that a sufficient computation has been spent on mining this block.
• nonce A 64 bit value. This value combined with mixHash also proves that the computation has been spend for
mining this block.
Transactions Trie
A transaction is mapped in the trie so that the key is a transaction 𝑖𝑛𝑑𝑒𝑥 and the value is the
transaction 𝑇 . Both the transaction index and the transaction itself are 𝑅𝐿𝑃 encoded. It compose a
key-value pair, stored in the trie:
𝑅𝐿𝑃 (𝑖𝑛𝑑𝑒𝑥) → 𝑅𝐿𝑃 (𝑇 )

• Nonce: an ordinal number of a transaction. For every new transaction submitted by the same
sender, the nonce is increased. Prevents sending the same transaction twice.
• gasPrice: A value indicating current price of gas.
• gasLimit: A value indicating maximal amount of gas the sender is able to spend on executing this
transaction.
• to: Address of an account to receive funds, or zero for contract creation.
• value: Amount of funds to transfer between external accounts, or initial balance of an account for
a new contract.
• init: EVM initialization code for new contract creation.
• data: Input data for a message call together with the message (i.e. a method) signature.
• v, r, s: Values encoding signature of a sender.
Transactions Trie

Three types of transactions and the mapping of respective fields


Contract Creation
Message Calls
• Message call execution of a method triggerd by a special transaction which
has non-empty field data
• The transaction that calls a contract cobines both the method signature
and the input data into the data field
• The method signature is stored in hashed form followed by the input data
• The data field is encoded in standardized binary format Abstract Binary
Interface
• Contracts may call methods of other contracts via internal transactions.
• Internal transactions are not recorded in the blockchain
• They do not have the gas limit and consumed gas is billed against the
source caller
• This allows creating libraries which are not priced themselves
Transaction Receipt
• When a transaction is submitted to a blockchain, it is not executed
immediately.
• First executes the transaction the miner, who potentially put it in the
block.
• Then, the transaction becomes part of the blockchain and all
participating nodes will sooner or later synchronize, i.e. execute the
transaction.
• Because of this process, a user submitting originally the transaction
cannot have its results immediately.
Transaction Receipt Trie
• As a solution, result of each transaction execution is captured in the
Transaction Receipt Trie.
• One entry in this trie is created for each transaction
• Optionally, the trie may contain log messages generated by smart
contracts.
• By analyzing the Receipts Trie, the user can study log messages to get
deeper insight.
• Ethereum nodes provide an API that allows the user to register for
events and get notifications when a transaction receipt has arrived.
Transaction Receipt Trie
• The Receipt Trie has following structure. The key is a transaction
𝑖𝑛𝑑𝑒𝑥 and the value is a receipt 𝑅. They compose a key-value pair:
𝑅𝐿𝑃 (𝑖𝑛𝑑𝑒𝑥) → 𝑅𝐿𝑃 (𝑅)

The receipt 𝑅 has following fields:


• Cumulative gas used in a respective block after execution of current
transaction.
• Set of logs printed by this transaction
• A Bloom Filter containing hashes of log entries
• A status code of the transaction result, expressed as a number. It
semantics is application dependent.
Blooms Filter
Standard Bloom Filter
Bloom filter example
Standard Bloom Filter (cont.)
False positive probability
False positive rate vs. k
Message Logs
• The Receipt Trie can contain a set of log messages, produced by smart
contract.
• In the case of Solidity, the log message is emitted via a keyword emit.
• The set of logs contains tuples with following items:
• A contract account address, who triggered the log, i.e. executed this Smart
Contract.
• A sequence of 32 bytes long containing event topics.
• A sequence of bytes containing the log message itself
• The log messages may contain any arbitrary data and every message
may be assigned to a topic. This way clients may listen only to
messages from certain topics if they are not interested in all log
messages.
Log Event Updates
Transaction Receipt
World State Trie
• Also known as State Trie or Global State Trie
• In contract to Trasaction Trie it is mutable data structure
• World state trie is a mapping between addresses and account states.
• Keccak(address) -> RLP(A)
• It can be seen as a global state that is constantly updated by transaction executions.
• The Ethereum network is a decentralized computer and state trie is considered as
hard drive.
• All the information about accounts are stored in world state trie and you can retrieve
information by querying it.
• World state trie is closely related to account storage trie because it has “storageRoot”
field that points the root node in account storage trie.
World state trie node fields
• nonce
• Number of transactions sent from this address (if
this is an External Owned Account - EOA) or the
number of contract-creations made by this account
• balance
• Total Ether (in Wei) owned by this account.
• storageRoot
• A 256-bit hash root of the account storage trie.
Empty for EOAs
• codeHash
• Hash of EVM code. The bytecode is stored in
undelying database under this hash key. Empty for
EOA
One important details about the account state is that all fields (except the codeHash)
are mutable.
Account Storage Trie
• Account Storage Trie is where data associated with an account is stored.
• Accessed via storageRroot field in world state trie account
• This try is directly modified using smart contract byte code SLOAD and
SSTORE
• Every key in this trie is an index of a slot stored in the leaf node
• Index represent one of more global variable determined at the compile
time
• Keccak(index) -> RLP(slot)

• Smart contract data is persisted in the account storage trie as a mapping


between 32-bytes integers.
Storage
Trie
Updates
Smart Contract Programming
• Solidity (javascript based), most popular
 Not yet as functional as other, more mature, programming
languages
• Serpent (python based)
• LLL (lisp based)

1
Smart Contract Programming
Solidity
Solidity is a language similar to JavaScript which allows you to develop contracts and compile to
EVM bytecode. It is currently the flagship language of Ethereum and the most popular.
• Solidity Documentation - Solidity is the flagship Ethereum high level language that is used to
write contracts.
• Solidity online realtime compiler

Serpent
Serpent is a language similar to Python which can be used to develop contracts and compile to
EVM bytecode. It is intended to be maximally clean and simple, combining many of the
efficiency benefits of a low-level language with ease-of-use in programming style, and at the
same time adding special domain-specific features for contract programming. Serpent is
compiled using LLL.
• Serpent on the ethereum wiki
2
• Serpent EVM compiler
Smart Contract Programming

Atom Ethereum interface - Plugin for the Atom editor that features
syntax highlighting, compilation and a runtime environment (requires
backend node).
Atom Solidity Linter - Plugin for the Atom editor that provides Solidity
linting.

Vim Solidity - Plugin for the Vim editor providing syntax highlighting.
Vim Syntastic - Plugin for the Vim editor providing compile checking.

3
Smart Contract Programming: Solidity
contract Example {

uint value;

function setValue(uint pValue)


{ value = pValue;
}

function getValue() returns (uint)


{ return value;
}

4
Smart Contract Programming: Solidity
var logIncrement =
[Link]({sender: userAddress,
uint value});

[Link](function(err, result) {
// do something with result
})

5
Development Workflow
Testing Cycle

Create Fund Develop Compile Sign & Interact &


Account Account Deploy Test

● Onboard Additional Users


● Create New Accounts
● Develop New Applications

6
Development Workflow: Create Account
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• Programmatically: Go, Python, C++, JavaScript, Haskell


• Tools
 [Link]
 MetaMask
 TestRPC
 Many other websites
7
Development Workflow: Fund Account
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• From friends
• Faucet
• Exchanges (for public blockchain)

8
Development Workflow: Develop
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

• Ethereum Application Components:


 Base application: can be developed in any language
 Smart contract: developed in Solidity or one of the other
contract compatible languages
 Connector library: facilitates communication between base
application and smart contracts (Metamask)

9
Development Workflow: Sign and Deploy
Create Fund Develop Compile Sign & Interact &
Account Account Deploy Test

Transaction
Sign
Signed tx
Deploy Live Smart
Contract

Bytecodes Connector*

*Library that facilitates communication and


connection with Blockchain; Connects your code to a
running node. 10
Development Workflow: TestRPC
Create Fund Develop Compile Sign & Interact
Account Account Deploy &
Test

TestRPC/TestChain
• Local development or Test Blockchain
• [Link]

11
Development Workflow: TestRPC
• EthereumJS TestRPC: [Link] is
suited for development and testing
• It's a complete blockchain-in-memory that runs only on your
development machine
• It processes transactions instantly instead of waiting for the
default block time – so you can test that your code works quickly
– and it tells you immediately when your smart contracts run into
errors
• It also makes a great client for automated testing
• Truffle knows how to use its special features to speed up test
runtime by almost 90%.
12
Blockchain Technology

Introduction to Ethereum
Tokens

Ashutosh Bhatia
BITS Pilani
[Link]@[Link]
Token on Blockchain
• Block chain based abstractions (logical entities) that can
owned and that represent asset, currency access rights
etc.

• Unlike physical token that are not really exchange and


often restricted to specific businesses, organization and
locations
How token are used in Blockchain
• Currency : A token can serve as a form of currency, with a value determined
through private trade.
• Resource : A token can represent a resource earned or produced in a sharing
economy. Ex. storage or CPU token representing resources
• Asset: A token can represent ownership of an intrinsic or extrinsic, tangible or
intangible asset; Ex. gold, real estate, a car, oil, energy, etc.
• Access: A token can represent access rights and grant access to a digital or
physical property, such as a discussion forum, an exclusive website, a hotel room,
or a rental car.
• Voting: A token can represent voting rights in a digital or legal system.
• Collectible: A token can represent a digital collectible (e.g., CryptoPunks) or
physical collectible (e.g., a painting).
• Identity: A token can represent a digital identity (e.g., avatar) or legal identity
(e.g., national ID).
Tokens and Fungibility
• In economics, fungibility is the property of a good or a commodity
whose individual units are essentially interchangeable.
• Tokens are fungible when we can substitute any single unit of the
token for another without any difference in its value or function.
• Non-fungible tokens are tokens that each represent a unique tangible
or intangible item and therefore are not interchangeable.
• Digital Collectables: In CryptoKitties you can breed and adopt Kitties of all
colours and shapes. Create Collections of your favourite cats and share them
with our breeding community.
Counterparty Risks
• Counterparty risk is the risk that the other party in a transaction will
fail to meet their obligations.
• when an asset is traded indirectly through the exchange of a token of
ownership, there is additional counterparty risk from the custodian of
the asset.
• Do they have the asset?
• Will they recognize (or allow) the transfer of ownership based on the transfer
of a token (such as a certificate, deed, title, or digital token)?
• In the world of digital tokens representing assets, as in the non-digital world,
it is important to understand who holds the asset that is represented by the
token and what rules apply to that underlying asset.
Tokens on Ethereum
• Blockchain tokens existed before Ethereum. In some ways, the first
blockchain currency, Bitcoin, is a token itself.
• Many token platforms were also developed on Bitcoin and other
cryptocurrencies before Ethereum.
• However, the introduction of the first token standard on Ethereum led
to an explosion of tokens.
• Vitalik Buterin suggested tokens as one of the most obvious and useful
applications of a generalized programmable blockchain such as
Ethereum.
Tokens on Ethereum
• Tokens are different from ether because the Ethereum protocol does not know
anything about them.
• Sending ether is an intrinsic action of the Ethereum platform, but sending or even
owning tokens is not.
• The ether balance of Ethereum accounts is handled at the protocol level, whereas
the token balance of Ethereum accounts is handled at the smart contract level.
• In order to create a new token on Ethereum, you must create a new smart
contract.
• Once deployed, the smart contract handles everything, including ownership,
transfers, and access rights.
• You can write your smart contract to perform all the necessary actions any way you
want, but it is probably wisest to follow an existing standard.
• We will look at such standards next. We discuss the pros and cons of the following
standards
The ERC20 Token Standard
• The first standard was introduced in November 2015 by Fabian Vogelsteller
as an Ethereum Request for Comments (ERC).
• It was automatically assigned GitHub issue number 20, giving rise to the
name “ERC20 token.”
• The vast majority of tokens are currently based on the ERC20 standard.
• ERC20 is a standard for fungible tokens
• different units of an ERC20 token are interchangeable
• The ERC20 standard defines a common interface for contracts
implementing a token, such that any compatible token can be accessed and
used in the same way.
• The interface consists of a number of functions that must be present in every
implementation of the standard, as well as some optional functions and attributes
that may be added by developers.
Using Tokens: Utility or Equity
• Almost all projects in Ethereum today launch with some kind of
token. But do all these projects really need tokens?
• The majority of projects are using tokens in one of two ways: either as
“utility tokens” or as “equity tokens.”
• Utility tokens is required to gain access to a service, application, or
resource.
• Examples of utility tokens include tokens that represent resources such as
shared storage, or access to services such as social media networks.
• Equity tokens represent shares in the control or ownership of
something.
• Equity tokens can be as limited as nonvoting shares for distribution of
dividends and profits, or as expansive as voting shares in a decentralized
autonomous organization
Utility Tokens: Who Needs Them?
• The real problem is that utility tokens introduce significant risks and adoption
barriers for startups.
• Perhaps in a distant future “tokenize all the things” will become reality, but at
present the set of people who have an understanding of and desire to use a
token is a subset of the already small cryptocurrency market.
• For a startup, each innovation represents a risk that works as the barrier for the
adoption of the technology by the users
• Still a very small portion of the world believe in blockchain technology
• Only a subset of those people would be ready to use the service offered by your innovation
over this technology
• Adding utility tokens to that may further reduce the degree of adoption of the project.
• Nevertheless, some of the most innovative business ideas are indeed taking
place in the crypto realm.
• If regulators are not quick enough to adopt laws and support new business models,
entrepreneurs and associated talent will seek to operate in other jurisdictions that are
more crypto-friendly. This is already happening.
ERC20: functions and events
• An ERC20-compliant token contract must provide at least the following functions and
events:
• totalSupply : Returns the total units of this token that currently exist. ERC20 tokens can
have a fixed or a variable supply.
• balanceOf: Given an address, returns the token balance of that address.
• transfer: Given an address and amount, transfers that amount of tokens to that address,
from the balance of the address that executed the transfer.
• transferFrom : Given a sender, recipient, and amount, transfers tokens from one account
to another. Used in combination with approve.
• Approve : Given a recipient address and amount, authorizes that address to execute
several transfers up to that amount, from the account that issued the approval.
• Allowance : Given an owner address and a spender address, returns the remaining
amount that the spender is approved to withdraw from the owner.
• Transfer: Event triggered upon a successful transfer (call to transfer or transferFrom)
(even for zero-value transfers).
• Approval: Event logged upon a successful call to approve.
Solidity Class Examples
Tuesday, May 16, 2023 2:40 PM

[Link]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Greeter {

//Like functions, state variables can be declared with different levels of visibility modifiers,
including public, internal, and private.
//Note that all data on blockchain is publicly visible from the outside world.
//State variable modifiers only restrict how the data can be interacted with from within the
contract or other contracts.
string private greeting = "Hello, World!";

//The solidity language provides two types of addresses: one is address and the other is address
payable.
//The difference between them is that address payable gives access to the transfer and send
methods, and variables of this type can also receive ether.
//We are not sending ether to this address and we can use the address type for our purposes.
address private _owner;

constructor() {
_owner = [Link];
}

// We need to update the function to be a view function since we are now going to access data
stored on the blockchain.
function greet() external view returns (string memory) {
return greeting;
}
// The external modifier function can not be called from within the smart contract inwhich it is
defined. We can call it from other contracts or transactions.
// internal and private functions must use the implicit receiver, can not be called on an object or
on this.
//The major difference between these two modifiers is that private functions are only visible
within the contract in which they are defined, and not in the derived contracts.
// Functions that will not alter the state of the contract’s variables can be marked as either pure or
view. The pure function do not read data from the blockchain.
// Instead, they operate on the data passed in or, in the case, data that did not need any input at
all e.g. return a string “hello world”. The view functions are allowed to read data from the
blockchain, but again they are restricted in that they can not write to the blockchain.
// We can indicate that the returned value is not referencing anything located in our contract’s
persisted storage by using the keyword memory.

// We want to add another function that allows us to set the message that will be returned by our
greet() function.
// Our setGreeting function is intended to update the state of our contract with a new greeting,
which means we need to accept a parameter for this new value.
//because this function is being called from outside world, the data being passed in the parameter
is not part of the contract's persisted storage, so it must be labelled with the data location calldata.
The calldata location is only needed when the function is declared as external and when the data
type of the parameter is a reference type such as a mapping, struct, or array.

Compre Page 1
// In order to update a variable in one function, and have that variable be available in another
function, we will need to store the data in the contract's persisted storage by using state variable.

function setGreeting(string calldata _greeting) external onlyOwner{


greeting = _greeting;
}

// The modifier syntax looks very much similar like function syntax but without the visibility
declaration.
// The first argument of require function is an expression that will evaluate to a boolean. When
this expression results in false,
//the transaction is completely reverted, meaning that all state changes are reversed and the
program stops execution.
// second argument is optional.
// _; line is where the function that is being modified will be called. If you put anything after this
line, it will be run after the function body completes.
modifier onlyOwner() {
require([Link] == _owner, "Ownable: caller is not the owner");
_;
}

//we want to set the owner of the greeter contract to the address that deployed the contract.
//This means we will need to store the address during initialization, and for that, we will need to
write a constructor function.
//We will also need to access some information from the msg object which is globally available.
//To check that owner exist, we can invoke an owner getter function. Since this is a getter
function, we need to add a state variable that will hold the address of the owner, and then our
function should return that address.

function owner() public view returns(address) {


return _owner;
}
}

[Link]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract bank {

mapping(address => uint256) private balances;


address owner;

constructor() {
owner = [Link];
}

function deposit() payable public {


balances[[Link]] = balances[[Link]] + [Link];
}

function withdraw(uint256 _amount) payable public {


require(balances[[Link]] >= _amount);
balances[[Link]] = balances[[Link]] - _amount;
payable([Link]).transfer(_amount);
}

Compre Page 2
function transfer(address _to, uint256 _value) public {

require(balances[[Link]] >= _value);


_transfer([Link], _to, _value);
}

function _transfer(address _from, address _to, uint256 _value) internal {


require(_to != address(0));
balances[_from] -= _value;
balances[_to] += _value;
payable(_to).transfer(_value);
}

function balance() view public returns (uint256) {


return balances[[Link]];
}
}

ERC20_Token.sol
pragma solidity ^0.5.0;

//import "contracts/[Link]";

contract Token {
// using SafeMath for uint256;

string public name = "DApp Token";


string public symbol = "DAPP";
uint256 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address =>uint256)) public allowance;//person=>exchange=>
amount

//event
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);

constructor() public {
totalSupply = 1000000 * (10 ** decimals);
balanceOf[[Link]] = totalSupply;
}

function transfer(address _to, uint256 _value) public returns (bool success) {

require(balanceOf[[Link]] >= _value);


_transfer([Link], _to, _value);
return true;
}

function _transfer(address _from, address _to, uint256 _value) internal {


require(_to != address(0));
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}

Compre Page 3
//approval
function approve(address _spender, uint256 _value) public returns (bool success){
require(_spender != address(0));
allowance[[Link]][_spender] = _value;
emit Approval([Link], _spender, _value);
return true;
}

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(balanceOf[_from] >= _value);
require(allowance[_from][[Link]] >= _value);
allowance[_from][[Link]] -= _value;
_transfer(_from, _to, _value);
return true;
}

function _allowance(address owner, address spender) public view returns (uint256) {


return allowance[owner][spender];
}
}

ERC20_Token_using_Inheritance.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "[Link]
contracts/blob/master/contracts/token/ERC20/[Link]";

contract WILPSmartToken is ERC20 {


constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
_mint([Link], 1000 * 10 ** 18);
}
}

Compre Page 4
Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the
Ethereum network. Since each Ethereum transaction requires computational resources to execute, each transaction
requires a fee. Gas refers to the fee required to conduct a transaction on Ethereum successfully. Gas fees are paid in
Ethereum's native currency, ether (ETH). Gas prices are denoted in gwei, which itself is a denomination of ETH - each gwei
is equal to 0.000000001 ETH (10-9 ETH). Wei itself is the smallest unit of ETH. Total fee would have been: Gas units (limit)
* Gas price per unit. Before the London Upgrade, miners would receive the total gas fee from any transaction included in a
block.
Gas is a reference to the computation required to process the transaction by a validator.

AFTER THE LONDON UPGRADE


The total fee would now be: units of gas used * (base fee + priority fee) where the base fee is a value set by the protocol and
the priority fee is a value set by the user as a tip to the validator. Validator receives the tip of units of gas used * priority fee.
Base fee of units of gas used * base fee is burned.

In short, gas fees help keep the Ethereum network secure. By requiring a fee for every computation executed on the
network, we prevent bad actors from spamming the network. In order to avoid accidental or hostile infinite loops or other
computational wastage in code, each transaction is required to set a limit to how many computational steps of code
execution it can use. The fundamental unit of computation is "gas".

Although a transaction includes a limit, any gas not used in a transaction is returned to the user (i.e. max fee - (base fee +
tip) is returned). Gas limit refers to the maximum amount of gas you are willing to consume on a transaction. A standard
ETH transfer requires a gas limit of 21,000 units of gas.

For example, if you put a gas limit of 50,000 for a simple ETH transfer, the EVM
would consume 21,000, and you would get back the remaining 29,000. However, if
you specify too little gas, for example, a gas limit of 20,000 for a simple ETH
transfer, the EVM will consume your 20,000 gas units attempting to fulfill the
transaction, but it will not complete. The EVM then reverts any changes, but since
the miner has already done 20k gas units worth of work, that gas is consumed.

High gas fees are due to the popularity of Ethereum. Gas price alone does not actually determine how much we have to pay
for a particular transaction. To calculate the transaction fee, we have to multiply the gas used by the base gas fee, which is
measured in gwei.

Transaction: Transactions are cryptographically signed instructions from accounts. An account will initiate a transaction to
update the state of the Ethereum network. The simplest transaction is transferring ETH from one account to another.

An Ethereum transaction refers to an action initiated by an externally-owned account, in other words an account managed
by a human, not a contract. For example, if Bob sends Alice 1 ETH, Bob's account must be debited and Alice's must be
credited. This state-changing action takes place within a transaction. Transactions, which change the state of the EVM, need
to be broadcast to the whole network. Any node can broadcast a request for a transaction to be executed on the EVM; after
this happens, a validator will execute the transaction and propagate the resulting state change to the rest of the network.

Contract deployment transactions: a transaction without a 'to' address, where the data field is used for the contract code.
Regular transactions: a transaction from one account to another.
Execution of a contract: a transaction that interacts with a deployed smart contract. In this case, 'to' address is the smart
contract address.
Simple transfer transactions require 21000 units of Gas.

Agenda
1) Write a smart contract – A simple bank
Functionality:
1.a) Deposit some ether in the bank
1.b) Withdraw ether from the bank
1.c) Transfer ether from one account to another account
1.d) Check the balance corresponding to a account in the bank

2) Require an IDE such as remix online IDE, truffle, or any other to write smart contract and connect to the
blockchain network

3) Deploy the smart contract onto a Ethereum blockchain network (mainnet, testnets, local private blockchain
network such as Ganache)
3.a) Install Ganache
3.b) Install Metamask extension in the browser
3.c) Add the Ganache network in the metamask
3.d) Import Ganache accounts in the metamask
3.e) Connect the remix online IDE with the metamask
3.f) Select the Injected Provider – Metamask in the environment dropdown in remix online IDE
Note: If we use some testnet, we need to borrow some fake ether from the faucet (tool to get testnet ether).
4) Interact with the deployed smart contract

We will write a smart contract for depositing, withdrawing, and transferring functionality in a bank. This smart
contract will act as a bank where we can deposit and withdraw the ether, and transfer the ether from one address
to another address. We will also include a functionality to check the balance in an individual address.
As we know, there are two types of account addresses in Ethereum -
1) Externally-owned account (EOA) – controlled by anyone with the private keys
2) Contract account – a smart contract deployed to the network, controlled by code
Both account types have the ability to:
1) Receive, hold and send ETH and tokens
2) Interact with deployed smart contracts
 To write smart contracts, we require an IDE which allows us to write the smart contract and to connect
to one of the Ethereum blockchain network. There are different IDEs available such as remix online
IDE, truffle, and others.

 Once a smart contract is written, now we need to deploy this smart contract onto a Ethereum blockchain.
A blockchain is nothing but a peer to peer network of nodes maintaining a synchronized ledger in the
form of blocks connecting to each other through the hashes of the blocks. A block is nothing but a
collection of transactions made by users or even smart contracts. These transactions are validated by the
miners available in the blockchain network.
 So we need a Ethereum blockchain network through which users communicate. There are different
networks available – mainnet (real Ethereum blockchain network where we need real ether to
communicate in this network), testnet (different testnets are available such as Rinkeby, Goerli, and
others where we need fake ether to communicate.), local private Ethereum blockchain network such as
Ganache (where we need fake ether to communicate).
 Each node in the network is associated with an address (externally-owned account address) through
which we communicate in the network. Ganache provides us default 10 accounts with 100 fake ethers.
We can use these addresses to communicate with any other network as well. We need a wallet to
maintain the ethers in the account. We need a private key to sign the transactions. We need a browser
that can communicate with the blockchain network. Generally, all these are handled by a wallet called
metamask itself. Metamask is a crypto wallet & a gateway to blockchain apps. MetaMask provides the
simplest yet most secure way to connect to blockchain-based applications. MetaMask is an extension for
accessing Ethereum enabled distributed applications, or "Dapps" in your browser! The extension injects
the Ethereum web3 API into every website's javascript context, so that dapps can read from the
blockchain. MetaMask generates passwords and keys on your device, so only you have access to your
accounts and data.

Fundamentals and characteristics of Ethereum Blockchain: These Ethereum fundamentals form the foundation
for understanding how to design and develop decentralized applications.

1. Ether and Networks: The Ethereum protocol has its own currency, called ether (denoted by
ETH). The fundamental use of this currency is to pay block creators (minors or validators) to
include, validate and execute the transactions in blocks. The smallest unit of a ether is called a
wei (1 ether = 1018 wei). There are other units as well such as Gwei and others. While there is a
single Ethereum protocol, there is more than one network running that protocol such as
mainnet, testnet, and local private Ethereum network. The public Ethereum network is referred
as “mainnet” where the ether has real-world value. There are public test networks or “testnets”
available to test the smart contracts with fake ether. Testnets are just a replica of public
Ethereum network. Each testnet has its own faucet used to provide fake ethers. It is also
possible to create private networks running Ethereum, similar to how a private “internet” is
called an “intranet”. For instance, Ganache is a tool that creates a local private Ethereum
network with accounts having fake ethers. Ganache is kind of a simulator that allows to you to
test the smart contracts and application. Ganache is mostly used for research purpose where you
have to run 1000s of transactions at one go. Since ganache is a local network, it is fast
compared to testnets.
2. Gas and Transaction Cost: There are different programming languages available to write the
smart contract codes in Ethereum. Solidity is one of the popular programming languages. Like
other programming languages, solidity also has a compiler which compiles the solidity code to
bytecode, which provides a series of opcodes to the EVM. An opcode is an instruction such as
PUSH 1 or MLOAD that is understood by EVM. Each of these opcodes has an associated gas
cost. Note that a transaction contains bytecodes. The gas concept is used to decouple the price
of ether from Ethereum’s transaction fees. To decouple the exchange rate between gas and ether,
every Ethereum transaction sets its own gas price to determine how many wei a single unit of
gas costs. As block creators decide which transactions to include in a block, they are
incentivized to include the transactions that will give them the most generous gas price for their
computations. The gas price is dynamic depending on the market rate. Therefore, you should set
the gas price equal or above market rate so that the minors can select your transactions to be
added in the block. Each Ethereum transaction has to include gas and gas price attributes, which
when multiplied will set the maximum transaction fee for the transaction. This gas attribute sets
a limit to how many computations the transaction can perform. If that limit is reached, the smart
contract execution reverts, but the transaction is still written to the blockchain, and the fees are
consumed by the block creator. If the smart contract call completes with leftover gas, the gas is
returned to the transaction creator. Each block is specified with a gas limit. The sum of the gas
used across all transactions in a block cannot exceed the block’s specified gaslimit. This also
means that no single transaction’s gas usage can exceed the block’s gaslimit.
3. Accounts: There are two types of account in Ethereum blockchain. 1) Externally owned account
(EOA): can send ether from one EOA to another EOA. 2) Smart contract account. Both are also
identified by the Ethereum address. Additionally, Ethereum transactions can be sent from an
EOA to smart contracts. Every transaction in the Ethereum blockchain is initiated by an EOA.
Smart contracts can’t spontaneously perform an action. They can call other smart contracts, but
every transaction originates from an EOA. When contracts are called, they can emit events,
store data, receive ether, send ether to EOAs, or send data or ether to other contracts.
4. Contracts: Like object oriented parlance, a contract is really a class, or a collection of state
variables, and functions. There are two types of solidity functions: read-only and write-only.
Read-only functions are denoted with the pure and view keywords. Such functions cannot
change the state of the contracts or emit events, therefore, can be called without paying any gas
costs, and there will be no transaction created. There is no additional keyword with write-only
functions. They can return data, but due to the asynchronous nature of Ethereum, the return data
is practically useless. The function data must be sent via transaction and included in a block in
order to for the function to be executed. They change the state of the contracts and often emits
one or more events in the process. The purpose of events in Ethereum is generally twofold: to
provide a custom historical log of what has occurred in the contract, and to allow observers to
subscribe to real-time updates. Due to the open nature of blockchain, we already have a
historical ledger of everything, but events provide more domain-specific logging and updates.
5. Transaction: A transaction can have an arbitrary number of contracts involved in its execution, provided
that its execution fits within the constraints of the block’s gaslimit. Solidity exposes a number of other
transaction-related attributes, but groups them into a message (msg) abstraction. Message refer to the
communication between contracts and anything that can call them, such as other contracts. For example,
a contract function call will always have a [Link]. That [Link] could be equal to the [Link] or
the creator of the transaction, or it could be the address of an intermediatory contract. Solidity’s message
(msg) attributes are as follows: data (raw bytes of data sent to the currently executed function), sender
(address of the caller of the currently executed external or public function), sig (a function identifier,
first four bytes of the calldata determine which function is being called.), value (amount of wei sent to
this function), timestamp, blockhash, difficulty, gaslimit, coinbase (address of block creator). To check
the time reported by the computer the program is running on, we use [Link]. This is the time
that the block was added to the blockchain. For every transaction in that block, the [Link]
attribute will be identical. Due to a blockchain’s low-resolution clock, we can never expect second to
occur. When you write code that checks the time, comparisons should always involve greater or less
than, rather than exactly equal. It is also important to keep in mind that the block creator can manipulate
the time a block is created as well as the ordering of the transactions to their advantage.
6. Signing transactions: The wallet software such as Metamask handles signing the transactions using the
user’s private key. Knowing the EOA’s private key is synonymous with owning that account because the
private key is what is used to sign transactions. Without this cryptographic signature, there is no way to
authenticate whether a transaction was actually sent by its specified EOA. When we send an Ethereum
transaction using any of the web3 libraries, the cryptographic signature happens in the background. The
following transaction attributes are concatenated, encoded, and then signed with the configured private
key (nonce, gasprice, gas, to, value, data, chainId). Once these attributes are signed, the signature itself is
included in the transaction so that Ethereum nodes can validate that the sender is legitimate.

Ethereum Client:
In a traditional web application, the server is centralized and located with a URL or IP address. This web
application software can be written in any programming language that is capable of sending HTTP request. The
client software would make interacting with the server easier since it would contain all the logic and abstractions
for building the requests and parsing responses. The client could also be released as a library and made available
for other applications to speed up adoption of the service.
When we install an Ethereum client, we are installing software that will allow us to run an Ethereum node on our
machine. This software comes with a command-line interface which allows us to create accounts or launch an
interactive console that preloads Web3. Additionally, this server will run a server to expose the Ethereum JSON
RPC API. We use JSON to send a request to a server, which then executes some predefined operations. It is
through this JSON RPC that we will be interacting with the blockchain.
There are number of Ethereum clients you can use, including cpp-ethereum, Geth, Parity. Parity is a client
written in rust and provides one of the faster syncing options of the available clients. Once the client is installed,
you can begin to sync the blocks from the network. Goerli is a testnet designed to work with several different
Ethereum clients such as geth and parity. After the initial sync, launching parity will be quick, as it will only
need to grab the latest blocks that have been added to the chain. At this point, you can go ahead and kill the
process with ctrl-C. If your application required users to download and run a full Ethereum client, you just lost a
lot of potential users.

Metamask: If your application required users to download and run a full Ethereum client, you just lost a lot of
potential users. Asking a user to install and run a full Ethereum node is a bit much for all. Outside of early
adopter, you will need to provide a much easier way for those less-savvy to begin using the application, and that
is exactly where MetaMask comes in. Metamask is distributed as a vrowser extension available on chrome and
other browsers. The metamask software provides users with the ability to create accounts, and loads a
preconfigured instance of web3 into browser that is used to interact with the blockchain via JSON RPC. With
metamask installed, you can now begin to interact with existing decentralized applications from your browser.

[Link]: It is time to install [Link] for the javascript tolls we will need for smart contract development. The
primary development tools we will use to develop our smart contracts or interact with the Ethereum network
have been built using JavaScript, which means we need [Link] to provide the JavaScript runtime environment.
Truffle (a framework): This provides tools make compiling, testing, deploying, and packaging your application
as easy as possible. In order to deploy the contracts, we need to turn to another tool provided by truffle toolbelt,
called migrations. Migrations are scripts written in JavaScript that are used to automate the deployment of our
contracts. The default migrations contract found in contracts/[Link] is the contract that is deployed by
migrations/1_initial_migration.js and is currently the only contract that has made its way to test the network. We
need to create another js file to deploy the created contract to the network. With truffle installed, the last thing we
need to do is add Ganache.
Ganache: Its your very own blockchain. In many regards, it is very much like Ethereum client. It provides tools
for creating accounts and runs a JSON RPC API server for you to connect and read/write to the blockchain. The
main difference is that it doesn’t actually connect to the Ethereum network.
Solidity: In solidity, we don’t have access to standard out, or the file system, the network, or any other
input/output, therefore can not print anything. What we do have are functions. The functions can return the
values and on the front end, we can retrieve it and print it.
Modifiers: External functions can be called from other contracts, or from transactions, but cannot be called from
within the contract or at least not without an explicit reference to the object it is being called on. The public
functions are also part of the interface, meaning they can be called from other contracts or transactions, but
additionally they can be called internally. This means you can use an implicit receiver of the message when
invoking the method inside of a method. The internal and private functions must use the implicit receiver or, in
other words, cannot be called on an object or on this. The major difference between these two modifiers is that
private functions are only visible within the contract in which they are defined, and not in the derived contracts.
Functions that will not alter the state of the contract’s variables can be marked as either pure or view. The pure
function do not read data from the blockchain. Instead, they operate on the data passed in or, in the case, data
that did not need any input at all e.g. return a string “hello world”. The view functions are allowed to read data
from the blockchain, but again they are restricted in that they can not write to the blockchain. We can indicate
that the returned value is not referencing anything located in our contract’s persisted storage by using the
keyword memory.
Function setGreeting (string calldata greeting) external {
}
Because this function is being called from the outside world, the data being passed in as a parameter is not part
of the contract’s persisted storage, but is included as part of the calldata and must be labelled with the data
location calldata. The calldata location is only needed when the function is declared as external and when the
data type of the parameter is a reference type such as mapping, struct, string, or array.
State variables: they will be available to all the functions defined inside of a contract. They are also where we
will store data that will exist for the entire lifetime of our contract. Like functions, state variables can be declared
with different levels of visibility modifiers, including public, internal, and private. Note that all data on
blockchain is publicly visible from the outside world. State variable modifiers only restrict how the data can be
interacted with from within the contract or other contracts.
Making the greeter ownable:
We now add the idea of ownership to the contract, and then restrict the ability to change the greeting to the
owner. In order to do this, we want to set the owner of the greeter contract to the address that deployed the
contract. This means we will need to store the address during initialization, and for that, we will need to write a
constructor function. We will also need to access some information from the msg object which is globally
available. To check that owner exist, we can invoke an owner getter function. Since this is a getter function, we
need to add a state variable that will hold the address of the owner, and then our function should return that
address.
The solidity language provides two types of addresses: one is address and the other is address payable. The
difference between them is that address payable gives access to the transfer and send methods, and variables of
this type can also receive ether. We are not sending ether to this address and we can use the address type for our
purposes.
Pragma solidity >= 0.4.0 < 0.7.0
Contract Greeter {
String private _greeting = “Hello, World!”;
Address private _owner;
Function greet() external view returns (string memory) {
Return _greeting;
}
Function setGreeting(string calldata greeting) external {
_grreting = greeting;
}
Function owner() public view returns(address){
Return _owner;
}
}
Now, what we want to check is that the owner address is the same as the deploying address. Now we need to
make a constructor that initialize the deploying address.
Constructor() public {
_owner = [Link];
}
Now we know that who created the contract, we can create a restriction that only the owner can update the
greeting. This type of access control is normally done with a function modifier. Such modifier will prevent the
function from being invoked if the clause is not met. Our modifier will use the require function, where the first
argument is an expression that will evaluate to a Boolean. When this expression results in a false, the transaction
is completely reverted, meaning all stage changes are reversed and the program stops execution. The revert
function also takes an optional string parameter that can be used to give more information to the caller as to why
the operation failed. The last part of our modifier is the _; line. This line is where the function that is being
modified will be called. If you put anything after this line, it will be run after the function body completes.
Function setGreeting(string calldata greeting) external onlyOwner{
_grreting = greeting;
}
Modifier onlyOwner(){
Require([Link] == _owner, “Ownable: caller is not an owner”);
_;
}
Import “openzeppelin-solidity/contracts/ownership/[Link]”
Contract greeter is Ownable {
Rest code is same.
}
An import statement will pull in all the global symbols from the imported file, such as Ownable, and make them
available in the current scope. Is keywork is used to inherit the properties from the imported file to the current
contract. Solidity also supports multiple inheritance.

Contract deployment: We can deploy our smart contracts in the following three different ways:
1) Deploy smart contract to ganache, a local blockchain that will allow you to experiment with your
application quickly.
2) Deploy the smart contract to the Goerli test network using the Ethereum client. This process is how you
would deploy your application directly to the Ethereum network by using a node you are managing
yourself.
3) Deploy the smart contract to the Rinkby test network using Infura, a third party provider of managed
Ethereum nodes.
After compiling the smart contract, JSON file will be generated. There are several filed in this JSNO file. Two
important fields are abi and bytecode fields. The application binary interface (ABI) describes the functions and
events of the smart contract. The ABI will be the basis for the client-side abstraction used to interact with the
smart contract. The bytecode field contains the result of the compiling the contract. This is the code the
Ethereum network will execute when the contract has been invoked from a client.
What happens during the deployment: When we deploy the contract, we submit a transaction to the Ethereum
network. The deployment transaction will need to set the receiving address to the 0x0 address. The deployment
transaction will also include the bytecode, which will be sent as the transaction data. With the contract being sent
as a transaction, it has to be mined before we will be able to interact with it. When the contract is mined, it will
execute the code in the constructor, setting the initial state for the contract.
To deploy the smart contract, we need to configure the network (ganache) configuration in the [Link]
file. Once the ganache is running and configured the file, we will need to import the accounts into Metamask
using the depicted mnemonic.

Tokens: Tokens are an abstraction that represents ownership. Ownership implies certain privileges such as the
right to use or sell an item like a vehicle or a house. The token is represented by a title or deed. It can also
provide the right to access something in the application. With ownership being something that can change often,
tracking these changes on a cryptographically secured platform makes a lot of sense. To assist developers in the
creation of tokens, the Ethereum community has developed several different types of token standards through the
Ethereum Improvement Proposal (EIP) process. For example, ERC-20 and ERC-721
ERC-20: The ERC-20 standard is used when creating a fungible, or mutually interchangeable token. These
tokens would be ideal replacements for things like reward points from retailers, miles from airlines, or a
currency. All tokens created from an ERC-20 contract are considered to have the same value and are effectively
indistinguishable from each other. Because all the tokens are considered identical, the primary responsibility of
an ERC-20 contract is tracking balances. ERC-20 tokens have been used for many different purposes, but one
that has likely caught your attention is the Initial Coin Offering (ICO). In an ICO, an organization will sell
tokens as a means to raise funds.
If the token is expected to gain in value based on the performance of the issuing organization, the token may be
considered a security. If that is the case, there are likely going to be some regulatory requirements that need to be
considered when developing these smart contracts. See EIP-1462.
Ethereum
Smart Contract
Programming
Ether and Networks
• Cryptocurrency or tokens: Ether (ETH)

• Use of ETH

• Smallest unit of a ether: Wei

• Multiple networks running Ethereum protocol


• Mainnet – real ether
• Testnet – Goerli, fake ether
• Local private blockchain network – Ganache, fake ether

• How will you get the fake ether?


• faucet
Gas and Transaction Cost
• Programming Languages: e.g. solidity
• Solidity Compiler: bytecode which provides a series of opcodes understood by EVM.

• Each opcode has an associated gas cost. Each gas unit has an associated gas price in cryptocurrency unit.
• Every Ethereum transaction sets gasLimit and its own gasPrice to determine how many wei a single unit of gas
costs.
• Maximum transaction fee = gasLimit * gasPrice for a single gas unit
• The gasPrice decides the selection of a transaction.
• The gasLimit decides how many computations a transaction can perform.
• If that limit is reached, the smart contract execution reverts, but the transaction is still written to the blockchain, and the fees are consumed by the block creator.
• If the smart contract call completes with leftover gas, the gas is returned to the transaction creator.

• Each block is specified with a gas limit. The sum of the gas used across all transactions in a block cannot
exceed the block’s specified gaslimit. This also means that no single transaction’s gas usage can exceed the
block’s gaslimit.
Accounts
1) Externally owned account (EOA)
2) Smart contract account

• Both are identified by the Ethereum address.

• Every transaction in the Ethereum blockchain is initiated by an EOA. Smart contracts can’t
spontaneously perform an action.

• Additionally, Ethereum transactions can be sent from an EOA to smart contracts. They can
call other smart contracts.

• When contracts are called, they can emit events, store data, receive ether, send ether to
EOAs, or send data or ether to other contracts.
Smart Contracts
• A contract is really a class, or a collection of state variables, and functions.
• Two types of solidity functions: read-only and write-only.
• Read-only functions are denoted with the pure and view keywords.
• Cannot change the state of the contracts or emit events, therefore, no gas costs, and no transaction created.
• No additional keyword with write-only functions.
• Can return data, but due to the asynchronous nature of Ethereum, the return data is practically useless.
• The function data must be sent via transaction.
• Change the state of the contracts and often emits one or more events in the process.

• The purpose of events in Ethereum is generally twofold:


• To provide a custom historical log of what has occurred in the contract,
• To allow observers to subscribe to real-time updates.

• Due to the open nature of blockchain, we already have a historical ledger of everything, but events provide
more domain-specific logging and updates.
Smart Contracts
• After compiling the smart contract, JSON file will be generated.

• There are several fields in this JSNO file. Two important fields are abi and bytecode fields.

• The application binary interface (ABI) describes the functions and events of the smart contract. The ABI will
be the basis for the client-side abstraction used to interact with the smart contract.

• The bytecode field contains the result of the compiling the contract. This is the code the Ethereum network will
execute when the contract has been invoked from a client.
Transaction
• A transaction can have an arbitrary number of contracts involved in its execution, provided that its execution
fits within the constraints of the block’s gaslimit.

• Solidity exposes a number of other transaction-related attributes, but groups them into a message (msg)
abstraction.
• Message refer to the communication between contracts and anything that can call them, such as other contracts.
For example, a contract function call will always have a [Link]. That [Link] could be equal to the
[Link] or the creator of the transaction, or it could be the address of an intermediatory contract.

• Solidity’s message (msg) attributes are as follows:


• data (raw bytes of data sent to the currently executed function),
• sender (address of the caller of the currently executed external or public function),
• sig (a function identifier, first four bytes of the calldata determine which function is being called.),
• value (amount of wei sent to this function),
• timestamp, blockhash, difficulty, gaslimit, coinbase (address of block creator).
Signing Transaction
• The wallet software such as Metamask handles signing the transactions using the user’s private key.

• Without this cryptographic signature, there is no way to authenticate whether a transaction was actually sent by
its specified EOA.

• When we send an Ethereum transaction using any of the web3 libraries, the cryptographic signature happens in
the background.

• The following transaction attributes (nonce, gasprice, gas, to, value, data, chainId) are concatenated, encoded,
and then signed with the configured private key.

• Once these attributes are signed, the signature itself is included in the transaction so that Ethereum nodes can
validate that the sender is legitimate.
Ethereum Client
• A software that allows us to run an Ethereum node on our machine.

• This software also allows us to create accounts or launch an interactive console that preloads Web3.

• It will also run a server to expose the Ethereum JSON RPC API that allows us to interact with the blockchain.

• Ethereum Clients: cpp-ethereum, Geth, Parity

• Once the client is installed, you can begin to sync the blocks from the network.

• If your application required users to download and run a full Ethereum client, you just lost a lot of potential
users.
Metamask
• Metamask provides a much easier way to use the decentralized applications.

• Metamask is distributed as a browser extension available on chrome and other browsers.

• The metamask software provides users with the ability to create accounts, and loads a preconfigured
instance of web3 into browser that is used to interact with the blockchain via JSON RPC.

• With metamask installed, you can now begin to interact with existing decentralized applications
from your browser.
Other software requirements
• [Link]: The primary development tools we will use to develop our smart contracts or interact with the
Ethereum network have been built using JavaScript, which means we need [Link] to provide the
JavaScript runtime environment.

• Truffle (a framework): This provides tools make compiling, testing, deploying, and packaging your
application as easy as possible. One of the tool is migrations.

• Ganache: Its your very own blockchain. In many regards, it is very much like Ethereum client. It
provides tools for creating accounts and runs a JSON RPC API server for you to connect and read/write
to the blockchain. The main difference is that it doesn’t actually connect to the Ethereum network.
Contract Deployment
• We can deploy our smart contracts in the following three different ways:

1) Deploy smart contract to ganache, a local blockchain that will allow you to experiment with your
application quickly.

2) Deploy the smart contract to the Goerli test network using the Ethereum client. This process is how
you would deploy your application directly to the Ethereum network by using a node you are
managing yourself.

3) Deploy the smart contract to the Rinkby test network using Infura, a third party provider of
managed Ethereum nodes.
What happens during the deployment
• When we deploy the contract, we submit a transaction to the Ethereum network.

• The deployment transaction will need to set the receiving address to the 0x0 address.

• The deployment transaction will also include the bytecode, which will be sent as the transaction data.

• With the contract being sent as a transaction, it has to be mined before we will be able to interact with it.

• When the contract is mined, it will execute the code in the constructor, setting the initial state for the
contract.
First smart contract: Greet everyone
• Our first program will greet us with “Hello, World!”.

1. Let’s create the Greeter file.

2. Create an empty contract

3. Define a function that can return the greet

4. Allow users to change the greetings. Make the greeting dynamic.

5. Add the idea of ownership to the contract, and then restrict the ability to change the greeting to the owner.
Second smart contract: Bank
1) Write a smart contract – A simple bank

Functionality:

1.a) Deposit some ether in the bank

1.b) Withdraw ether from the bank

1.c) Transfer ether from one account to another account

1.d) Check the balance corresponding to a account in the bank

You might also like