PDF Web3 Technologies
PDF Web3 Technologies
[Link].
(COMPUTER SCIENCE)
Semester - III
Revised Syllabus as Per NEP 2020
Web3 Technologies
© UNIVERSITY OF MUMBAI
Prof. (Dr.) Ravindra Kulkarni
Vice Chancellor
University of Mumbai, Mumbai.
Prin. (Dr.) Ajay Bhamare Prof. (Dr.) Shivaji Sargar
Pro Vice-Chancellor Director
University of Mumbai. CDOE, University of Mumbai.
1. Blockchain 1
2. Bitcoin 43
3. Smart Contracts and Ethereum 76
4. Ethereum And Ethereum Development Environment 114
5. Web3, Serenity, Ethereum 158
6. Hyperledger & tokenization 180
7. Introduction to Solidity Programming 219
8. Error handling and Smart Contracts 250
*****
Semester- III
Course Outcome:
The learner will be able to
Understand and apply the fundamentals of Web3 Technologies and bitcoin.
Develop skills in smart contracts and Ethereum development environment.
Understand and apply concept of Ethereum framework, serenity and
Tokenization
Apply Solidity programming for Smart contracts and tokenization
Total
Course Code Course Title
Credits
PSCS601 Web3 Technologies 04
MODULE I
Unit 1: Introduction to Web3 Technologies
Blockchain: Growth of blockchain technology, Distributed systems, the history
of blockchain and Bitcoin, Blockchain, Consensus, CAP theorem and
blockchain, Decentralization using blockchain, Methods of decentralization,
Routes to decentralization, Blockchain and full ecosystem decentralization, The
consensus problem, Analysis and design, Classification, Algorithms,
Bitcoin: Overview, Cryptographic keys, Transactions, Blockchain Mining,
Bitcoin network, Wallets, Bitcoin payments, Innovation in Bitcoin, Advanced
protocols, Bitcoin investment, and buying and selling Bitcoin
02
Unit 2: Smart Contracts & Ethereum
Smart Contracts: History, Definition Ricardian contracts, Smart contract
templates, Oracles, Deploying smart contracts, The DAO
Ethereum: Overview, Ethereum network, Components of the Ethereum
ecosystem, The Ethereum Virtual Machine (EVM), Smart contracts, Blocks and
Blockchain, Wallets and client software, Nodes and miners, APIs, tools, and
DApps, Supporting protocols, Programming languages,
Ethereum Development Environment: Overview, Test networks, Components
of a private network, starting up the private network, mining on the private
network, Remix IDE, MetaMask, Using MetaMask and Remix IDE to deploy a
smart contract
MODULE II
Unit 3: Serenity, Ethereum, Hyperledger & Tokenization
Web3: Exploring Web3 with Geth, Contract deployment, interacting with
contracts via frontends
Development frameworks: Serenity, Ethereum 2.0—an overview,
Development, phases, Architecture
Serenity: Ethereum 2.0—an overview, Development phases, Architecture
Hyperledger: Projects under Hyperledger, Hyperledger reference architecture,
Hyperledger Fabric, Hyperledger Sawtooth, Setting up a sawtooth development
environment.
Tokenization: Tokenization on a blockchain, Types of tokens, Process of
tokenization, Token offerings, Token standards, Trading and finance, DeFi, 02
Building an ERC-20 token,emerging concepts
Unit 4: Solidity Programming
Introduction to Solidity Programming: Layout of a Solidity Source File,
Structure of a Contract, Types, Units, and Globally Available Variables, Input
Parameters and Output Parameters, Control Structures, Function Calls,
Creating Contracts via new, Order of Evaluation of Expressions, Assignment,
Scoping and Declarations,
Error handling: Assert, Require, Revert and Exceptions
Smart Contracts: Solidity Programming –Contracts, Creating Contracts, Visibility
and Getters, Function Modifiers, Constant State Variables, Functions,
Inheritance, Abstract Contracts, Interfaces, Libraries.
Text Books:
1. Mastering Blockchain: A deep dive into distributed ledgers, consensus protocols,
smart contracts, DApps, cryptocurrencies, Ethereum, and more, 3rd Edition 2020
2. Andreas M. Antonopoulos, [Link] wood “Mastering Ethereum” O‟Reilly Media
Inc, 2019
3. Ritesh Modi, “Solidity Programming Essentials: A Beginner‟s Guide to Build
Smart Contracts for Ethereum and BlockChain”, Packt Publishing.
4. Josh Thompson, „Blockchain: The Blockchain for Beginnings, Guild to
Blockchain Technology and Blockchain Programming‟, Create Space
Independent Publishing Platform, First Edition - 2017.
Reference Books:
1. Josh Thompson, „Blockchain: The Blockchain for Beginnings, Guild to
Blockchain Technology and Blockchain Programming‟, Create Space Independent
Publishing Platform, First Edition - 2017.
Programme Name: [Link]. Computer
Course Name: Web3 Technologies
Science Semester III
Total Credits: 02 Total Marks: 50
University assessment: 50
Course
Course Title Credits
Code
PSCS602 Web3 Technologies Practical 02
Note: - The following practical can be performed using Solidity, NodeJS.
Ethereum and any other suitable platform
1 Install and understand Docker container, [Link], Java and Hyperledger
Fabric, Ethereum and perform necessary software installation on local
machine/create instance on Cloud to run.
2 Create and deploy a block chain network using Hyperledger Fabric SDK
for Java
3 Interact with a block chain network. Execute transactions and requests
against a block chain network by creating an app to test the network and
its rules
4 Deploy an asset-transfer app using block chain. Learn app development
within a Hyperledger Fabric network.
5 Use block chain to track fitness club rewards..
6 Build a web app that uses Hyperledger Fabric to track and trace member
rewards.
7 Car auction network: A Hello World example with Hyperledger Fabric
Node SDK and IBM Block chain Starter Plan. Use Hyperledger Fabric to
invoke chaincode while storing results and data in the starter plan
8 Develop an IoT asset tracking app using Block chain. Use an IoT asset
tracking device to improve a supply chain by using Block chain, IoT
devices, and Node-RED.
9 Create a global finance block chain application with IBM Block chain
Platform Extension for VS Code. Develop a [Link] smart contract and
web app for a Global Finance with block chain use case
10 Develop a voting application using Hyperledger and Ethereum.
UNIT 1
INTRODUCTION TO WEB3
TECHNOLOGIES
1
BLOCKCHAIN
Unit Structure
1.0 Objective
1.1 Growth of blockchain technology
1.1.1 Distributed systems,
1.1.2 The history of blockchain and Bitcoin,
1.1.3 Blockchain
1.1.4 Consensus
1.1.5 CAP theorem and blockchain
1.2 Decentralization using blockchain
1.2.1 Methods of decentralization
1.2.2 Routes to decentralization
1.2.3 Blockchain and full ecosystem decentralization
1.2.4 The consensus problem
1.2.5 Analysis and design
1.2.6 Classification
1.2.7 Algorithms
1.3 Summary
1.4 Exercise
1.0 OBJECTIVE
This objective of this chapter is :
2
relies on consensus mechanisms to maintain a single, trusted version of the Blockchain
ledger without a central authority. These mechanisms ensure agreement
among distributed nodes despite faults or malicious actors, forming the
backbone of the decentralized Web3 ecosystem.
Economic incentives through tokens and the growing need for secure
digital asset management also fueled adoption.
Key figures included Timothy C. May, Eric Hughes, and Nick Szabo.
4
Emergence of Bitcoin: Blockchain
Example:
2012: 25 BTC
Emergence of Exchanges:
Security Incidents:
7
Web3 Technologies How did Bitcoin solve the double-spending problem?
Bitcoin combined a public ledger (blockchain) with a Proof of Work
consensus mechanism.
Miners compete to solve cryptographic puzzles, and the longest chain
with the most accumulated work is accepted as the valid transaction
history, preventing double spending by making it computationally
expensive to rewrite history.
1.1.3 Blockchain:
Key Concepts:
Types of Blockchain:
Advantages of Blockchain:
9
Web3 Technologies Data Integrity: Every change is traceable and recorded in the ledger.
Disadvantages of Blockchain
Blockchain Architecture:
Block Structure: Each block typically contains
● Block Header:
○ Previous block hash
○ Timestamp
○ Nonce (for PoW)
○ Merkle root
● Block Body:
○ List of validated transactions
Hashing:
10
Consensus Algorithms: Blockchain
Algorithm Description
Proof of Stake (PoS) Proof of Stake (PoS) Validators are chosen based
on their stake in the network. More efficient.
Applications of Blockchain:
Consensus:
Definition:
Consensus is the mechanism by which a network of distributed agents
agree on a shared state or decision, even in the presence of failures or
adversarial behavior.
Validity: The agreed value must be one that was actually proposed by
a node.
Feature Description
Raft / Paxos:
Advantage Explanation
Fault Tolerance Can continue working even when some nodes are
unreliable.
1.1.4 Consensus:
What is consensus in blockchain networks?
A10: Consensus is the process by which network participants agree on a
single version of the blockchain state, despite failures or malicious
actors. It is vital for maintaining consistency and trust in a
decentralized environment.
15
Web3 Technologies Q11: What are some popular consensus algorithms?
A11:
Proof of Work (PoW): Miners solve computational puzzles (Bitcoin).
Proof of Stake (PoS): Validators are selected based on their stake
(Ethereum 2.0).
Delegated Proof of Stake (DPoS): Token holders elect a few delegates
(EOS).
Practical Byzantine Fault Tolerance (PBFT): Voting-based for
permissioned networks.
First proposed by Eric Brewer in 2000 and formally proved by Gilbert and
Lynch in 2002.
Property Description
Consistency ● All nodes see the same data at the same time. Every
(C) read receives the most recent write or an error.
● Consistency means that the duplicated data item will
appear in the same copies on all nodes during different
transactions.
● An assurance that each node in a distributed cluster
returns the same, most recent, and successful writer.
● Every client's perception of the data must be consistent
to be considered consistent.
16
Blockchain
● Sequential consistency, which is a particularly
powerful type of consistency, is referred to as
consistency in CAP.
● Example:
Recently the insurance policy of your car got outdated and
you want to update or get a new insurance policy for your
car. You decide to call the bank or the insurance company
and update it with them. When you call, you connect with
an agent. This agent asks you for the relevant details of
your previous policy. But once you have put down the
phone, you realize that you missed one detail. So you
frantically call the agent again. But, this time when you
call, you connect with a different agent but then also, they
are able to access your records as well and know that you
are registering for your new insurance policy. They make
the relevant changes in the house number and the rest of the
address is the same as the one you told the last operator.
We call this Consistency because even though you connect
to a different customer care operator, they were able to
retrieve the same information.
17
Web3 Technologies
Partition ● The system continues to operate despite arbitrary
Tolerance message loss or partial network failure.
(P) ● A communication breakdown a momentary delay or
lost connection between nodes is referred to as a
partition in a distributed system.
● Partition tolerance describes the ability of a cluster to
function even in the face of numerous communication
failures between system nodes.
● Example:
Unfortunately, you need to sell your car because it's old and
outdated and you don't use it very often. So you list all of
the specifics about your automobile on a website for sale,
and then you get in touch with a buyer. He starts
negotiating because he wants to acquire your car and hence
wants to complete the agreement process. However,
because the bargaining was not mutual, neither of you
could sign the agreement. Therefore, we might conclude
that the agreement has been breached or that there is no
partition tolerance in this situation.
18
Note: Blockchain
The CAP theorem states that in a distributed system, only two out of
three properties can be guaranteed simultaneously: Consistency,
Availability, and Partition tolerance.
19
Web3 Technologies When things go wrong, we must prioritize at most two distributed
system features and trade-offs between them.
The system will always process the query and attempt to return the
most recent version of the data even if it cannot ensure that it is up to
date because of network partitioning when availability is preferred
over consistency.
20
Sharing distributed transactions naturally raises questions about the Blockchain
CAP theorem.
When you think about it, the decentralization concept has made
Bitcoin the safest, most trusted, and most sought-after money on the
market.
Because each node in the network has a complete record of every data
published on the blockchain, public blockchains are now
decentralized.
Any blockchain solution must meet the needs of the user, which may
or may not involve certain decentralization levels.
Fully Centralized:
○ A system in which the whole system is controlled and managed by a
single central authority.
○ Take, for instance, the banking system.
Semi-decentralized:
○ A system in which the entire system is controlled and managed by
numerous intermediaries.
22
Fully Decentralized: Blockchain
Architectural Decentralization:
○ This sort of decentralization is concerned with the number of physical
computers in the system.
○ And how many PCs can it withstand malfunctioning at the same time?
○ As a result, architectural decentralized blockchains are ones in which
the same blockchain is run by various systems.
○ The blockchain will now be unaffected even if one machine crashes.
○ Bitcoin is a well-known example of decentralized blockchain
architecture.
Political Decentralization:
○ This sort of decentralization refers to the number of people or groups
in charge of or managing the computers in a system.
○ Bitcoin, for example, is politically decentralized since it is not owned
by any organization or individual.
○ The Bitcoin protocol is used by all nodes in the Bitcoin network.
Logical Decentralization:
○ This sort of decentralization is concerned with the representation of
the system's interface and data structures.
○ Bitcoin, for example, is not theoretically decentralized since it has a
single agreed-upon state and operates as a single system.
Decentralization's Advantages:
● Provides a trustless environment:
○ No one has to know or trust anybody other in a decentralized
blockchain network.
○ In the form of a distributed ledger, each member of the network owns
a copy of the exact same data.
○ If a member's ledger is tampered with or corrupted in any manner, the
majority of the network's members will reject it.
● Cost:
○ In an organization, decentralization might be costlier than
centralization.
○ Because it necessitates the development of communication-
automation systems and technologies.
● Conflict:
○ Decentralization should only be employed when the consumers' needs
are met.
○ Because disputes might arise if users do not properly preserve
decentralization.
● Volatility:
○ Cryptocurrencies built on a decentralized blockchain are extremely
volatile.
○ This is due to the fact that cryptocurrencies, or possibly the entire
technology, are relatively new to the market.
○ As a result, a large number of individuals are investing in them.
● Crime:
○ This is due to the fact that everything is done on the network
anonymously, which might lead to exploitation or misuse.
Methods of decentralization:
Two methods can be used to achieve decentralization: disintermediation
and competition (Contest-driven decentralization). These methods will be
discussed in detail in the sections that follow:
Disintermediation:
The concept of disintermediation can be explained with the aid of an
example. Imagine that you want to send money to a friend in another
country.
You go to a bank, which, for a fee, will transfer your money to the
bank in that country. In this case, the bank maintains a central
database that is updated, confirming that you have sent the money.
With blockchain technology, it is possible to send this money directly
to your friend without the need for a bank. All you need is the address
of your friend on the blockchain.
This way, the intermediary (that is, the bank) is no longer required,
and decentralization is achieved by disintermediation.
25
Web3 Technologies It is debatable, however, how practical decentralization through
disintermediation is in the financial sector due to the massive
regulatory and compliance requirements.
Nevertheless, this model can be used not only in finance but in many
other industries as well, such as health, law, and the public sector.
Contest-driven Decentralization:
This method will not result in full decentralization, but it allows smart
contracts to make a free choice based on the criteria just mentioned.
Decentralization by Design:
○ Systems are built natively and decentralized from the beginning.
○ Use peer-to-peer protocols, distributed consensus, and open source
code.
○ Example: Bitcoin, which started as a decentralized digital currency
from day one.
26
Progressive Decentralization Blockchain
Decentralization by Forking
○ Communities split from a centralized or semi-centralized project to
build an alternative.
○ Example: Ethereum Classic (a fork of Ethereum), Bitcoin Cash (a
fork of Bitcoin).
Token-Based Decentralization
○ Use of cryptographic tokens to distribute ownership, reward
participation, and govern protocol upgrades.
○ Voting rights, fee sharing, and DAO participation based on token
holding.
Open Protocol Standards
○ Creating and adhering to open, decentralized protocols that anyone
can implement.
○ Example: IPFS, ActivityPub, SMTP, and Matrix protocol.
1.2.3 Blockchain and full ecosystem decentralization:
Blockchain is a distributed ledger technology that allows the storage
of data in blocks of information, with each block containing batches
of transactions from one moment in time.
Its open, decentralized and secure nature allows blockchain to disrupt
traditional transactional systems.
Blockchain has the potential to transform the ecosystem by becoming
an indispensable part of our daily lives.
Understanding the underlying technology and its impact is imperative
for those looking to capitalize on this new era.
Let's break down how blockchain is changing the world and what it
means for your business.
27
Web3 Technologies What is the Blockchain Ecosystem?
All over the world, people have continuously struggled with keeping
their personal and business finances safe.
However, the success rate for financial security goes up a few notches
with blockchain technology.
Below are some of the ways in which the blockchain ecosystem can
benefit organizations:
Distributed:
○ With no centralized authority (i.e. a database administrator or single
point of failure) this brings new functionalities for the employees and
customers of an organization.
Smart contracts:
○ Smart contracts are essentially a computer program that automatically
executes agreed-upon terms in a contract when certain conditions are
met.
○ With the use of smart contracts the exchange of information is swift
and can also remove intermediaries in a process that would extend the
time to perform a task in a larger process.
○ It logs transactions in a linear, chronological order, and creates an
immutable set of records that are tamper-proof.
29
Web3 Technologies Improve ongoing operation:
○ The blockchain ecosystem should be viable for an organization when
it can improve the ongoing operation that existing solutions can't do.
○ For example, an organization where data sharing among various
departments and individuals occurs at a higher rate could benefit from
the blockchain structure of validating data among nodes or peers as
fast as possible.
Facilitate cross-enterprise collaboration:
○ It can facilitate cross-enterprise collaboration with the benefit of
decentralization, flexibility, distribution, and traceability.
Transparency:
○ All transactions are visible to all users of the network. Data can be
traced back to its source, making it almost impossible to forge a
digital item or transaction.
Consensus:
○ The participants in the blockchain ecosystem use the information they
receive to make calculations and verify new blocks, using a
consensus-based system.
○ This makes it difficult for fraudulent transactions or duplicate items to
get through.
Components of Blockchain Ecosystem:
The important logical components in the blockchain ecosystem are as
follows:
Node application:
It is a particular internet application that every internet-connected
computer must download for participating in a blockchain ecosystem.
After node application installation, a user becomes a participant in the
blockchain network.
Once one has a node application installed, it can participate in the
ecosystem.
30
Distributed ledger: Blockchain
This is the logical component and the data structure that is managed
inside the node application.
Once the node application is installed, one can view the respective
ledger contents from that ecosystem.
Consensus algorithms:
They provide the rules of the game for how the ecosystem will arrive
at the single view of the ledger.
There are different consensus algorithms like PoW, PoS, etc, each
method qualifies nodes as honest in their own way before
participating in the consensus-building process.
Virtual machine:
Who are the expected participants and why do they want to join the
ecosystem?
3. Ecosystem model:
4. Ecosystem governance:
Below are some of the questions that should be discussed in this step:
○ What governance will be required to bring the ecosystem to life?
○ How will value and cost for the blockchain ecosystem be fairly
allocated?
5. Organizations' preparation:
Each organization must have an idea about what benefits it can derive
from joining the ecosystem.
32
This is possible only because of the presence of the consensus Blockchain
protocol which is a core part of any Blockchain network.
Essentially, the consensus protocol makes sure that every new block
that is added to the Blockchain is the one and only version of the truth
that is agreed upon by all the nodes in the Blockchain.
○ Synchronous Systems
■ Have known bounds on message delay and processing time.
■ Easier to design consensus (timeouts are reliable indicators).
○ Asynchronous Systems
■ No guarantees on timing; more realistic but harder to solve.
33
Web3 Technologies ■ Fischer-Lynch-Paterson (FLP) theorem: In a purely asynchronous
system, consensus is impossible if even one node may fail.
○ Partially Synchronous Systems
■ Operate asynchronously most of the time but occasionally behave
synchronously.
■ Many practical protocols (e.g., PBFT, Raft) assume partial synchrony.
● Fault Models
● Different fault types affect design choices:
○ Crash Faults – Nodes stop working but do not behave maliciously.
○ Omission Faults – Nodes fail to send/receive messages.
○ Byzantine Faults – Nodes can behave arbitrarily, possibly
maliciously.
○ Requires stronger algorithms (e.g., Byzantine Fault Tolerance).
● Performance Metrics
● When analyzing a consensus protocol, evaluate:
○ Fault Tolerance – Maximum number of faulty nodes tolerated.
○ Message Complexity – Total number of messages exchanged.
○ Time Complexity – Number of communication rounds to reach
agreement.
○ Scalability – How performance changes as system size increases.
○ Energy Efficiency – Important for wireless sensor and IoT networks.
1.2.6 Classification:
Consensus problems can be classified according to several criteria:
● By Fault Model
○ Crash Fault Consensus
○ Byzantine Consensus
○ Hybrid Models (some nodes crash, some act maliciously)
● By Synchrony
○ Synchronous Consensus – Easier, deterministic solutions possible.
○ Asynchronous Consensus – Requires randomized or failure-detection-
based methods.
○ Partially Synchronous Consensus – Practical compromise.
34
● By Decision Type Blockchain
● By Application Domain
○ Distributed Databases – Commit protocols (e.g., Two-Phase Commit).
○ Blockchain Systems – Proof-of-Work, Proof-of-Stake, PBFT.
○ Control Systems & Robotics – Distributed averaging, leader-follower
control.
Classification Examples
Basis
1.2.7 Algorithms:
Now, we will discuss various consensus algorithms and how they work.
35
Web3 Technologies ● Practical Byzantine Fault Tolerance (PBFT):
○ Please refer to the existing article on practical Byzantine Fault
Tolerance(pBFT).
● Proof of Capacity:
○ In the Proof of Capacity consensus, validators are supposed to invest
their hard drive space instead of investing in expensive hardware or
burning coins.
○ The more hard drive space validators have, the better their chances of
getting selected for mining the next block and earning the block
reward.
37
Web3 Technologies
1.3 SUMMARY
This chapter provided a detailed Q&A-based exploration of
blockchain technology, from its history and core principles to the
technical underpinnings of consensus and decentralization.
38
1.4 EXERCISE WITH SOLUTION (NOTE: ELABORATE Blockchain
Answer:
Blockchain is a decentralized, distributed ledger that stores data in linked,
cryptographically secured blocks.
Key features:
1. Decentralization – No central authority; data shared across nodes.
2. Immutability – Once recorded, data cannot be altered without
consensus.
3. Transparency – Transactions visible to authorized participants.
4. Security – Uses cryptographic hashes and digital signatures.
5. Consensus Mechanisms – Ensure agreement on the ledger’s state.
Q2. What is Web3, and how does blockchain support it?
Answer:
Web3 refers to the next generation of the internet that is decentralized,
user-centric, and built on blockchain technology.
● Blockchain’s role:
○ Provides decentralization, removing intermediaries.
○ Ensures trust through transparent ledgers.
○ Enables smart contracts for automated transactions.
○ Facilitates secure digital ownership via NFTs and tokens.
Q3. Explain the CAP theorem and its relevance to blockchain.
Answer:
The CAP theorem states a distributed system can guarantee only two of:
1. Consistency (all nodes have the same data),
2. Availability (every request gets a response),
3. Partition tolerance (system continues despite network splits).
● Blockchain must ensure partition tolerance.
● Public blockchains often prioritize availability, achieving eventual
consistency after confirmations.
39
Web3 Technologies Q4. Describe the difference between centralized, decentralized, and
distributed systems.
Answer:
Centralized: Single authority manages all data and operations.
Decentralized: Multiple authorities or nodes share control; failures
are isolated.
Distributed: Data and processes spread across multiple nodes, often
geographically; may be centralized or decentralized in control.
Q5. State the core requirements of a valid consensus protocol.
Answer:
1. Agreement – All non-faulty nodes decide on the same value.
2. Termination – Decision is reached in finite time.
3. Validity – Decision must be one of the proposed values.
4. Integrity – No node decides more than once.
Q6. Classify consensus problems based on fault models and provide
examples.
Answer:
1. Crash Fault Consensus – Nodes fail silently (e.g., Paxos, Raft).
2. Byzantine Fault Consensus – Nodes behave maliciously (e.g.,
PBFT, Tendermint).
3. Hybrid Models – Combination of crash and Byzantine faults.
Q7. Differentiate between Proof of Work (PoW) and Proof of Stake (PoS).
Answer:
● PoW:
○ Uses computational puzzles.
○ High energy consumption.
○ Example: Bitcoin.
● PoS:
○ Selects validators based on stake.
○ Energy-efficient and faster.
○ Example: Ethereum 2.0.
40
Q8. Write short notes on PBFT (Practical Byzantine Fault Tolerance). Blockchain
Answer:
Answer:
Advantages:
Trustless transactions.
Greater transparency.
Disadvantages:
Complex governance.
Answer:
41
Web3 Technologies Q11. Compare synchronous, asynchronous, and partially synchronous
systems in consensus design.
Answer:
Answer:
1. Supply Chain Management – Tracking goods from origin to
consumer.
2. Healthcare – Secure patient data sharing.
3. Voting Systems – Transparent, tamper-proof elections.
4. Intellectual Property – Time-stamped proof of creation using NFTs.
*****
42
2
BITCOIN
Unit Structure
2.0 Objective
2.1 Cryptographic keys
2.2 Transactions
2.3 Blockchain Mining
2.4 Bitcoin network
2.5 Wallets
2.6 Bitcoin payments
2.7 Innovation in Bitcoin
2.8 Advanced protocols
2.9 Bitcoin investment and buying & selling Bitcoin
2.10 Summery
2.11 Exercise
2.0 OBJECTIVE
By the end of this chapter, students should be able to:
Other developers took over and the Bitcoin community has since
grown exponentially.
In this system:
Public keys act as the “account number” that others can use to send
bitcoins.
Bitcoin addresses are derived from public keys to simplify usage and
enhance security.
44
Types of Keys in Bitcoin: Bitcoin
a) Private Key:
Functions:
○ Generate corresponding public key.
○ Sign transactions.
b) Public Key:
Functions:
○ Share with others to receive Bitcoin.
○ Used by nodes to verify transaction signatures.
Security: Cannot feasibly derive the private key from the public key
due to the Elliptic Curve Discrete Logarithm Problem.
Bitcoin Addresses:
Creation Steps:
1. Start with public key.
2. Apply SHA-256 hash.
3. Apply RIPEMD-160 hash.
4. Add version byte and checksum.
5. Encode in Base58Check format.
Example: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
45
Web3 Technologies Digital Signatures in Bitcoin:
Bitcoin uses ECDSA signatures:
○ Signing: Uses private key + transaction data → signature (two values:
r and s).
○ Verification: Uses public key + signature + transaction data.
Properties:
○ Authenticity: Signature proves the sender owns the private key.
○ Non-repudiation: Sender cannot deny signing.
○ Integrity: If transaction data changes, the signature becomes invalid.
Security Considerations:
Private key storage: Use hardware wallets, paper wallets, or
encrypted software wallets.
Backup: Essential, as loss is irreversible.
Avoid key reuse: Enhances privacy and reduces attack vectors.
Randomness: Weak random number generation can compromise
keys.
Multisignature wallets: Require multiple private keys to authorize
transactions, improving security.
Example Flow:
1. Key Generation: User generates private key → derives public key →
derives address.
2. Receiving BTC: Sender uses recipient’s address to send BTC.
3. Spending BTC: Recipient signs transaction with private key.
4. Verification: Bitcoin network verifies the signature using the public
key.
Summary Table:
46
Bitcoin
Visibility Keep secret Share openly Share openly
Generation Random From private key via From public key via
ECDSA hashing
2.2 TRANSACTIONS
A Bitcoin transaction is a signed piece of data that transfers ownership of
bitcoins from one party to another.
Transactions are the only way bitcoins are created and moved on the
blockchain.
They are recorded in a public ledger and validated by the Bitcoin network
using cryptographic methods.
Components of a Bitcoin Transaction
b) Transaction Outputs:
● Represent where the bitcoins are going.
● Each output includes:
○ Value (in satoshis; 1 BTC = 100,000,000 satoshis).
○ ScriptPubKey (locking script specifying spending conditions, usually
requiring a signature from a matching private key).
c) Amount:
● Amounts are specified in satoshis to avoid floating-point errors.
● Sum of inputs ≥ sum of outputs (difference = transaction fee).
47
Web3 Technologies d) Transaction Fee:
● Calculated as: Fee = Total Input Value – Total Output Value.
● Incentivizes miners to include the transaction in a block.
Transaction Flow:
1. Creation
○ User specifies recipient’s address, amount, and transaction fee.
○ Wallet software selects appropriate UTXOs as inputs.
2. Signing
○ Inputs are signed using the sender’s private key (ECDSA).
3. Broadcasting
○ Transaction is sent to the Bitcoin network (P2P nodes).
4. Validation
○ Nodes verify:
■ Signatures match the public keys.
■ Inputs are unspent and valid.
■ No double-spending occurs.
5. Inclusion in Block
○ Miners select transactions and include them in a new block.
○ Once mined, the transaction gains confirmations (1 confirmation
after being in a block, more over time).
Example Transaction:
Let’s say Alice sends 0.8 BTC to Bob:
48
● Inputs: Bitcoin
Transaction Lifecycle
Unconfirmed State:
Confirmed State:
Security Aspects:
49
Web3 Technologies Change Addresses: Protect privacy by not reusing addresses.
Fee often depends on transaction size (in bytes), not amount of BTC
transferred.
Summary Table:
50
2.3 BLOCKCHAIN MINING Bitcoin
Introduction:
Mining in Bitcoin is the process by which:
Purpose of Mining:
1. Transaction Verification
○ Ensures that only valid transactions are recorded.
○ Prevents double-spending.
3. Network Security
○ High computational cost deters malicious attacks.
Proof-of-Work (PoW) Mechanism
Mining involves finding a nonce (arbitrary number) such that:
scss
CopyEdit
SHA-256(SHA-256(Block Header)) < Target Difficulty
Coinbase Transaction:
● The first transaction in each block.
● Pays the miner the block reward + transaction fees.
● Newly minted bitcoins are unspendable until 100 block confirmations.
2. Block Formation
○ Coinbase transaction is added first.
○ Transactions are hashed into a Merkle tree.
3. Hashing
○ Miners vary the nonce and rehash the block header until they find a
valid hash.
4. Block Submission
○ First miner to find a valid hash broadcasts it to the network.
5. Verification
○ Other nodes validate the block and append it to their chain.
Mining Difficulty:
52
Rewards & Halving: Bitcoin
Mining Pools:
PoW mining makes such attacks costly and impractical for large
networks like Bitcoin.
Environmental Considerations:
53
Web3 Technologies
Summary Table
Aspect Details
54
Network Architecture: Bitcoin
Node Types:
1. Full Nodes
○ Store the entire blockchain.
○ Verify all transactions and blocks.
○ Example software: Bitcoin Core.
3. Mining Nodes
○ Specialized full nodes that perform Proof-of-Work.
○ May operate individually or in pools.
4. Archival Nodes
○ Maintain complete historical blockchain data.
5. Pruned Nodes
○ Store only recent blocks, discarding older data to save space.
Network Functions:
● Transaction Broadcasting: Users create and sign transactions, then
send them to connected nodes.
● Validation: Nodes check transactions for:
○ Proper signatures.
○ No double-spending.
○ Valid input UTXOs.
● Block Propagation: Miners bundle valid transactions into blocks and
broadcast them.
55
Web3 Technologies ● Consensus Maintenance: Ensures all nodes agree on the longest
valid chain.
● Gossip Protocol:
○ Nodes randomly relay messages to peers, ensuring eventual
propagation across the network.
Peer Discovery:
● Nodes maintain a list of peers.
● New nodes discover peers via:
○ Hardcoded seed nodes.
○ DNS seeds.
○ Peer exchange with connected nodes.
Network Security:
Network Upgrades:
56
Hard Forks: Non-backward-compatible changes requiring all nodes Bitcoin
to upgrade.
Summary Table
Component Description
Consensus Proof-of-Work
2.5 WALLETS
Introduction:
A Bitcoin wallet is a digital tool that allows users to store, send, and
receive bitcoins securely.
It manages a user’s private keys and public addresses, enabling
interaction with the Bitcoin blockchain.
The wallet does not physically store bitcoins; instead, it stores the
cryptographic keys needed to access and spend them.
B) Based on Functionality:
1. Full Node Wallets
○ Store full blockchain.
○ Verify all transactions independently (e.g., Bitcoin Core).
2. Lightweight Wallets (SPV)
○ Store only block headers.
○ Rely on full nodes for verification (e.g., Electrum).
3. Multisignature Wallets
○ Require multiple private keys to authorize spending.
○ Commonly used in corporate or escrow services.
Wallet Security:
Example Workflow:
1. Wallet generates a private key → derives public key → creates
address.
2. User shares the address to receive funds.
3. Wallet detects incoming transaction from blockchain.
4. When spending, wallet signs the transaction with the private key.
5. Transaction is broadcast to the Bitcoin network for validation.
Best Practices:
Key Characteristics:
2. Transaction Creation
○ Payer’s wallet selects appropriate UTXOs as inputs.
○ Defines outputs: payment amount to merchant + change back to
payer.
60
3. Transaction Signing Bitcoin
4. Broadcasting
○ Transaction is sent to the Bitcoin peer-to-peer network.
5. Verification
○ Nodes validate the transaction:
■ Correct signatures.
■ No double-spending.
■ Inputs are unspent.
7. Settlement
○ Once confirmed, the merchant considers payment final.
2. Off-Chain Payments
○ Transactions handled outside the blockchain.
○ Examples: Lightning Network, payment channels.
3. Escrow Payments
○ Uses multisignature transactions to hold funds until conditions are
met.
61
Web3 Technologies ● Works through bi-directional payment channels between parties.
● Advantages:
○ Near-instant payments
● No chargebacks or reversals.
● Privacy (if best practices like address reuse avoidance are followed).
62
Summary Table Bitcoin
Step Description
2. Blockchain Ledger
○ Immutable, append-only record of transactions.
3. Proof-of-Work Consensus
○ Secures the network without trusted intermediaries.
4. Double-Spend Prevention
○ Ensures coins cannot be spent twice using cryptographic verification.
63
Web3 Technologies Subsequent Innovations in Bitcoin
A) Segregated Witness (SegWit):
● Implemented via a soft fork in 2017.
● Separates transaction signatures (“witness” data) from main block
data.
● Benefits:
○ Increases effective block capacity.
○ Fixes transaction malleability.
○ Enables Layer 2 solutions like the Lightning Network.
B) Lightning Network:
● A Layer 2 payment channel network for faster, cheaper transactions.
● Allows off-chain microtransactions with final settlement on the
blockchain.
● Enables high scalability and instant payments.
C) Taproot Upgrade:
● Activated in November 2021.
● Combines Schnorr signatures, Merkelized Abstract Syntax Trees
(MAST), and improved scripting capabilities.
● Benefits:
○ Better privacy for complex transactions.
○ Lower fees.
○ More efficient multisignature setups.
D) Schnorr Signatures:
● Introduced with Taproot.
● Allows aggregation of multiple signatures into one.
● Benefits:
○ Saves space.
○ Improves privacy.
○ Reduces verification load.
64
E) Pay-to-Script-Hash (P2SH): Bitcoin
65
Web3 Technologies Summary Table
B) Counterparty:
● A peer-to-peer financial platform built on Bitcoin.
● Uses embedded data in Bitcoin transactions (via OP_RETURN) to
create and exchange custom tokens.
● Functions: Decentralized exchange (DEX), asset creation, smart
contract support.
66
C) Omni Layer (formerly Mastercoin): Bitcoin
D) Lightning Network:
● Layer 2 payment protocol for instant, low-cost Bitcoin transactions.
● Uses bidirectional payment channels with final settlement on-chain.
● Benefits:
○ Scalability (millions of transactions per second possible).
○ Near-instant confirmation.
○ Low fees.
● Limitations: Requires liquidity and active channel management.
E) Sidechains:
● Independent blockchains pegged to Bitcoin.
● Allow assets to be transferred between chains via a two-way peg.
● Example: Liquid Network (for faster settlement, confidential
transactions).
● Benefits:
○ Experimentation without changing Bitcoin’s main chain.
○ Specialized features (e.g., higher speed, privacy).
F) Drivechains:
● Proposed mechanism for multiple sidechains with different consensus
rules.
● Miners control the pegging process between Bitcoin and sidechains.
67
Web3 Technologies H) Payment Channels:
● Enable multiple payments between two parties without recording each
on-chain.
● Types:
○ Unidirectional: One-way flow of funds.
○ Bidirectional: Payments in both directions (basis for Lightning
Network).
Advantages:
● Extend Bitcoin’s capabilities beyond simple payments.
● Improve scalability through off-chain solutions.
● Allow experimentation without risking the main Bitcoin protocol.
● Enable interoperability with other blockchain ecosystems.
Challenges:
● Complexity in implementation.
● Need for user adoption and network effects.
● Risk of protocol centralization (e.g., in managed sidechains).
● Security trade-offs when moving assets off-chain.
Summary Table
Investment Methods:
1. Direct Purchase
○ Buy Bitcoin and store in a wallet.
3. Bitcoin Mining
○ Invest in hardware to earn block rewards.
4. Derivatives Trading
○ Futures, options, and CFDs for speculative positions.
69
Web3 Technologies Risks in Bitcoin Investment:
70
C) Bitcoin ATMs: Bitcoin
Selling Bitcoin:
● Similar process to buying but reversed:
1. Transfer Bitcoin to exchange or buyer’s address.
2. Execute sell order.
3. Withdraw fiat to bank account or receive payment.
Security Considerations:
● Always withdraw Bitcoin from exchanges to private wallets after
purchase.
● Use escrow services for P2P trades.
● Avoid using public Wi-Fi when making transactions.
● Double-check addresses before sending funds.
Summary Table
71
Web3 Technologies
ATM Cash purchase Cash payout (limited) High fees
2.10 SUMMERY
This chapter covers Bitcoin as the first decentralized cryptocurrency,
focusing on its core components and supporting technologies.
It then details transactions, their inputs, outputs, fees, and the UTXO
model, along with the process from creation to confirmation.
72
Public key: Derived from the private key; used to verify signatures. Bitcoin
SPV nodes: Store only block headers, rely on full nodes for
verification.
Full nodes provide maximum security; SPV nodes are lightweight and
resource-efficient.
Instant transactions.
11. What are sidechains and why are they used in Bitcoin?
Answer:
Sidechains are independent blockchains pegged to Bitcoin via a two-way
peg.
They allow asset transfers between chains, enabling new features without
altering Bitcoin’s main chain (e.g., Liquid Network for faster settlement).
*****
75
UNIT 3
SMART CONTRACTS & ETHEREUM
3
SMART CONTRACTS AND ETHEREUM
Unit Structure
3.0 Objective
3.1 History
3.2 Definition Ricardian contracts
3.3 Smart contract templates
3.4 Oracles
3.5 Deploying smart contracts
3.6 The DAO
3.7 Ethereum Overview,
3.8 Ethereum network,
3.9 Components of the Ethereum ecosystem,
3.10 The Ethereum Virtual Machine (EVM),
3.11 Smart contracts
3.12 Summary
3.13 Exercise
3.0 OBJECTIVE
To understand the concept, history, and evolution of smart contracts.
76
To understand the role of smart contracts within the Ethereum Smart Contracts and
Ethereum
ecosystem.
3.1 HISTORY
Introduction:
Smart contracts are self-executing agreements whose terms are directly
written into lines of code. While they have gained widespread recognition
in recent years, their conceptual roots date back to the mid-1990s. This
document traces their historical development, from early analogies to
sophisticated blockchain-based implementations, with emphasis on key
milestones and technological transitions.
● Limitations:
○ Required trusted third parties.
○ Vulnerable to single points of failure.
○ Limited programmability.
77
Web3 Technologies Bitcoin Era (2009–2014)
● Bitcoin's Contribution: Introduced a decentralized ledger enabling
peer-to-peer transactions without intermediaries.
● Limitations:
○ Bitcoin’s scripting language is intentionally non–Turing-complete.
○ Complex contract logic was impractical.
● Applications:
○ Decentralized Finance (DeFi): Lending, borrowing, automated
market makers.
○ Tokenization: ERC-20 (fungible tokens), ERC-721 (non-fungible
tokens).
78
○ Governance: Decentralized autonomous organizations (DAOs). Smart Contracts and
Ethereum
○ Supply Chain Tracking: Verifiable product provenance.
● Key Milestones:
○ 2017: ICO boom leveraging ERC-20 tokens.
○ 2020–2021: DeFi and NFT markets explode.
○ Ongoing: Cross-chain interoperability and Layer-2 scalability.
Evolution Timeline
Conclusion:
The historical journey of smart contracts reflects the progression from
theoretical constructs to a foundational pillar of the decentralized web.
The Ethereum platform's introduction of a Turing-complete virtual
machine marked a pivotal turning point, transforming smart contracts into
a versatile tool underpinning a vast range of applications. As blockchain
technology continues to evolve, smart contracts are poised to drive
innovation across finance, governance, and digital ownership.
Definition:
A Ricardian contract is:
A digital contract that is both readable by humans (natural language) and
parsable by software (structured format), signed digitally, and
cryptographically linked to its execution.
Key Characteristics:
1. Human-readable
○ Contains natural language text understandable to lawyers, judges, and
laypeople.
2. Machine-readable
○ Encoded in a format that software can parse, interpret, and use to
execute instructions.
3. Digitally Signed
○ Signed by relevant parties using cryptographic keys for authentication
and integrity.
5. Dual Functionality
○ Serves as both the legal agreement and the basis for program
execution.
Structure:
A Ricardian contract typically includes:
80
Hash Fingerprint – unique ID linking the agreement to blockchain Smart Contracts and
Ethereum
records.
Advantages:
Purpose:
Key Features:
1. Standardized Structure
○ Templates define the format, variables, and parameters that must be
filled in.
81
Web3 Technologies ○ Ensures consistency in how contracts are created and executed.
3. Parameterization
○ Variables such as parties’ identities, payment amounts, and time
limits can be easily customized without rewriting the entire contract
logic.
4. Reusability
○ Common legal or business terms are codified once and reused
multiple times.
5. Interoperability
○ Templates promote compatibility across different blockchain
platforms or contract systems.
Examples of Use:
Advantages:
3.4 ORACLES
Definition:
Purpose:
Smart contracts alone can only access and act upon data available
within the blockchain.
Types of Oracles:
1. Inbound Oracles
○ Feed external real-world data into the blockchain.
○ Example: Weather data for crop insurance smart contracts.
2. Outbound Oracles
○ Send blockchain events or instructions to external systems.
○ Example: Triggering a bank payment when a contract condition is
met.
3. Software Oracles
○ Fetch data from online sources (APIs, websites, databases).
4. Hardware Oracles
○ Gather data from physical devices (IoT sensors, RFID tags).
5. Human Oracles
○ Individuals or organizations providing signed data to the blockchain.
83
Web3 Technologies Trust and Security:
● Oracles must be trusted because they can affect the outcome of a
contract.
● Risks include:
○ Single point of failure if one oracle is compromised.
○ Data manipulation from malicious providers.
● Mitigation strategies:
○ Decentralized oracles – aggregate data from multiple sources.
○ Cryptographic proofs – e.g., TLSNotary or trusted execution
environments.
○ Reputation systems – track and rank oracle reliability.
84
Process of Deployment: Smart Contracts and
Ethereum
1. Writing the Contract
○ Usually written in a high-level language like Solidity (for Ethereum).
○ Must follow syntax and logic for the target blockchain platform.
2. Compilation
○ Source code is compiled into bytecode for the blockchain’s virtual
machine (e.g., EVM).
○ Compilation also generates an ABI (Application Binary Interface)
describing contract functions.
5. Mining/Validation
○ Miners or validators include the transaction in a block.
7. Verification
○ The contract’s source code can be verified on platforms like Etherscan
to match the deployed bytecode.
Gas Costs:
● Deployment requires gas fees, which cover:
○ Storage of bytecode on the blockchain.
○ Execution of the constructor code.
● Larger or more complex contracts cost more gas to deploy.
Post-Deployment Interaction:
● Contracts cannot be changed after deployment (immutability).
85
Web3 Technologies ● Users interact with the contract through:
○ Transactions (state-changing).
○ Calls (read-only queries).
● Interaction is done via the ABI using tools like [Link], [Link], or
wallets like MetaMask.
86
2. Compile → bytecode + ABI Smart Contracts and
Ethereum
The compiler (e.g., solc) converts source to EVM bytecode (what gets
deployed) and produces an ABI (Application Binary Interface) used by
clients to encode/decode calls and events. Pay attention to compiler
version and optimization settings because bytecode (and gas costs) depend
on them.
6. Mining / Validation
Miners/validators include the tx in a block and the network reaches
consensus. Until mined, the tx is pending. If the transaction runs out of gas
during creation, the contract is not deployed and any state changes are
reverted (but gas is still spent).
Best Practices:
● Test extensively on a testnet (Ropsten, Rinkeby, Goerli) before
mainnet deployment.
● Optimize code to reduce gas usage.
● Include security audits to prevent vulnerabilities.
● Implement pausable or upgradeable patterns via proxy contracts if
future changes might be needed.
How It Worked:
1. Investment Phase
○ Participants sent ETH to The DAO’s smart contract in exchange for
DAO tokens.
○ Tokens granted voting rights proportional to holdings.
2. Proposal Process
○ Project proposals were submitted for funding.
88
○ Token holders voted on proposals, and those passing the required Smart Contracts and
Ethereum
quorum and majority would be executed.
Innovations:
● One of the earliest large-scale attempts at decentralized governance.
● Fully autonomous — rules enforced purely through code.
● No central authority or management.
● Funding decisions made transparently and democratically by token
holders.
Lessons Learned:
● Smart contract bugs can have massive financial consequences.
● Importance of formal verification, code audits, and security best
practices.
89
Web3 Technologies ● Highlighted the governance challenges in decentralized systems.
● Sparked a debate over immutability vs. community consensus in
blockchain.
Significance:
● The DAO remains a landmark event in blockchain history.
● Influenced security practices and governance models for decentralized
applications (DAOs).
● Demonstrated both the potential and risks of large-scale autonomous
organizations.
90
Ethereum Blockchain Structure: Smart Contracts and
Ethereum
● Accounts:
○ Externally Owned Accounts (EOAs) – controlled by private keys.
○ Contract Accounts – controlled by contract code.
● Transactions:
○ Transfer ETH or trigger smart contract execution.
● Blocks:
○ Contain transactions, state changes, and references to previous blocks.
● State:
○ The cumulative storage of account balances, contract code, and
storage data.
Consensus Mechanism:
● Initially Proof-of-Work (PoW) – miners solve puzzles to add blocks.
● Transitioning to Proof-of-Stake (PoS) with Ethereum 2.0 for:
○ Energy efficiency.
○ Increased scalability.
○ Reduced hardware requirements.
Development Tools and Ecosystem:
● Languages: Solidity (primary), Vyper.
● Frameworks: Truffle, Hardhat, Remix.
● Libraries: [Link], [Link].
● Testnets: Goerli, Sepolia (used for deployment testing).
● Rich ecosystem of DApps, DeFi platforms, NFTs, DAOs, and Layer-
2 scaling solutions.
Ethereum Use Cases:
● Decentralized Finance (DeFi) – lending, borrowing, exchanges.
● Tokenization – ERC-20 (fungible), ERC-721 (NFTs).
● Decentralized Autonomous Organizations (DAOs).
● Supply Chain Management.
● Gaming and Metaverse applications.
91
Web3 Technologies Strengths:
● Flexibility due to Turing-complete smart contracts.
● Large and active developer community.
● First-mover advantage in the smart contract space.
Challenges:
● Scalability limitations.
● High gas fees during congestion.
● Security vulnerabilities in smart contract code.
● Transition complexity to PoS.
Key Components:
1. Nodes
○ Computers running Ethereum client software (e.g., Geth, Nethermind,
Besu).
○ Maintain a local copy of the blockchain.
○ Verify and propagate transactions and blocks.
2. Clients
○ Implement the Ethereum protocol.
○ Support interaction with the Ethereum Virtual Machine (EVM).
3. Peers
○ Nodes connect to multiple peers to exchange blockchain data and stay
in sync.
Transaction Propagation:
1. A transaction is created and signed by an EOA.
2. The transaction is broadcast to peers.
3. Miners/validators select transactions from the mempool to include in
blocks.
4. Once included in a block, it becomes part of the permanent
blockchain history.
Network Layers:
1. Application Layer
○ DApps and user-facing applications.
○ Smart contracts written in Solidity/Vyper.
2. Execution Layer
○ Ethereum Virtual Machine executes bytecode deterministically.
3. Consensus Layer
○ Initially Proof-of-Work (Ethash), transitioning to Proof-of-Stake
under Ethereum 2.0.
4. Networking Layer
○ Peer discovery, data propagation, transaction gossip protocol.
● Testnets
○ Goerli, Sepolia (for testing contracts without real ETH).
● Private Networks
○ Used by organizations for internal blockchain applications.
93
Web3 Technologies Security and Redundancy:
● Decentralization ensures no single point of failure.
● Consensus rules prevent malicious actors from altering history.
● Full nodes verify all transactions independently.
1) Ethereum Nodes:
Nodes are individual computers that participate in the Ethereum network,
maintaining the blockchain and validating transactions.
1. Full Nodes: Store a complete copy of the Ethereum blockchain and
validate all transactions and blocks. They ensure the integrity of the
network.
2. Light Nodes: Store only a subset of the blockchain data, relying on
full nodes for transaction verification. They are less resource-
intensive, making them suitable for devices with limited storage.
3. Archive Nodes: Store all historical states of the Ethereum blockchain,
allowing users to access past versions of the blockchain for analysis
or research.
2) Ethereum Virtual Machine (EVM):
The EVM is the decentralized runtime environment that executes smart
contracts on the Ethereum network. It allows developers to deploy and run
their code in a consistent manner across all nodes. The EVM is crucial for
executing complex computations, facilitating the development of dApps.
3) Smart Contracts:
Smart contracts are self-executing agreements with the terms of the
contract directly written into code.
1. Automation: They automatically execute actions when predefined
conditions are met, reducing the need for intermediaries.
2. Transparency: The code and conditions are visible and verifiable on
the blockchain, ensuring trust among participants.
94
3. Programmable Logic: Developers can create complex logic and Smart Contracts and
Ethereum
workflows using programming languages like Solidity.
4) Transactions:
Transactions are the primary units of data on the Ethereum network,
representing the transfer of value or information.
1. Transaction Structure: Each transaction contains details like sender
and recipient addresses, value (in Ether), gas limit, and nonce
(transaction count).
2. Gas and Transaction Fees: Gas is a unit that measures the
computational effort required to execute operations. Users pay gas
fees in Ether to incentivize miners or validators for processing their
transactions.
5) Consensus Mechanisms:
The consensus mechanism ensures that all nodes in the network agree on
the validity of transactions and the state of the blockchain.
1. Proof of Work (PoW): Originally used by Ethereum, where miners
solve complex mathematical problems to validate transactions.
2. Proof of Stake (PoS): Ethereum is transitioning to PoS with
Ethereum 2.0, where validators are chosen based on the amount of
Ether they hold and are willing to "stake." This mechanism aims to
improve scalability and reduce energy consumption.
95
Web3 Technologies 4. Oracles:
Oracles are third-party services that provide smart contracts with real-
world data.
1. Data Integration: They enable smart contracts to access off-chain
information, such as market prices, weather data, and other external
events.
2. Examples: Chainlink and Band Protocol are popular oracle services
used in DeFi and other applications.
5. Wallets:
Wallets are tools that allow users to manage their Ether and tokens,
enabling them to send, receive, and interact with dApps.
1. Hot Wallets: Online wallets like MetaMask offer easy access to
dApps but are less secure than cold wallets.
2. Cold Wallets: Hardware wallets like Ledger and Trezor store
private keys offline, providing enhanced security for long-term
storage.
Purpose of EVM
Here are the several key purposes of EVM:
1. Execution of Smart Contracts: The EVM is responsible for
executing smart contracts, which are self-executing contracts with the
terms directly written into code. This allows for automated and
trustless transactions.
2. Decentralization: By running on a distributed network, the EVM
ensures that no single party controls the execution of contracts,
enhancing trust and security.
3. State Management: The EVM maintains a global state of all
accounts and smart contracts, tracking changes and ensuring
consistency across the network.
4. Resource Management: The gas mechanism in the EVM helps
regulate resource usage, preventing abuse and ensuring that
computational resources are allocated fairly.
5. Compatibility: The EVM allows developers to write applications in
high-level programming languages (like Solidity) that can be
compiled and executed on the Ethereum network, promoting ease of
development and interoperability.
6. Turing Completeness: The EVM’s Turing-complete nature allows it
to perform any computation that can be described algorithmically,
making it versatile for a wide range of applications.
7. Security: The EVM isolates contract executions, preventing
unintended interactions between contracts and enhancing the overall
security of the Ethereum ecosystem.
97
Web3 Technologies 3. Execution: Each node runs its own instance of the EVM to execute
the transaction. The EVM processes the contract logic and updates the
global state of the blockchain.
4. Gas Mechanism: Each operation consumes gas, which users pay for.
If the transaction runs out of gas, it reverts, but the gas is still spent.
5. Stack Management: The EVM uses a stack-based architecture to
manage data and execute instructions, storing temporary data in
memory and permanent data on-chain.
6. Block Creation and Validation: Processed transactions are bundled
into blocks by miners or validators, validated against consensus rules,
and added to the blockchain.
7. Finality: Once included in a block, the changes are permanent and
publicly verifiable.
98
8. Interoperability: Many other blockchains use EVM to enable the Smart Contracts and
Ethereum
deployment of Ethereum-compatible smart contracts, promoting a
broader ecosystem.
1. Languages
1. Solidity: The most widely used language for writing smart contracts.
It’s similar to JavaScript and designed specifically for Ethereum.
2. Vyper: A Python-like language focused on simplicity and security,
aimed at providing a more secure alternative to Solidity.
99
Web3 Technologies 2. Development Tools:
1. Remix: A web-based IDE that allows developers to write, test, and
deploy smart contracts easily.
2. Truffle: A popular framework that provides a suite of tools for
developing, testing, and deploying DApps, including a built-in testing
environment and migration scripts.
3. Hardhat: A development environment for Ethereum that includes
advanced debugging capabilities and support for local blockchain
networks.
4. Deployment:
1. Deployment Scripts: Developers create scripts to automate the
deployment of contracts to the Ethereum network, specifying
parameters and handling transaction fees.
2. Testnets: Developers often deploy contracts on Ethereum test
networks (like Ropsten, Rinkeby, or Goerli) to test functionality
without spending real Ether.
6. Security Practices:
1. Auditing: Conducting thorough audits of smart contracts to identify
vulnerabilities before deployment.
2. Common Vulnerabilities: Awareness of common issues like
reentrancy, overflow/underflow, and improper access control is
crucial for secure development.
100
7. Deployment to Mainnet: Smart Contracts and
Ethereum
Once contracts are thoroughly tested and audited, they can be deployed to
the Ethereum mainnet, where they will operate in a live environment.
Security Considerations:
1. Reentrancy Attacks: Occurs when a function makes an external call
to another contract before it resolves. This can allow the called
contract to call back into the original function, potentially leading to
unexpected behaviors.
2. Integer Overflow/Underflow: Operations that exceed the maximum
or minimum values of integers can lead to vulnerabilities. Use
libraries like SafeMath to prevent this.
3. Access Control Issues: Ensuring that only authorized users can
execute certain functions is critical. Implement proper access control
mechanisms using modifiers.
4. Third-Party Audits: Having contracts reviewed by independent
auditors can help identify vulnerabilities and improve overall security.
101
Web3 Technologies 5. Code Reviews: Regular code reviews among development teams can
catch potential issues early in the development process.
6. Proxy Contracts: Implement upgradeable contracts using proxy
patterns to allow for updates in case vulnerabilities are discovered
after deployment.
7. Timelock Mechanisms: Consider using timelocks for upgrades to
provide a window for users to react before changes are made.
8. Fallback Functions: Use fallback functions judiciously. They should
not contain complex logic and should primarily be used for receiving
Ether.
Benefits of EVM:
1. Execute Untrusted Code: One can execute untrusted code without
putting the data at risk. EVM guarantees that its computations will not
interfere with anything else happening in the system or with the
personal files.
2. Execute Complex Smart Contracts: One can run complex smart
contracts in EVM without worrying about how they interact with each
other. One can write them once and then run them on multiple
platforms, which allows for the creation of a single contract that runs
on multiple computing environments.
3. Deterministic Processing: Smart contracts written on EVM have
access to all of Ethereum's states at any given time, allowing for
processing to happen in a deterministic way and giving more
guarantees about their correctness. For example, one cannot make an
infinite loop in EVM by calling the same function twice. It would stop
executing and return a finite value.
4. Distributed Consensus: One of the potential applications of
Ethereum is to allow for distributed consensus where everyone is
running the same program but from their computers.
5. Robust Against Failure: This is a complex process because the
network needs to be able to come to a consensus at any given time.
This way, the system becomes more robust against failures of
individual nodes and you can update several nodes simultaneously
without worrying that they might end up disagreeing with each other
because of how code was written.
6. Easy to Write Stateful Contracts: From a developer perspective,
EVM is designed for writing smart contracts as well as for creating
DApps (decentralized applications), which are programs running on
distributed networks in a way that ensures all of them are seeing the
same version. It also makes it incredibly easy to write stateful
contracts, which need access to some kind of persistent storage.
102
Limitations of EVM: Smart Contracts and
Ethereum
1. High Cost of Storing Data: First is gas, which is what you need to
use to pay the fee to run a smart contract, and the other is the high
cost of storing data on the blockchain, which could take up more than
3TB
2. High Gas Cost: In Ethereum, all transactions require a fee to execute.
These fees are called "gas", and are paid in ETH tokens. Gas is priced
at the moment of execution, and depends on the complexity of
executing a transaction. The more difficult the computation for a
transaction, the higher its gas cost will be.
3. High Gas Price During Network Congestion: During times when
there is high network congestion due to many transactions being
pushed onto the blockchain, gas prices rise because there are fewer
transactions that can go through (the same amount of computational
power has to service more transactions).
4. Technical Expertise Required: Writing smart contracts and using
EVM requires technical expertise. It’s a Turing-complete system,
which allows programmers to write scripts in any programming
language they wish. This can be excellent or disastrous, depending on
the intention behind the code being written. Programming languages
are not inherently good or bad; it all depends on who is using them
and for what purpose. The downside of this technology is that it could
create a lot of complicated problems because with more power comes
more responsibility for the writer of code.
103
Web3 Technologies Later, the Ethereum platform emerged which was considered more
powerful, precisely because the developers/programmers could make
custom contracts in a Turing-complete language.
104
2. Automation: Smart contracts can automate the tasks/ processes that Smart Contracts and
Ethereum
are done manually.
3. Speed: Smart contracts use software code to automate tasks, thereby
reducing the time it takes to maneuver through all the human
interaction-related processes. Because everything is coded, the time
taken to do all the work is the time taken for the code in the smart
contract to execute.
4. Backup: Every node in the blockchain maintains the shared ledger,
providing probably the best backup facility.
5. Security: Cryptography can make sure that the assets are safe and
sound. Even if someone breaks the encryption, the hacker will have to
modify all the blocks that come after the block which has been
modified. Please note that this is a highly difficult and computation-
intensive task and is practically impossible for a small or medium-
sized organization to do.
6. Savings: Smart contracts save money as they eliminate the presence
of intermediaries in the process. Also, the money spent on the
paperwork is minimal to zero.
7. Manages information: Smart contract manages users' agreement,
and stores information about an application like domain registration,
membership records, etc.
8. Multi-signature accounts: Smart contracts support multi-signature
accounts to distribute funds as soon as all the parties involved confirm
the agreement.
It can also include the time constraints that can introduce deadlines in
the contract.
Every smart contract has its address in the blockchain. The contract
can be interacted with by using its address presuming the contract has
been broadcasted on the network.
The idea behind smart contracts is pretty simple. They are executed on a
basis of simple logic,
IF-THEN for example:
Note:
The WHEN constraint can be added to include the time factor in the smart
contracts. It can be seen that these smart contracts help set conditions that
have to be fulfilled for the terms of the contract agreement to be executed.
There is no limit on how much IF or THEN you can include in your
intelligent contract.
106
Smart Contract Working: Smart Contracts and
Ethereum
Network updates: After smart contracts are executed, all the nodes
on the network update their ledger to reflect the new state. Once the
record is posted and verified on the blockchain network, it cannot be
modified, it is in append mode only.
107
Web3 Technologies contract can, for example, enforce vehicle maintenance service every
six months; failure of which will lead to suspension of driving license.
3. Music Industry: The music industry could record the ownership of
music in a blockchain. A smart contract can be embedded in the
blockchain and royalties can be credited to the owner's account when
the song is used for commercial purposes. It can also work in
resolving ownership disputes.
4. Government elections: Once the votes are logged in the blockchain,
it would be very hard to decrypt the voter address and modify the vote
leading to more confidence against the ill practices.
5. Management: The blockchain application in management can
streamline and automate many decisions that are taken late or
deferred. Every decision is transparent and available to any party who
has the authority(an application on the private blockchain). For
example, a smart contract can be deployed to trigger the supply of raw
materials when 10 tonnes of plastic bags are produced.
6. Healthcare: Automating healthcare payment processes using smart
contracts can prevent fraud. Every treatment is registered on the
ledger and in the end, the smart contract can calculate the sum of all
the transactions. The patient can't be discharged from the hospital
until the bill has been paid and can be coded in the smart contract.
108
2. Autonomy: There are direct dealings between parties. Smart Smart Contracts and
Ethereum
contracts remove the need for intermediaries and allow for
transparent, direct relationships with customers.
3. Reduce fraud: Fraudulent activity detection and reduction. Smart
contracts are stored in the blockchain. Forcefully modifying the
blockchain is very difficult as it's computation-intensive. Also, a
violation of the smart contract can be detected by the nodes in the
network and such a violation attempt is marked invalid and not stored
in the blockchain.
4. Fault-tolerance: Since no single person or entity is in control of the
digital assets, one-party domination and situation of one part backing
out do not happen as the platform is decentralized and so even if one
node detaches itself from the network, the contract remains intact.
5. Enhanced trust: Business agreements are automatically executed and
enforced. Plus, these agreements are immutable and therefore
unbreakable and undeniable.
6. Cost-efficiency: The application of smart contracts eliminates the
need for intermediaries(brokers, lawyers, notaries, witnesses, etc.)
leading to reduced costs. Also eliminates paperwork leading to paper
saving and money-saving.
3.12 SUMMARY
The chapter begins by tracing the history of smart contracts, starting
with Nick Szabo’s 1994 conceptualization, inspired by vending
machines as primitive automated agreements.
109
Web3 Technologies It introduces Ricardian contracts as hybrid legal–digital documents
bridging legal text and executable code.
Answer:
The term “smart contract” was introduced by Nick Szabo in 1994, defined
as a set of promises in digital form with protocols for performance.
Inspired by vending machines, the concept aimed to automate and enforce
agreements without intermediaries. Early implementations were
centralized and limited, but blockchain technology — especially Ethereum
— enabled fully decentralized and programmable contracts.
110
Q2. Define Ricardian contracts and explain their key features. Smart Contracts and
Ethereum
Answer:
A Ricardian contract is a human-readable and machine-readable digital
agreement, cryptographically signed and hashed for immutability.
Features include:
Digital signatures
Answer:
Smart contract templates are standardized blueprints for creating recurring
blockchain agreements. Advantages include:
Faster development
Reusability
Answer:
Oracles provide off-chain data to blockchain smart contracts, enabling
them to respond to real-world events. Types include inbound, outbound,
software, hardware, and human oracles. They are critical for applications
like DeFi, insurance, and supply chain but require trust and security
measures such as decentralization and cryptographic proofs.
Q5. Outline the steps for deploying a smart contract on Ethereum.
Answer:
1. Write contract code (e.g., Solidity)
2. Compile to bytecode + ABI
3. Create deployment transaction (no recipient)
4. Sign with deployer’s private key
111
Web3 Technologies 5. Broadcast to the network
6. Mining/validation and contract address assignment
7. Optional source verification
8. Interact via ABI using calls/transactions
Q6. What was The DAO, and why is it significant?
Answer:
The DAO was a decentralized investment fund launched in 2016 on
Ethereum. It allowed token holders to vote on proposals for project
funding. A vulnerability led to a hack draining 3.6 million ETH. The
community’s response — a hard fork — created Ethereum (ETH) and
Ethereum Classic (ETC). It remains significant for lessons on security,
governance, and blockchain immutability.
Q7. Give an overview of Ethereum’s main features.
Answer:
Ethereum is a decentralized blockchain supporting Turing-complete smart
contracts and DApps. It uses the EVM for execution, Ether (ETH) as
currency, and a gas system for resource allocation. Applications include
DeFi, NFTs, DAOs, and more, supported by an active developer
community.
Q8. Differentiate between EOAs and contract accounts in Ethereum.
Answer:
Answer:
A peer-to-peer network of nodes runs Ethereum clients, maintains
blockchain copies, propagates transactions, and executes smart contracts.
It includes mainnet (public), testnets (Goerli, Sepolia), and private
networks. Layers include application, execution (EVM), consensus, and
networking.
Q10. List and explain key components of the Ethereum ecosystem.
Answer:
Smart Contracts
DApps
DAOs
Oracles
Answer:
The EVM is a decentralized, Turing-complete runtime environment for
executing smart contract bytecode on all Ethereum nodes. It ensures
deterministic execution, security, and interoperability, forming the
foundation for Ethereum’s programmability.
*****
113
4
ETHEREUM AND ETHEREUM
DEVELOPMENT ENVIRONMENT
Unit Structure
4.0 Objective
4.1 Blocks and Blockchain
4.2 Wallets and client software
4.3 Nodes and miners
4.4 APIs, tools, and DApps
4.5 Supporting protocols
4.6 Programming languages
4.7 Ethereum Development Environment: Overview
4.8 Test networks
4.9 Components of a private network
4.10 starting up the private network
4.11 mining on the private network
4.12 Remix IDE
4.13 MetaMask
4.14 Using MetaMask and Remix IDE to deploy a smart contract
4.15 Summary
4.16 Exercise
4.0 OBJECTIVE
The objective of this chapter is to provide a comprehensive understanding
of the Ethereum blockchain and its development environment. It explains
the structure and functioning of Ethereum blocks, wallets, nodes, APIs,
tools, supporting protocols, and programming languages. It also covers the
process of setting up private networks, mining, and using popular tools
like Remix IDE and MetaMask for developing, testing, and deploying
smart contracts on Ethereum testnets or the mainnet.
114
Ethereum And Ethereum
4.1 BLOCKS AND BLOCKCHAIN Development Environment
Definition:
● A blockchain is a distributed, append-only ledger composed of
sequentially linked blocks.
● Each block contains a set of transactions, a reference (hash) to the
previous block, and metadata ensuring integrity.
Structure of a Block;
1. Block Header:
○ Parent Hash – hash of the previous block, linking the chain.
○ Ommers Hash – hash of ommer (uncle) blocks.
○ Beneficiary Address – address receiving mining/validation rewards.
○ State Root – hash of the entire system state after applying the block’s
transactions.
○ Transactions Root – Merkle root of all transactions in the block.
○ Receipts Root – Merkle root of all transaction receipts.
○ Logs Bloom – Bloom filter for efficient log/event searching.
○ Difficulty – difficulty level of the proof-of-work puzzle.
○ Number – block height in the chain.
○ Gas Limit – maximum gas allowed for transactions in the block.
○ Gas Used – total gas consumed by all transactions.
○ Timestamp – block creation time.
○ Extra Data – arbitrary data up to 32 bytes.
○ Mix Hash & Nonce – proof-of-work fields (PoW mode).
2. Transactions:
○ List of transactions included in the block.
○ Each transaction changes the blockchain state.
3. Ommers (Uncles):
○ Valid blocks mined almost simultaneously but not part of the main
chain.
○ Provide additional rewards to encourage decentralization.
115
Web3 Technologies Blockchain Linking:
● Each block points to its parent via the parent hash.
● This creates an immutable chain: changing a past block would alter all
subsequent hashes, making tampering evident.
● Consensus rules determine the “canonical” chain in case of forks.
State Transition:
● Ethereum’s blockchain records state changes.
● Applying transactions in a block to the previous state produces the
new state (captured by the State Root).
● This model is known as the Ethereum State Machine.
Block Propagation:
1. A miner/validator assembles a block from transactions in the
mempool.
2. The block is validated and broadcast to peers.
3. Other nodes verify transactions, state changes, and proof-of-
work/stake.
4. Once validated, it is added to the node’s local chain.
Importance in Ethereum:
● Blocks bundle transactions and record the system’s state at specific
points.
● They serve as checkpoints for consensus and enable replay protection.
● Provide an immutable, verifiable transaction history.
Relation to Consensus:
● In PoW, miners compete to find a valid nonce.
● In PoS, validators are selected to propose and attest to blocks.
● Chain selection rules (e.g., longest chain, GHOST protocol) ensure
consistency.
116
● Client Software: Programs implementing the Ethereum protocol, Ethereum And Ethereum
Development Environment
enabling nodes to participate in the network by validating blocks,
executing smart contracts, and maintaining the blockchain.
Wallets:
Wallets do not store Ether directly; they store the keys that allow control
of Ether and smart contracts.
Types of Wallets:
1. Hot Wallets (connected to the internet)
○ Examples: MetaMask, MyEtherWallet.
○ Convenient but more vulnerable to hacking.
3. Paper Wallets:
○ Printed QR codes containing private/public keys.
○ Prone to physical loss or damage.
4. Mobile Wallets:
○ Smartphone apps like Trust Wallet.
5. Desktop Wallets:
○ Installed software like Mist (deprecated) or Ethereum Wallet.
6. Web Wallets:
○ Browser-based, run on centralized or decentralized platforms.
Key Functions:
● Generating and storing private/public keys.
● Creating and signing transactions.
● Viewing account balances and transaction history.
● Interacting with smart contracts.
Security Considerations:
● Protect private keys with encryption and backups.
● Use hardware wallets for long-term storage.
117
Web3 Technologies ● Beware of phishing and malware.
Client Software:
Ethereum clients are essential for running a node and interacting with the
blockchain.
Roles of Clients:
● Maintain a full or partial copy of the blockchain.
● Verify transactions and blocks.
● Relay data across the network.
● Provide JSON-RPC APIs for DApps and wallets.
Types of Clients:
1. Full Nodes
○ Store the entire blockchain.
○ Validate all transactions independently.
○ Examples: Geth, OpenEthereum (deprecated), Nethermind, Besu.
2. Light Clients:
○ Store only block headers.
○ Rely on full nodes for detailed data.
3. Archive Nodes:
○ Store complete blockchain history and past states.
118
● DApps integrate wallets to sign and send transactions via web3 Ethereum And Ethereum
Development Environment
libraries.
Types of Nodes
1. Full Nodes:
○ Store the complete blockchain and state.
○ Validate all transactions and smart contracts independently.
○ Examples: Geth, Nethermind, Besu.
2. Light Nodes:
○ Store only block headers.
○ Request full data from full nodes when needed.
○ Useful for mobile and low-resource environments.
3. Archive Nodes:
○ Store historical states of the blockchain.
○ Used by block explorers, analytics services.
Node Functions:
● Propagate transactions and blocks.
● Verify block validity.
● Execute smart contracts in the Ethereum Virtual Machine (EVM).
● Maintain and update the local blockchain copy.
Ethereum Miners:
● Definition: Miners are specialized nodes in Proof-of-Work (PoW)
Ethereum that compete to produce new blocks by solving
computational puzzles.
● Miners validate transactions, group them into blocks, and perform
PoW to secure the network.
119
Web3 Technologies Mining Process:
1. Collect pending transactions from the mempool.
2. Verify transaction validity and gas payment.
3. Assemble a candidate block with transactions, ommers (uncles), and
metadata.
4. Perform the Ethash PoW algorithm to find a nonce satisfying the
difficulty target.
5. Broadcast the mined block to the network.
6. Receive block rewards and gas fees.
Rewards in PoW:
● Block Reward: Fixed ETH amount for successfully mining a block.
● Uncle Rewards: Incentives for including near-miss valid blocks
(ommers).
● Transaction Fees: Gas paid by users.
Node–Miner Relationship:
● All miners are nodes, but not all nodes are miners.
● Full nodes validate blocks produced by miners/validators.
● Light nodes rely on full nodes for complete data.
120
○ Provides methods to query blockchain data, send transactions, interact Ethereum And Ethereum
Development Environment
with smart contracts.
○ Supported by clients like Geth, Nethermind, Besu.
2. [Link]:
○ JavaScript library to interact with Ethereum from web applications.
○ Simplifies contract calls, transactions, and event subscriptions.
3. [Link]:
○ Lightweight alternative to [Link].
○ Offers wallet management, contract interaction, and blockchain
queries.
4. Infura API:
○ Provides scalable Ethereum access without running a full node.
○ Used by DApps to connect to Ethereum over HTTPS/WebSockets.
4.4.2. Tools:
Tools assist in developing, testing, and deploying smart contracts and
DApps.
2. Truffle Suite:
○ Framework for smart contract development, testing, and migration.
○ Includes Ganache (local blockchain for testing).
3. Hardhat:
○ Development environment for compiling, deploying, testing.
○ Supports advanced debugging and forking mainnet state.
4. Ganache:
○ Personal Ethereum blockchain for development.
○ Runs locally with configurable mining and account settings.
121
Web3 Technologies 5. MythX, Slither:
○ Security analysis tools for detecting vulnerabilities.
DApp Characteristics:
● Decentralized control — no single point of failure.
● Open-source code for transparency.
● Incentive systems via tokens.
a) Whisper Protocol:
● Purpose: Peer-to-peer messaging protocol for decentralized
communication between DApps.
122
● Functionality: Ethereum And Ethereum
Development Environment
○ Enables DApps to send and receive encrypted messages.
○ Useful for signaling and off-chain coordination.
● Status: Experimental and not widely used in production.
● Features:
○ Anonymity and privacy via message encryption.
○ Suitable for low-throughput, secure messaging.
b) Swarm:
● Purpose: Decentralized storage and content distribution system.
● Functionality:
○ Stores and distributes large files without relying on centralized
servers.
○ Works with Ethereum smart contracts for data availability.
● Features:
○ Redundancy and fault tolerance.
○ Incentive layer for resource sharing.
● Integration:
○ Used for storing DApp assets (e.g., website frontends, media).
○ Complements IPFS but tightly integrated with Ethereum’s
ecosystem.
● Functionality:
○ Uses content-addressing (hashes) to identify and retrieve data.
○ Efficient distribution across nodes.
123
Web3 Technologies d) Layer-2 Protocols:
● Purpose: Scalability solutions operating on top of Ethereum’s base
layer.
● Examples:
○ State Channels: Off-chain transactions with on-chain settlement.
○ Plasma: Child chains for high throughput applications.
○ Rollups: Batch processing transactions (Optimistic Rollups,
zkRollups).
● Benefits:
○ Reduced gas fees.
○ Higher transaction throughput.
Primary Languages:
a) Solidity:
● Type: Statically typed, contract-oriented.
● Purpose: Most widely used for Ethereum smart contract
development.
● Syntax: Inspired by JavaScript, C++, and Python.
● Features:
○ Supports inheritance, libraries, and complex data types.
○ Includes modifiers for access control.
124
○ Event logging for DApp interaction. Ethereum And Ethereum
Development Environment
● Compilation: Uses solc to produce EVM bytecode and ABI.
● Usage:
○ ERC token standards.
○ DeFi protocols.
○ NFTs and DAOs.
b) Vyper:
● Type: Python-like syntax, strongly typed.
● Purpose: Designed for simplicity and security.
● Features:
○ Minimalistic — intentionally excludes features like modifiers,
inheritance to avoid complexity.
○ Focuses on auditability and readability.
● Use Cases:
○ Security-sensitive contracts.
○ Protocol-level development.
Supporting Languages:
● Bamboo: Experimental language for formal verification-friendly
contracts.
● Yul:
○ Intermediate language for EVM and eWASM.
○ Optimized for low-level operations and cross-platform compilation.
125
Web3 Technologies ● Fe:
○ Python-inspired language under development.
○ Emphasizes safety and simplicity.
Compilation Flow:
1. Write source code in Solidity/Vyper.
2. Compile to EVM bytecode via language compiler.
3. Generate ABI for DApp integration.
4. Deploy bytecode to Ethereum blockchain.
Core Components:
1. Programming Languages
○ Solidity, Vyper, LLL, Yul — used to write smart contracts.
2. Compilers:
○ Convert high-level code to Ethereum Virtual Machine (EVM)
bytecode.
○ Example: solc for Solidity, vyper compiler.
3. Development Frameworks:
○ Truffle, Hardhat, Brownie — manage project structure, migrations,
and testing.
126
4. Local Blockchain Simulators: Ethereum And Ethereum
Development Environment
○ Ganache, Hardhat Network — simulate Ethereum for testing without
costs.
5. Ethereum Clients
○ Geth, Nethermind, Besu — connect to and interact with the Ethereum
network.
Stages of Development:
1. Smart Contract Design:
○ Define contract logic, state variables, and functions.
2. Implementation:
○ Write code in Solidity/Vyper.
3. Compilation:
○ Convert source to bytecode and generate ABI.
4. Testing:
○ Use frameworks and simulators to validate logic and security.
5. Deployment:
○ Deploy to testnets, then mainnet.
6. Interaction:
○ Use DApp frontends, scripts, or CLI tools to interact.
7. Maintenance:
○ Upgrade via proxies, bug fixes, audits.
Test Networks:
● Used for risk-free contract deployment and experimentation.
● Examples:
○ Goerli
○ Sepolia
● Provide free test ETH from faucets.
127
Web3 Technologies Integrated Development Environments (IDEs):
● Remix IDE
○ Web-based, supports compilation, deployment, debugging.
● VS Code
○ With Solidity plugins for syntax highlighting and linting.
Security Tools:
● MythX, Slither, Oyente for static and dynamic analysis.
● Essential for finding vulnerabilities before deployment.
Best Practices:
● Start on testnets before mainnet deployment.
● Regular code audits.
● Maintain clear documentation.
● Use version locking for compiler versions to avoid inconsistencies.
Purpose:
● Safe environment for:
○ Contract development and debugging.
○ Testing deployment scripts and DApp integration.
○ Experimenting with protocol upgrades.
● Avoids financial risk since test ETH has no real-world value.
128
Key Ethereum Testnets: Ethereum And Ethereum
Development Environment
1. Goerli
○ Cross-client, proof-of-authority initially, now PoS-compatible.
○ Supported by major Ethereum clients.
○ Reliable for multi-client testing.
2. Sepolia:
○ PoS testnet with smaller state size.
○ Fast syncing and efficient for development.
○ Preferred for lightweight testing.
Testnet vs Mainnet:
Best Practices:
● Always deploy to testnets before mainnet.
● Use test ETH for full workflow testing.
● Monitor gas costs and transaction behavior in testnets to estimate
mainnet performance.
129
Web3 Technologies
4.9 COMPONENTS OF A PRIVATE NETWORK
● A private Ethereum network is a blockchain network restricted to a
specific group of participants, used for internal testing, enterprise
solutions, or research.
● It operates with its own genesis block, consensus rules, and network
permissions.
Core Components;
a) Genesis Block:
● The first block in the blockchain.
● Customizable to define:
○ Initial account balances.
○ Consensus parameters.
○ Network ID.
● Configured via a genesis file in JSON format.
b) Ethereum Clients:
● Software for running nodes in the network.
● Examples: Geth, Besu, Nethermind.
● Nodes can be configured for:
○ Mining/validating blocks.
○ RPC endpoints for DApps.
○ Permissioned peer connections.
c) Consensus Mechanism:
● Determines how blocks are validated and added.
d) Networking Layer:
● Manages peer discovery and data propagation.
130
● In private networks, peer lists may be manually defined. Ethereum And Ethereum
Development Environment
● Uses the devp2p protocol or permissioned networking.
e) Accounts:
● Externally Owned Accounts (EOAs) for users.
● Contract Accounts for smart contracts.
● Pre-funded accounts can be set in the genesis file.
g) Block Explorer:
● Tool for viewing transactions, blocks, and network state.
● Examples: Blockscout, custom explorers.
Additional Components:
● Wallets: For managing private keys (e.g., MetaMask configured for
the private network).
● Monitoring Tools: For tracking network performance and security.
● Oracles: Optional for feeding off-chain data.
131
Web3 Technologies Step 1: Install Geth on Your System
● Go to the official Geth download page and download the setup
according to your operating system.
132
Ethereum And Ethereum
Development Environment
As seen in the above diagram we can see that blockchain is initialized with
the genesis block.
To create a private blockchain, a genesis blockis needed. To do this, create
a genesis file, which is a JSON file with the following commands-
comma
{
"config":{
133
Web3 Technologies "chainId":987,
"homesteadBlock":0,
"eip150Block":0,
"eip155Block":0,
"eip158Block":0
},
"difficulty":"0x400",
"gasLimit":"0x8000000",
"alloc":{}
}
Explanation:
● config: It defines the blockchain configuration and determines how
the network will work.
● chainId: This is the chain number used by several blockchains. The
Ethereum main chain number is "1". Any random number can be
used, provided that it does not match with another blockchain number.
● homesteadBlock: It is the first official stable version of the Ethereum
protocol and its attribute value is "0".
● One can connect other protocols such as Byzantium, eip155B, and
eip158. To do this, under the homesteadBlock add the protocol name
with the Block prefix (for example, eip158Block) and set the
parameter “0” to them.
● difficulty: It determines the difficulty of generating blocks. Set it low
to keep the complexity low and to avoid waiting during tests.
● gasLimit: Gas is the “fuel” that is used to pay transaction fees on the
Ethereum network. The more gas a user is willing to spend, the higher
will be the priority of his transaction in the queue. It is recommended
to set this value to a high enough level to avoid limitations during
tests.
● alloc: It is used to create a cryptocurrency wallet for our private
blockchain and fill it with fake ether. In this case, this option will not
be used to show how to initiate mining on a private blockchain.
This file can be created by using any text editor and save the file with
JSON extension in the folder MyNetwork.
134
Step 4: Execute genesis file Ethereum And Ethereum
Development Environment
Open cmd or PowerShell in admin mode enter the following command-
command
geth --identity
identity "yourIdentity" init \path_to_folder\[Link] --
datadir \path_to_data_directory
path_to_data_directory\MyPrivateChain
Parameters-
path_to_folder- Location of Genesis file.
path_to_data_directory- Location of the folder in which the data of our
private chain will be stored.
The above command instructs Geth to use the [Link] file.
After executing the above command Geth is connected to the Genesis file
and it seems like this:
The command also has the identifier 8080. It should be replaced with an
arbitrary number that is not equal to the identifier of the networks already
created, for example, the identifier of the main network Ethereum
("networkid = 1"). After successfully executing the command we can see
like this-
135
Web3 Technologies
Note:
The highlighted text is the address of [Link] file finds it in your console
and copy it for use in the next step.
ste
Every time there is a need to access the private network chain, one will
need to run commands in the console that initiate a connection to the
Genesis file and the private network.
Now a personal blockchain and a private Ethereum network is ready.
136
Ethereum And Ethereum
Development Environment
It can be seen from the above screenshot that it shows zero balance. This
is because when starting a private network
network in the genesis file, we did not
specify anything in the alloc attribute.
137
Web3 Technologies Consensus Options for Private Mining
1. Proof-of-Work (PoW):
○ Uses the Ethash algorithm.
○ Miners solve computational puzzles to produce blocks.
○ Suitable for testing mining economics or PoW-based logic.
2. Proof-of-Authority (PoA):
○ Validators are pre-approved in the genesis configuration.
○ Faster block times, minimal computational cost.
○ Examples: Clique, IBFT.
Mining Setup Steps (PoW Example)
3. Monitor Mining:
Attach to the console:
arduino
geth attach ipc:[Link]
138
4. Block Rewards: Ethereum And Ethereum
Development Environment
○ Miners receive block rewards and transaction fees in private ETH.
○ Used for deploying contracts and testing DApps.
3. Block Creation
○ Validators take turns producing blocks according to configuration.
Best Practices:
● Keep mining difficulty low for PoW to avoid long block times.
● Use PoA for faster and more predictable block generation in
development.
● Regularly back up accounts holding mining rewards.
139
Web3 Technologies
Step 2: Write the Smart contract in the code section, and click the
Compile button under the Compiler window to compile the contract.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.5.0;
contract SolidityTest{
uint a=10;
uint b=12;
uint sum;
function getResult() public returns(uint){
sum=a+b;
return sum;
}
}
140
Step 3: To execute the code, click on the Deploy button under Deploy and Ethereum And Ethereum
Development Environment
Run Transactions window.
Step 4: After deploying the code click on the method calls under the drop-
down of deployed contracts to run the program, and for output, check to
click on the drop-down on the console.
141
Web3 Technologies
4.13 METAMASK
How to use MetaMask to Deploy a Smart contract in Solidity
(Blockchain)?
Smart contracts are self-executing contracts. They were first proposed by
Nick Szabo in the 90s. They are set of rules and protocols which two
parties agree upon and have to follow. One of the main features is that
they are immutable once deployed on the blockchain. It is widely used in
the Ethereum blockchain. The main language used for writing smart
contracts in Solidity.
IDE:
To write and execute solidity codes, the most common IDE used is an
online IDE known as REMIX. You can either open it online on
[Link] or install it in your system from
[Link] You can also use Mist (the
Ethereum DApp browser).
After you write the code and compile it you can deploy it in following
ways –
● Remix VM (London)
● Remix VM (Berlin)
● Injected Provider - MetaMask
● Hardhat Provider
● Ganache Provider
● Foundry Provider
● Wallet Connect
● External Http Provider
● L2 - Optimism Provider
● L2 - Arbitrum One Provider
This article explains how to deploy your contract by using MetaMask as
Injected Provider - MetaMask.
MetaMask:
MetaMask is a type of Ethereum wallet that bridges the gap between the
user interfaces for Ethereum (e.g. Mist browsers, DApps) and the regular
web (e.g. Chrome, Firefox, websites).
142
Its function is to inject a JavaScript library called [Link] into the Ethereum And Ethereum
Development Environment
namespace of each page your browser loads. [Link] is written by the
Ethereum core team. MetaMask is mainly used as a plugin in chrome. You
can add it from here or download it directly from this link.
After adding MetaMask as an extension in chrome and creating an
account, set up your account as follows –
Step 1: Select Goerli Test Network from a list of available networks as
below:
Metamask
Step 2: Request test ether by using this link :
[Link]
Goerli Faucet
Step 3: MetaMask is ready for deployment. To know more about
MetaMask visit the MetaMask official guide.
Steps to deploy your contract
143
Web3 Technologies Step 1: Open Remix IDE in your browser. After opening click on + and
write the filename as follows:
144
Step 3: After compilation and move to deploy section just below the Ethereum And Ethereum
Development Environment
compilation and select Injected Provider - MetaMask in place of Remix
VM as shown below -
146
Ethereum And Ethereum
Development Environment
Deployed Contract
Step 6: Expand the deployed contract as below and get the output using
the get_output() function:
147
Web3 Technologies
148
Output Ethereum And Ethereum
Development Environment
Step 7: Now, to verify whether your transaction (process) executed
successfully, you can check your balance on MetaMask.
Now your contract is completely ready to function. Make sure the
compiler version matches the version of your solidity code. This is the
basic implementation of MetaMask with solidity.
Features:
● Manage Ethereum accounts and keys
● Send/receive ETH and tokens
● Connect to decentralized applications (DApps)
● Switch between Ethereum mainnet, testnets, or custom networks
149
Web3 Technologies 2. Create a Wallet:
○ Click Get Started → Create a Wallet
○ Set a strong password
○ Backup the Secret Recovery Phrase securely
3. Select Network:
○ By default, MetaMask connects to Ethereum Mainnet.
○ To test, switch to a test network like Sepolia or Goerli:
■ Settings → Advanced → Enable test networks
■ Select the desired testnet from the network dropdown
Steps in Remix:
1. Create new file [Link]
2. Paste the contract code
3. Save the file
3. Allow Connection:
○ MetaMask will prompt you to connect
○ Select your account and approve
Verifying Deployment:
● Copy the deployed contract address from Remix
● Paste into a blockchain explorer (e.g., Etherscan)
● View transaction history, contract bytecode, and more
Best Practices:
● Test on Testnets before mainnet deployment to avoid losing ETH
● Always backup your MetaMask wallet
● Keep private keys and recovery phrases offline
● Use correct Solidity compiler version to avoid compatibility issues
● Optimize gas usage in your smart contract
Summary Flow:
1. Install & Set up MetaMask
2. Fund test account with faucet ETH
3. Open Remix IDE and write contract
4. Compile the contract
5. Connect Remix to MetaMask
152
6. Deploy to the selected network Ethereum And Ethereum
Development Environment
7. Confirm transaction in MetaMask
8. Interact with the contract in Remix or via other DApps
4.15 SUMMARY
This chapter introduces the core concepts and components of the
Ethereum ecosystem.
● Blocks & Blockchain: Defines the structure of blocks, including
transactions, ommers, and metadata. Explains blockchain linking,
consensus rules, and the Ethereum state machine.
● Wallets & Clients: Describes different types of wallets (hot, cold,
paper, mobile, desktop, web) and Ethereum clients (full, light,
archive). Discusses security considerations and how wallets interact
with clients.
● Nodes & Miners: Explains node types, functions, and the mining
process under PoW and PoS. Covers the relationship between nodes
and miners.
● APIs, Tools & DApps: Introduces Ethereum APIs (JSON-RPC,
[Link], [Link], Infura), development tools (Remix, Truffle,
Hardhat, Ganache), and DApps’ characteristics.
● Supporting Protocols: Details Whisper, Swarm, IPFS, and Layer-2
protocols for scalability, storage, and communication.
● Programming Languages: Discusses Solidity, Vyper, LLL, Yul,
and others used for Ethereum smart contract development.
● Ethereum Development Environment: Outlines programming
languages, compilers, frameworks, clients, test networks, and
security tools.
● Test Networks: Explains the purpose and features of Goerli,
Sepolia, and legacy testnets.
● Private Network Components: Describes the genesis block,
clients, consensus mechanisms, accounts, APIs, and benefits of
private networks.
● Starting a Private Network: Provides step-by-step setup
instructions using Geth, creating accounts, and mining.
● Mining on a Private Network: Covers PoW and PoA mining
configurations and best practices.
153
Web3 Technologies ● Remix IDE & MetaMask: Gives practical guidance for compiling,
deploying, and interacting with smart contracts using Remix IDE
connected to MetaMask.
● Deployment Workflow: Shows how to write, compile, and deploy a
smart contract, confirm transactions, and verify on blockchain
explorers.
Examples:
● State Channels: Off-chain transactions with on-chain settlement.
● Plasma: Child chains for specific use cases.
● Rollups: Batch transaction processing (Optimistic, zkRollups).
They are crucial for scaling Ethereum without compromising
decentralization and security.
Reference Link:
[Link]
private-ethereum-network/
[Link]
a-smart-contract-in-solidity-blockchain/
*****
157
Module II
Unit 3
5
WEB3, SERENITY, ETHEREUM
Unit Structure
5.0 Objectives
5.1 Introduction to Web3
5.2 Development Framework: Ethereum 2.0
5.3 Serenity
5.4 Summary
5.5 Questions
5.6 Reference
5.0 OBJECTIVES
Serenity, Ethereum, Hyperledger, and tokenization each contribute
uniquely to advancing blockchain technology and its applications.
Ethereum aims to create a decentralized platform for running smart
contracts and decentralized applications (dApps), enabling programmable,
trust less interactions on a public blockchain. Serenity, also known as
Ethereum 2.0, focuses on upgrading Ethereum by improving scalability,
security, and sustainability through mechanisms like Proof of Stake and
shard chains. Hyperledger, in contrast, is a collaborative open-source
project designed to develop enterprise-grade, permissioned blockchain
frameworks that prioritize privacy, modularity, and interoperability for
businesses. Tokenization ties these efforts together by representing real-
world assets, rights, or utilities as digital tokens on blockchains,
facilitating new economic models and liquidity. Together, these initiatives
aim to foster secure, efficient, and flexible blockchain ecosystems that
empower users, enterprises, and developers.
158
5.1.1What is Web3? Web3, Serenity, Ethereum
Web3 has become a catch-all term for the vision of a new, better internet.
At its core, Web3 uses blockchains, cryptocurrencies, and NFTs to give
power back to the users in the form of ownership.
Web3 puts power in the hands of individuals rather than corporations.
a few core principles guide its creation.
Web3 is decentralized: instead of large swathes of the internet
controlled and owned by centralized entities, ownership gets
distributed amongst its builders and users.
Web3 is permissionless: everyone has equal access to participate in
Web3, and no one gets excluded.
Web3 has native payments: it uses cryptocurrency for spending and
sending money online instead of relying on the outdated infrastructure
of banks and payment processors.
Web3 is trust less: it operates using incentives and economic
mechanisms instead of relying on trusted third-parties.
Censorship resistance:
The power dynamic between platforms and content creators is
massively imbalanced.
On Web3, your data lives on the blockchain. When you decide to
leave a platform, you can take your reputation with you, plugging it
into another interface that more clearly aligns with your values.
Web 2.0 requires content creators to trust platforms not to change the
rules, but censorship resistance is a native feature of a Web3 platform.
159
Web3 Technologies Decentralized autonomous organizations (DAOs):
As well as owning your data in Web3, you can own the platform as a
collective, using tokens that act like shares in a company. DAOs let
you coordinate decentralized ownership of a platform and make
decisions about its future.
Identity:
Traditionally, you would create an account for every platform you
use. For example, you might have a Twitter account, a YouTube
account, and a Reddit account. Want to change your display name or
profile picture? You have to do it across every account. You can use
social sign-ins in some cases, but this presents a familiar problem—
censorship. In a single click, these platforms can lock you out of
your entire online life. Even worse, many platforms require you to
trust them with personally identifiable information to create an
account.
Web3 solves these problems by allowing you to control your digital
identity with an Ethereum address and Ethereum Name Service
(ENS) profile. Using an Ethereum address provides a single login
across platforms that is secure, censorship-resistant, and anonymous.
Native payments:
Web2's payment infrastructure relies on banks and payment
processors, excluding people without bank accounts or those who
happen to live within the borders of the wrong country. Web3 uses
tokens like ETH to send money directly in the browser and requires
no trusted third party.
160
need higher levels of adoption on layer 2 to make Web3 accessible to Web3, Serenity, Ethereum
everyone.
2. User experience:
The technical barrier to entry to using Web3 is currently too high. Users
must comprehend security concerns, understand complex technical
documentation, and navigate unintuitive user interfaces. Wallet providers,
in particular, are working to solve this, but more progress is needed before
Web3 gets adopted en masse.
3. Education:
4. Centralized infrastructure:
161
Web3 Technologies
162
Web3, Serenity, Ethereum
5.1.5 Summary:
Web3 (or Web 3.0) is the next generation of the internet that aims to be
decentralized, user-owned, and blockchain-based.
Web3, or Web 3.0, is the evolving vision of a decentralized internet that
shifts control from centralized corporations to users through blockchain
technology. Unlike Web2, where platforms like Google and Facebook
dominate data and content, Web3 enables users to own their digital
identities, assets, and interactions using tools like cryptocurrencies, NFTs,
and decentralized applications (dApps). Web3 also introduces new models
for finance (DeFi), governance (DAOs), and the digital economy.
5.1.7 Summary:
Contract deployment refers to the process of uploading and activating a
smart contract on a blockchain network, making it publicly accessible and
executable. A smart contract is a self-executing program that runs on a
decentralized network like Ethereum and contains the logic for automated
transactions or agreements. During deployment, the contract’s compiled
bytecode is sent as a transaction to the blockchain, typically initiated by a
user or developer’s wallet. Once confirmed by the network, the contract
receives a unique address and becomes immutable and autonomous,
meaning it cannot be altered and can be interacted with by users or other
contracts. Deployment often requires paying a transaction fee (gas) and
must be carefully planned, as errors in the code become permanent once
deployed.
165
Web3 Technologies
5.2 DEVELOPMENT FRAMEWORK
5.2.1Ethereum, 2.0:
[Link] Overview:
Ethereum 2.0, also known as Serenity, is a significant upgrade to the
Ethereum blockchain aimed at enhancing its scalability, security, and
sustainability.
[Link].Development of Ethereum:
Ethereum was conceived in 2013 by programmer Vitalik Buterin.[4] Other
founders include Gavin Wood, Charles Hoskinson, Anthony Di Iorio,
and Joseph Lubin.[5] In 2014, development work began and
[6]
was crowdfunded, and the network went live on 30 July 2015. Ethereum
allows anyone to deploy decentralized applications onto it, which anyone
can then use.[7] Decentralized finance (DeFi) applications
provide financial instruments that do not directly rely on financial
intermediaries like brokerages, exchanges, or banks. This facilitates
borrowing against cryptocurrency holdings or lending them out
for interest.[8][9] Ethereum allows users to create fungible (e.g. ERC-20)
and non-fungible tokens (NFTs) with a variety of properties, and to create
smart contracts that can receive, hold, and send those assets in accordance
with the contract's immutable code and a transaction's input data.
Formal development of the software underlying Ethereum began in early
2014 through a Swiss company, Ethereum Switzerland GmbH
(EthSuisse).[23] The idea of putting executable smart contracts in the
blockchain needed to be specified before it could be implemented in
software. This work was done by Gavin Wood, then the chief technology
officer, in the Ethereum Yellow Paper that specified the Ethereum Virtual
Machine.[24][25] Subsequently, a Swiss non-profit foundation,
the Ethereum Foundation (Stiftung Ethereum), was founded.
Development was funded by an online public crowd sale from July to
August 2014, in which participants bought the Ethereum value token
(ether) with another digital currency, bitcoin. While there was early praise
167
Web3 Technologies for the technical innovations of Ethereum, questions were also raised
about its security and scalability.[13]
The Foundation funded multiple teams in different cities building three
separate implementations of the protocol: Geth (Go), Pyethereum
(Python), a C++ implementation, and also Swarm (decentralized file
storage), Mist Browser (A wallet, browser and a user interface for smart
contracts, now defunct) among other projects. The intended purpose of the
three distinct implementations would be so that if one of them had a bug,
the other two could be used as a comparison.
168
Web3, Serenity, Ethereum
Date Event Description
169
Web3 Technologies 3. Phase 1.5: Transition of Ethereum 1.0 to Ethereum 2.0, merging the
current Ethereum (Ethereum 1.0) with Ethereum 2.0 to fully transition
from PoW to PoS.
4. Phase 2: Full state execution: smart contracts on shards, user
accounts, cross-shard transactions.
1. Phase 0:
Launch Date: December 1, 2020
Key Component: Introduction of the Beacon Chain, which
implements the Proof of Stake (PoS) consensus mechanism.
Purpose: Establishes the foundation for PoS and begins the process
of transitioning from Proof of Work (PoW) to PoS.
Functions: Manages validator registration, staking, and the PoS
protocol.
2. Phase 1:
Launch Date: Expected in 2024
Key Component: Introduction of Shard Chains.
Purpose: Improve scalability by splitting the Ethereum network into
multiple smaller chains (shards) that can process transactions and data
in parallel.
Functions: Shard chains will operate alongside the Beacon Chain,
increasing the network’s capacity and efficiency.
3. Phase 1.5:
Launch Date: Integrated with Phase 1
Key Component: Transition of Ethereum 1.0 to Ethereum 2.0.
Purpose: Merge the current Ethereum (Ethereum 1.0) with Ethereum
2.0 to fully transition from PoW to PoS.
Functions: Ethereum 1.0’s mainnet will become a shard chain of
Ethereum 2.0, completing the transition to PoS.
4. Phase 2:
Launch Date: After Phase 1, timeline TBD
Key Component: Full implementation of shard chains and the
Execution Layer.
170
Purpose: Complete the rollout of shard chains, enhance the execution Web3, Serenity, Ethereum
environment with eWASM (Ethereum WebAssembly), and integrate
all components of Ethereum 2.0.
1. Beacon Chain: The core component that manages the Proof of Stake
(PoS) protocol and coordinates the network. It oversees validator
activities, manages consensus, and handles randomness generation.
2. Shard Chains: Shard chains are multiple smaller chains that run in
parallel to improve scalability. Each shard processes its transactions
and smart contracts, increasing overall network capacity and
efficiency.
171
Web3 Technologies
There are several benefits associated with Ethereum 2.0, which is also
known as Serenity.
172
7. Usability: Ethereum 2.0 will be more user-friendly than the older Web3, Serenity, Ethereum
Ethereum network, as it has a simpler user interface.
[Link] Summary:
5.3 SERENITY
Serenity Shield's web3 data storage solution will allow this content to be
uploaded and permanently saved.
173
Web3 Technologies 5.3.2. Importance of Serenity:
Tests are structured into steps, tasks, and actions, making them easier
to maintain and read.
Database checks
174
2. Behavior-Driven Development (BDD): Web3, Serenity, Ethereum
Serenity works well with Rest-Assured for API automation, allowing you
to test REST endpoints as part of a broader test suite.
5. Cross-Browser Testing:
175
Web3 Technologies 2. Step Definitions:
Java methods that implement steps from the feature files.
Annotated with @Given, @When, @Then (from Cucumber).
Call tasks or interactions to perform actions.
5.4 SUMMARY
Web3 Serenity and Ethereum are closely intertwined in the evolution of
decentralized technologies. Ethereum, a foundational blockchain platform,
pioneered smart contracts and decentralized applications (dApps), forming
the backbone of the Web3 ecosystem—a vision of the internet where users
have control over their data, identity, and digital assets. Serenity, also
known as Ethereum 2.0, represents a major upgrade to Ethereum aimed at
improving scalability, security, and energy efficiency through the
transition from a proof-of-work (PoW) to a proof-of-stake (PoS)
176
consensus mechanism. This upgrade is critical for enabling mass adoption Web3, Serenity, Ethereum
of Web3 applications by reducing transaction costs and increasing
throughput. Together, Ethereum and Serenity lay the groundwork for a
more open, user-owned internet, advancing the ideals of decentralization
and trustless interaction.
5.5 QUESTIONS
1. How is web3 different from web2?
2. What is the advantage of web3 over its predecessors?
3. What is serenity?
4. What are the applications of web3 technology in business?
5. What is a DAO?
6. Why Should You Learn about Ethereum and Smart Contracts?
7. How is Ether used in the Ethereum blockchain?
8. What is a smart contract?
9. What are the challenges in dApp development?
10. Explain Generation of Ethereum 2.0.
177
Web3 Technologies b) Bitcoin scrypt is turing-complete while Ethereum's Solidity is
turing-incomplete.
c) Ethereum is more accepted compared to Bitcoin.
d) Ethereum is deflationary while Bitcoin is inflationary.
4. Which statement best describes Ethereum?
a) A Bitcoin clone with programmability.
b) A server company located in the US.
c) A cryptocurrency derived from Bitcoin.
d) A distributed computer with a Native currency.
5. Which characteristic is not applicable distinctively for web3?
a) Decentralization
b) Contextual communication
c) Data Ownership
d) Speed
6. How is web3 different from web2?
a) Web3 was created as the internet for big tech corporations.
b) Web3 emphasizes allowing control and ownership over data.
c) The objectives of web3 focus on introducing interactive content to
the internet.
d) Web3 delivers a better user interface than web2.
7. Which of the following is an example of web3 use cases?
a) Defi protocols
b) Non-fungible tokens
c) Metaverse applications
d) All of the above
8. Which of the following statements provides the best description of
web3?
a) Web3 is process-centric
b) Web3 focuses on users
c) The primary focus of web3 is on applications
178
d) All of the above. Web3, Serenity, Ethereum
5.6 REFERENCE
WEB [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
*****
179
6
HYPERLEDGER & TOKENIZATION
Unit Structure
6.0 Objectives
6.1 Introduction to Hyperledger
6.2 Hyperledger Fabric
6.3 Hyperledger Sawtooth
6.4 Tokenization
6.5 Token Standards
6.6 Trading and finance
6.7 Summary
6.8 Questions
6.9 Reference
6.0 OBJECTIVES
The objective of Hyperledger is to provide a collaborative, open-source
framework for developing enterprise-grade, permissioned blockchain
technologies that support business use cases such as supply chain
management, finance, healthcare, and identity. It is hosted by the Linux
Foundation and aims to create modular, scalable, and secure blockchain
platforms that enable organizations to conduct trusted and transparent
transactions without relying on a central authority. On the other hand,
tokenization refers to the process of converting physical or digital assets
into blockchain-based tokens. The objective of tokenization is to increase
liquidity, transparency, and efficiency in asset management by enabling
fractional ownership, faster settlement, and reduced transaction costs.
Together, Hyperledger and tokenization are transforming how assets are
represented and exchanged in the digital economy, particularly in
regulated enterprise environments.
180
6.1.1 Hyperledger Architecture: Hyperledger & tokenization
1. Consensus Layer:
Creates an agreement on the ordering and confirms the accuracy of
the transaction database that comprises a block.
The communication layer is used by the consensus layer to
communicate with the client and other network peers.
Confirms that all transactions in a proposed block are correct
according to approval and consensus policies.
Interfaces with the smart-contract layer and relies on it to validate the
accuracy of an ordered transaction database in a block.
They're also widely utilized to synchronize data across a decentralized
network and assure transaction consistency and transparency.
3. Communication Layer:
Communication Layer is in charge of peer-to-peer message transfer
between nodes in a shared ledger instance.
The communication layer is used by the consensus layer to
communicate with the client and other network peers.
The algorithm must function exactly like a single node system,
executing each transaction atomically one at a time.
If communication does not fail, then each non-faulty node will finally
get every submitted transaction.
TLS is used for secure communication among nodes in the Fabric.
TLS communication can employ both one-way (server only) and 2
different (server and client) authentication.
182
5. Crypto Abstraction: Hyperledger & tokenization
6. Identity Service:
Allows for the formation of a trusted root during the configuration of
a blockchain instance, the enrolment and registration of identities or
systems entities during network operation, and the administration of
changes such as drops, additions, and revocations. It also offers
authentication and permission.
The smart contract layer employs the identity services layer to
authenticate and approve the entity requesting to execute the smart
contract while processing the transaction.
Hyperledger Fabric provides a personal identity service that handles
user IDs and authenticates all network participants to enable
permissioned networks. Access control lists can be utilized to add
layers of permission by authorizing certain network actions.
Certification Authorities are in charge of managing certificates (or
CA). Fabric CA is Hyperledger's Certification Authority
7. Policy Service:
Policy Services is in charge of policy management for the system's
numerous policies, including the endorsement policy, consensus
policy, and group management policy. It communicates with and is
dependent on another module to enforce the different policies.
183
Web3 Technologies Fabric policies reflect the process through which members agree to
approve or reject changes to the network, a route, or a smart
contract. Policies are agreed upon by channel members when the
channel is first set up, but they can also be changed as the channel
evolves.
Policies are one of the features that distinguish Hyperledger Fabric
from other blockchains such as Ethereum or Bitcoin. Transactions in
those systems can be generated and confirmed by any node in the
network.
8. API:
It enables clients and applications to interface with blockchains. there
are three types of API used in hyperledger they are:
Admin API: This class establishes a management link to a
Hyperledger Composer runtime. The link can then be used to Install
BusinessNetworkDefinitions and deactivate Business network
definitions Refresh BusinessNetworkDefinitions and Ping the
runtime to confirm it is up and running and properly configured In
the connection profile storage, save a connection profile document.
Common API: The Common API comprises the APIs that are used
to access information about the Business Network to which you are
connected as well as to establish new assets, participants,
transactions, and events. It also offers APIs for obtaining
information about these resources.
Runtime API: All transaction functions have access to the Runtime
API. It provides API access to build and issue queries, emit events,
retrieve all forms of registries, get the current participant, and get the
serializer to produce resources from JavaScript objects. - execute
HTTP REST calls.
9. Interoperation:
Allows separate blockchain instances to communicate with one
another.
Interoperability, supported by comprehensive data and transaction
standards, is required to capitalize on this powerful technology. The
food industry, for example, has made tremendous progress in
leveraging data standards to promote food safety and product
visibility use cases.
Interoperability and integration are currently top-of-mind challenges
in the blockchain sector.
184
[Link] Benefits of Hyperledger Architecture: Hyperledger & tokenization
1. Hyperledger Burrow:
Similar to the Ethereum Virtual Machine, Hyperledger Burrow offers
a flexible blockchain client with a permissioned blockchain-based
interpreter. Monax initially contributed and Intel co-sponsored.
Burrow's declared goal is to support the operation of permissioned
networks that are 'open to the public.' With Burrow's permissions
approach, there are numerous shades of grey in terms of network
involvement.
2. Hyperledger Iroha:
Hyperledger Iroha is focusing on mobile application development and
Sumeragi, a revolutionary chain-based Byzantine Fault Tolerant
consensus mechanism. Soramitsu, Hitachi, NTT Data, and Colu are
working on this project.
Hyperledger Iroha is a corporate blockchain platform built for
distributed ledger infrastructure initiatives. The Iroha platform can be
used to create an identity management system, such as national ID
cards.
186
3. Hyperledger Indy: Hyperledger & tokenization
4. Hyperledger Fabric:
Hyperledger Fabric is led by IBM. Hyperledger Fabric is a plug-and-
play blockchain technology implementation with a configurable
degree of permissions. The Linux Foundation manages this private
and confidential blockchain framework.
Hyperledger Fabric is a scalable, flexible architecture-based platform
for distributed ledger applications. It is designed to allow for
pluggable versions of various aspects and to manage the financial
ecosystem's complexities and intricacies.
5. Hyperledger Grid:
The Hyperledger Grid is an ecosystem of technologies, frameworks,
and libraries that collaborate to allow application developers to
choose which components are most suited to their industry or market
model. Cargill is spending resources on the project's development.
The Hyperledger Grid platform is used to create supply chain
solutions that integrate distributed ledger components. It offers an
expanding range of tools that help to expedite the development of
supply chain smart contracts and client interfaces. This is not a
distributed ledger or a client application implementation.
6. Hyperledger Sawtooth:
Hyperledger Sawtooth is a flexible platform for developing,
implementing, and running distributed ledgers, and it features a
revolutionary consensus mechanism known as Proof of Elapsed Time.
This consensus is suitable for large distributed validator groups while
consuming few resources.
Intel is working on this project. Hyperledger Sawtooth is an open-
source industrial blockchain-as-a-service platform that can run
customized smart contracts without requiring knowledge of the core
system's underlying design.
187
Web3 Technologies [Link] Hyperledger Reference Architecture (Protocol Overview):
Identity Services:
Policy Services:
Defines network rules like:
o Access policies
o Consensus rules
o Endorsement policies
Controls who can do what on the network.
Component Description
188
Hyperledger & tokenization
Component Description
189
Web3 Technologies
a. Scalability:
Fabric's modular architecture allows for horizontal scalability, with
multiple peer nodes processing transactions in parallel. It is designed to
support high transaction throughput and scalability. Its architecture allows
for the partitioning of the network into smaller sub-networks called
channels. Each channel can have its own smart contracts and transaction
logic, enabling parallel processing of transactions. This partitioning
capability enhances scalability by allowing different channels to operate
independently and process transactions in parallel.
c. Flexibility:
Fabric's pluggable consensus mechanism and support for various
programming languages offer flexibility in designing and deploying
blockchain applications. It offers pluggable consensus, which means that
190
different consensus algorithms can be used within the same network. This Hyperledger & tokenization
flexibility allows organizations to choose the consensus mechanism that
best suits their requirements, whether it's a practical Byzantine fault-
tolerant (PBFT) consensus algorithm, a crash fault-tolerant (CFT)
consensus algorithm, or even a combination of both. The ability to choose
consensus algorithms enhances network resilience, performance, and
customization options.
d. Security Features:
Fabric incorporates several security features to protect the network and its
data. It utilizes a permissioned network model, where participants must be
authenticated and authorized to access the network. Fabric's endorsement
policy and validation mechanisms ensure that only authorized transactions
are committed to the ledger. It also supports the use of private channels,
where sensitive data can be shared only with specific participants. These
security measures make Hyperledger Fabric suitable for enterprise use
cases that require data confidentiality and integrity.
6.2.4 Summary:
Hyperledger Fabric is a permissioned blockchain platform developed by
IBM and hosted by the Linux Foundation’s Hyperledger project. It is
designed for enterprise use cases that require privacy, scalability, and
modularity.
192
2. Consensus Engine: The state engine manages the agreement on the Hyperledger & tokenization
order and validity of transactions across the network. Sawtooth's
default consensus algorithm, uses a lottery-based approach to select
block leaders in an energy-efficient manner. It supports various
consensus algorithms, including PBFT and Raft, providing flexibility
in how consensus is achieved.
3. Blockchain: The core ledger where all transactions are recorded in a
secure and immutable manner. Blocks contain a list of transactions
and other metadata, such as a previous block hash, to maintain the
chain's integrity. The state represents the current state of the
blockchain, including data and changes made by transactions.
4. Validator: The validator is a node that participates in the network,
validates transactions, and proposes new blocks. It ensures that
transactions are correctly processed and that blocks meet the
consensus criteria. The responsibility of the validator includes
maintaining the blockchain ledger, handling transaction requests, and
enforcing consensus rules.
5. Rest API: The consensus provides a set of HTTP endpoints for
interacting with the Sawtooth network. It allows developers to submit
transactions, query the blockchain state, and interact with the
blockchain network programmatically.
6. Client SDKs: Software development kits provided for various
programming languages to interact with the Sawtooth network. It
includes SDKs for languages such as Python, JavaScript, and Java,
facilitating application development and integration with Sawtooth.
7. Transaction Family: Transaction family defines the rules and logic
for processing specific types of transactions. It includes transaction
processors and state handlers tailored to the needs of the application.
Developers can create custom transaction families to handle
application-specific logic.
8. State Database: State database stores the current state of the
blockchain, reflecting the result of all processed transactions.
Typically uses a database system such as Apache Cassandra or
RocksDB to manage and query state data efficiently.
9. Sawtooth Runtime: It manages the execution of transactions and
maintains the global state. It includes the transaction processor and
state database, coordinating the execution and storage of transactions.
10. Configuration System: The configuration system manages network
configurations and settings, including consensus parameters and
network topology. It allows dynamic updates to network
configurations without requiring a complete system restart.
193
Web3 Technologies 6.3.4 Applications of Hyperledger Sawtooth:
1. Supply Chain Management: Sawtooth can be used to track the
provenance of goods throughout the supply chain, providing visibility
and accountability from production to delivery. It ensures the
authenticity and quality of products by recording each step in the
supply chain, including manufacturing, transportation, and
distribution.
2. Financial Services: The Sawtooth facilitates the management and
transfer of digital assets such as cryptocurrencies or tokenized assets.
It streamlines processes like letters of credit, invoicing, and payment
settlements by providing a transparent and tamper-proof record.
3. Healthcare: The Sawtooth securely stores and manages patient data,
including medical records, consent forms, and treatment history,
ensuring data privacy and accessibility. It tracks pharmaceuticals from
manufacturing to distribution, preventing counterfeit drugs and
ensuring compliance with regulations.
4. Voting Systems: The Sawtooth provides secure and transparent
electronic voting solutions, ensuring the integrity and confidentiality
of ballots.
5. Identity Management: It manages digital identities and credentials
for citizens, enhancing security and reducing fraud in public services.
6. Energy Sector: The Sawtooth supports peer-to-peer energy trading
platforms, enabling secure and efficient transactions of energy credits
and resources. It manages and optimizes energy grid operations,
including monitoring and verification of energy distribution and
consumption.
194
5. Interoperability: Integrating Sawtooth with existing enterprise Hyperledger & tokenization
systems and technologies may require custom adapters and significant
development effort.
195
Web3 Technologies To set up a Hyperledger Sawtooth development environment, you can
follow one of several approaches depending on your preference and
operating system. Sawtooth is modular and designed for enterprise-grade
blockchain applications. Below is a step-by-step guide for setting it up in a
development environment, especially using Docker, which is the
recommended method.
bash
CopyEdit
docker-compose -f [Link] logs -f
6.3.8 summary:
Hyperledger Sawtooth is an enterprise-grade, modular blockchain
platform developed by the Linux Foundation under the Hyperledger
project. It is designed for scalability, flexibility, and separation
197
Web3 Technologies between application and core system logic, making it suitable for
enterprise use cases.
Hyperledger Sawtooth is a versatile blockchain framework offering many
features and benefits, but it also comes with some limitations. Key
challenges include complex setup and management, scalability concerns,
limited consensus options, and difficulties with custom transaction
processor development. Despite these limitations, Sawtooth’s flexibility
and robust architecture make it a powerful choice for various blockchain
applications when these challenges are effectively managed.
6.4 TOKENIZATION
Tokenization in blockchain refers to the process of converting ownership
or rights of an asset into a digital token that resides on a blockchain. This
enables fractional ownership, increased liquidity, and secure transactions,
making it a transformative concept for both individuals and enterprises.
Tokenization on a blockchain refers to the process of converting rights
to an asset into a digital token on a blockchain. This allows physical or
digital assets to be represented, transferred, and traded on decentralized
networks. Here's a breakdown of what it involves:
6.4.1 What Is Tokenization?
Tokenization creates a digital representation of ownership over an asset,
stored as a token on a blockchain. This can include:
Real-world assets: Real estate, art, commodities, gold, vehicles
Financial instruments: Stocks, bonds, derivatives
Intellectual property: Royalties, patents
Digital-native assets: In-game items, loyalty points, NFTs
198
6.4.2 How It Works? Hyperledger & tokenization
199
Web3 Technologies
200
Transparency: Blockchain's immutable ledger ensures trust by Hyperledger & tokenization
providing a clear history of ownership and transactions.
Cost Efficiency: Eliminates intermediaries, reducing transaction costs
and time.
201
Web3 Technologies 3. Special Characters: Handling special characters such as punctuation,
email addresses, and URLs can be tricky. For instance,
"[Link]@[Link]" could be tokenized in multiple ways and
interpretations, complicating text analysis.
1. Utility Tokens
Purpose: Give users access to a product or service on a blockchain
platform.
Not for investment—primarily for use within a system.
202
Examples: Hyperledger & tokenization
2. Security Tokens
Purpose: Represent ownership of real-world assets like stocks, real
estate, or dividends.
Heavily regulated; similar to traditional financial securities.
Examples:
o tZERO – a tokenized stock exchange.
o RealT – tokenized real estate properties.
3. Governance Tokens
Purpose: Allow holders to vote on changes or decisions in a
decentralized protocol.
Key in DAOs (Decentralized Autonomous Organizations).
Examples:
o UNI (Uniswap) – governance over the Uniswap DEX.
o COMP (Compound) – used to vote on lending protocol rules.
4. Stablecoins
Purpose: Maintain a stable value by pegging to assets like fiat
currencies.
Used for payments, trading, and DeFi.
Types:
o Fiat-collateralized: Backed by reserves (e.g., USDC, USDT).
o Crypto-collateralized: Backed by other crypto (e.g., DAI).
o Algorithmic: Stabilized by smart contract algorithms (e.g., failed
UST).
6. Exchange Tokens
Purpose: Native tokens of crypto exchanges, used for trading fee
discounts, staking, etc.
Examples:
o BNB (Binance Coin) – used on Binance ecosystem.
o OKB, KCS (KuCoin Token) – similar use cases.
7. Asset-backed Tokens:
Purpose: Represent ownership of physical assets (gold, real estate,
oil).
Example:
o PAXG (Paxos Gold) – backed by real gold.
1. Asset Identification:
The first step in the tokenization process is to identify the physical or
digital asset that requires protection. This could be payment card
information, personal identifiers such as social security numbers, or any
other sensitive data that needs to be secured.
2. Digital Representation:
After identifying the asset, the next step is to capture its essential
characteristics, such as its value and ownership, and create a digital
counterpart. This digital representation serves as the foundation for the
tokenization process. It involves mapping the key attributes of the asset
into a digital form that can be processed and managed within the
tokenization system. Ensuring accuracy and completeness in this step is
critical, as it directly impacts the integrity and utility of the resulting
token.
204
3. Token Creation: Hyperledger & tokenization
4. Asset Securitization:
To ensure the link between the physical or digital asset and its
corresponding token is secure, various methods are employed. One
common method is the use of smart contracts, which are self-executing
contracts with the terms of the agreement directly written into code.
Smart contracts automate and enforce the rules and conditions under
which the token represents the asset, ensuring that the token accurately
reflects the asset’s value and ownership. Another method is the use of
digital certificates, which serve as electronic documents that verify the
authenticity and ownership of the asset. These certificates can be stored on
the blockchain alongside the token, providing an additional layer of
security and verification. This process of asset securitization creates a
robust and verifiable connection between the original asset and its digital
representation. It ensures that any changes or transfers of ownership are
transparent and traceable, making the tokenization process both secure and
reliable.
5. Token Generation:
A key step in the tokenization process is generating the unique token. This
involves using specialized algorithms or services designed for
tokenization. These algorithms take the original sensitive data and
transform it into a secure and unique token. Techniques used include:
o Encryption: Converts the data into a coded form that can only be
read if decrypted with the correct key, ensuring that the tokenized data
cannot be easily accessed or understood by unauthorized parties.
o Hashing: Creates a fixed-size string of characters from the original
data using a mathematical function. This process is one-way, meaning
the original data cannot be easily retrieved from the hash, adding an
extra layer of security.
205
Web3 Technologies o Format-preserving transformation: Alters the data while
maintaining its original format, which is particularly useful when the
token needs to fit into a specific data structure or format without
changing how the data looks. These techniques collectively help
generate tokens that are not only secure but also retain the necessary
characteristics to be useful in the system or application where they
will be used. This ensures that the tokenized data maintains its
integrity and can be safely utilized without compromising security.
7. Token Replacement:
In the final step, the original sensitive data is replaced with the generated
tokens within the application or system. This ensures that tokens can be
used just like the original data, maintaining the system’s normal
operations without any disruptions. Additionally, processes are put in
place to update or replace tokens when necessary, such as when the
original data needs to be updated or when a token is compromised.
Step-by-step:
1. Normalize text (e.g., lowercase, remove extra spaces).
2. Split on punctuation and spaces.
206
3. Return list of tokens. Hyperledger & tokenization
Summary:
Tokenization is the process of converting ownership rights to a real or
digital asset into a digital token on a blockchain. These tokens can then be
transferred, stored, or traded securely and efficiently.
207
Web3 Technologies 5. Token Generation Event (TGE):
A broader term for any event where tokens are created and
distributed.
Can overlap with ICOs or other offerings.
Component Description
Example:
Imagine a startup launching a decentralized music platform:
They issue 10 million MUSIC tokens.
Sell 5 million in a public ICO for $0.10 each.
Funds are used to build and market the platform.
MUSIC tokens are used on the platform for streaming, rewards, etc.
[Link] Summary: A token offering is a method used by blockchain-
based projects or companies to raise capital by issuing digital tokens.A
token offering is the sale of digital tokens to investors, typically in
exchange for cryptocurrencies (like Bitcoin or Ethereum) or fiat currency.
209
Web3 Technologies Security and Reliability: Token standards include rules for
transaction validation and data integrity, which help prevent fraud and
ensure the security of digital assets.
6.5.4 Summary:
In summary, token standards play a vital role in the blockchain ecosystem
by providing a structured approach to token creation and management,
fostering innovation, and enhancing user experience across various
platforms.
2. 24/7 Markets:
Tokenized assets can trade 24/7, similar to crypto markets, unlike
traditional stock exchanges that have fixed hours.
5. Faster Settlement:
Traditional trading often has a T+2 settlement time.
Tokenized assets can settle almost instantly with fewer
intermediaries.
Carbon
Traded in environmental finance markets
Credits
211
Web3 Technologies 6.6.4 Building an ERC-20 token:
Creating an ERC-20 token is a fundamental step in asset tokenization —
it represents a digital version of a real-world or digital asset that can be
easily traded on Ethereum and other compatible blockchains.
Let’s walk through the process of building an ERC-20 token specifically
for tokenization purposes (e.g., tokenizing real estate, equity, bonds,
etc.).
}
function burn(uint256 amount) external {
_burn([Link], amount);
}
}
[Link] Features:
Admin-controlled minting (for issuing new tokens backed by assets)
Token burning (for redeeming tokens)
OpenZeppelin’s secure and audited code
Platforms to watch:
Ondo Finance, Centrifuge, Maple Finance, BlackRock tokenized
funds (BUIDL)
2. Compliant Security Token Offerings (STOs):
"Tokenized equity, bonds, and investment products."
What it is: Digitally issuing regulated securities on a blockchain (e.g.,
stocks, bonds, funds).
Trends:
Tokenized private equity (e.g., KKR, Hamilton Lane on Avalanche)
STOs becoming more standardized with ERC-1400, Reg D/S
compliance
213
Web3 Technologies Benefits:
Automated dividends
Instant settlement
Global investor access with fractional ownership
Smart contracts
ERC-777, ERC-4626 (for tokenized vaults)
214
Token bound accounts (ERC-6551) for advanced identity + Hyperledger & tokenization
ownership
6.7 SUMMARY
Emerging concepts in tokenization are rapidly transforming how assets are
created, owned, and traded across traditional and decentralized finance.
One of the most significant trends is the tokenization of real-world assets
(RWAs), such as real estate, treasury bills, and private credit, enabling
broader access and liquidity through blockchain. Security Token Offerings
(STOs) are gaining traction as regulated instruments that digitize equities,
bonds, and funds with built-in compliance. Programmable tokens are
introducing automation in financial instruments, allowing self-executing
contracts for dividends, interest, and KYC enforcement. In the
sustainability space, tokenized carbon credits and ESG assets offer
215
Web3 Technologies transparent tracking and verification, while new interoperable standards
aim to enhance cross-chain liquidity and platform compatibility.
Tokenization is also extending into intellectual property and royalties,
enabling fractional ownership and revenue sharing in music, art, and
media. Additionally, AI-generated assets and infrastructure projects are
being tokenized, unlocking new investment models and data economies.
Together, these innovations are pushing tokenization beyond speculative
use cases into practical.
6.8 QUESTIONS
1. What Are the Core Goals of Hyperledger?
2. What Projects Are Listed Among the Hyperledger Umbrella?
3. What Is Hyperledger Sawtooth?
4. Explain the main components of Hyperledger Fabric and their roles.
5. What is a channel in Fabric and why would you use one?
6. How do you query the history of an asset in chaincode?
7. Explain the high-level architecture of Hyperledger Fabric and its main
components.
8. What is the primary purpose of tokenization?
9. How does tokenization work?
10. What are some of the challenges associated with implementing
tokenization?
5. What is Hyperledger?
a) A cryptocurrency like Bitcoin
b) A private company
c) A blockchain platform focused on financial markets.
d) An open-source collaborative blockchainproject hosted by the Linux
Foundation
217
Web3 Technologies 8. What is tokenization in the context of blockchain technology?
a) Breaking a password into smaller parts
b) Converting physical or digital assets into blockchain-based tokens
c) Encrypting a smart contract
d) Creating a cryptocurrency from scratch
6.9 REFERENCE
WEB [Link]
[Link]
/[Link]
[Link]
[Link]
[Link]
*****
218
UNIT 4
SOLIDITY PROGRAMMING
7
INTRODUCTION TO SOLIDITY
PROGRAMMING
Unit Structure
7.0 Objective
7.1 Introduction to Solidity Programming
7.2 Layout of a Solidity Source File
7.3 Structure of a Contract
7.4 Types
7.5 Units, and Globally Available Variables
7.6 Input Parameters and Output Parameters
7.7 Control Structures
7.8 Function Calls
7.9 Creating Contracts via new
7.10 Order of Evaluation of Expressions
7.11 Assignment
7.12 Scoping and Declarations
7.13 Summary
7.14 References
7.15 Question
219
Web3 Technologies Solidity is a statically typed language and supports concepts such as
variables, functions, modifiers, events, inheritance, libraries, and complex
user-defined data types. It is influenced by popular programming
languages like JavaScript, C++, and Python, making it relatively easy to
learn for developers with prior programming experience.
In the Web3 ecosystem, Solidity plays a crucial role by enabling the
development of decentralized applications (DApps) that operate without
centralized control. Solidity smart contracts are compiled into Ethereum
Virtual Machine (EVM) bytecode and deployed on the blockchain, where
they become immutable and transparent.
220
Immutability: Once deployed, smart contracts cannot be altered, Introduction to Solidity
Programming
ensuring transparency and trust.
Example:
// SPDX-License-Identifier: MIT
7.2.2 Pragma Directive:
The pragma directive specifies the compiler version that should be used to
compile the Solidity source file. This ensures compatibility and prevents
unexpected behavior due to version differences.
Example:
Pragma solidity ^0.8.0;
Example:
Import “./[Link]”;
221
Web3 Technologies 7.2.4 Contract Definition:
The contract definition is the core component of a Solidity source file. It
defines the smart contract’s name and contains state variables, functions,
modifiers, and events.
Example:
Contract SimpleStorage{ }
Example:
Uint public value;
7.2.6 Functions:
Functions define the executable logic of the smart contract. They can
modify or read state variables and may include access control and
visibility specifiers.
Example:
Function setValue(uint _value) public {
Value = _value;
}
7.2.7 Modifiers:
Modifiers are used to change the behavior of functions, commonly for
access control and validation checks.
Example:
Modifier onlyOwner() {
Require([Link] == owner);
_;
}
7.2.8 Events:
Events are used to log important actions on the blockchain. They allow
external applications to listen for and respond to contract activities.
222
Example: Introduction to Solidity
Programming
Event ValueUpdated(uintnewValue);
7.2.9 Constructor:
A constructor is a special function that is executed only once during
contract deployment. It is used to initialize state variables.
Example:
Constructor() {
Value = 0;
}
223
Web3 Technologies 7.3.1 Contract Declaration:
The contract declaration defines the contract using the contract keyword
followed by the contract name. It acts as the main container for all
variables and functions.
Example:
Contract BankAccount {
}
Example:
Uint public balance;
Address public owner;
7.3.3 Constructor:
The constructor is a special function executed only once at the time of
contract deployment. It initializes the contract’s state variables.
Example:
Constructor() {
Owner = [Link];
Balance = 0;
}
7.3.4 Functions:
Functions define the behavior and logic of the smart contract. They can
read or modify state variables and may be marked with visibility and
mutability specifiers.
Example:
Function deposit(uint amount) public {
Balance += amount;
}
224
7.3.5 Function Modifiers: Introduction to Solidity
Programming
Modifiers are used to alter function behavior by adding conditions such as
access control or validation.
Example:
Modifier onlyOwner() {
Require([Link] == owner);
_;
}
7.3.6 Events:
Events allow contracts to log important activities on the blockchain. They
help external applications track changes and transactions.
Example:
Event Deposit(address indexed user, uint amount);
Example:
Struct User {
Address userAddress;
Uint balance;
}
EnumAccountStatus{ Active, Closed }
7.3.8 Mappings:
Mappings are key-value data structures used for efficient storage and
retrieval of data.
Example:
Mapping(address =>uint) public balances;
7.3.9 Inheritance:
Solidity supports inheritance, allowing one contract to inherit properties
and functions from another.
225
Web3 Technologies Example:
Contract SavingsAccount is BankAccount {
}
7.4 TYPES
Solidity is a statically typed programming language, which means that the
type of every variable must be explicitly declared before use. Data types in
Solidity define the kind of values that can be stored and the operations that
can be performed on them. Proper use of data types helps in writing
secure, efficient, and reliable smart contracts.
226
Solidity data types are broadly classified into Value Types, Reference Introduction to Solidity
Programming
Types, and Special Types.
a) Boolean:
Used to store true or false values.
Example:
Bool isActive = true;
b) Integer Types:
Used to store whole numbers. Solidity supports signed (int) and unsigned
(uint) integers of various sizes.
Example:
Uint256 count = 100;
c) Address:
Stores Ethereum account or contract addresses and supports transfer of
Ether.
Example:
Address owner;
Example:
Bytes32 hash;
e) Enum:
Defines a user-defined type with a fixed set of named values.
Example:
Enum Status { Pending, Approved, Rejected }
227
Web3 Technologies A) Arrays:
Used to store collections of elements of the same type.
Example:
Uint[] numbers;
b) Structs:
Group related variables under a single name.
Example:
Struct Student {
Uint roll;
String name;
}
c) Mapping:
Stores data in key–value pairs for fast lookup.
Example:
Mapping(address =>uint) balances;
b) Bytes:
Used to store dynamic byte arrays.
Example:
Bytes data;
c) Function Types
Used to store references to functions.
228
Example: Introduction to Solidity
Programming
Function(uint) external returns (uint);
Examples:
Bool → false
Uint → 0
Address → 0x0000000000000000000000000000000000000000
Understanding data types is essential for memory management, gas
optimization, and contract security, making them a fundamental aspect of
Solidity programming.
Example:
Uint amount = 1 ether;
UintgasFee = 10 gwei;
229
Web3 Technologies Common time units:
Seconds
Minutes
Hours
Days
Weeks
Example:
UintlockTime = 7 days;
Example:
Address sender = [Link];
UintvalueSent = [Link];
Example:
UintcurrentBlock = [Link];
230
[Link] – gas price of the transaction Introduction to Solidity
Programming
[Link] – original external account that started the transaction
Example:
UintgasPrice = [Link];
Syntax:
Function functionName(type parameterName) public {
}
Example:
Function setValue(uint _value) public {
Value = _value;
}
231
Web3 Technologies In the above example, _value is an input parameter that receives data from
the function caller.
Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}
Syntax:
Function functionName() public returns (type) {
}
Example:
Function getValue() public view returns (uint) {
Return value;
}
Example:
Function getSum(uint a, uint b) public pure returns (uint result) {
Result = a + b;
}
Example:
Function getDetails() public view returns (uint, address) {
Return (balance, owner);
232
} Introduction to Solidity
Programming
7.6.6 Visibility and Mutability with Parameters:
Functions using input and output parameters often include:
Visibility specifiers: public, private, internal, external
State mutability specifiers: view, pure, payable
Example:
Function deposit() public payable returns (uint) {
Return [Link];
}
a) If Statement:
Syntax:
If (condition) {
// statements
233
Web3 Technologies }
Example:
If (balance > 0) {
Balance = balance – 1;
}
b) If–else Statement:
Syntax:
If (condition) {
// statements
} else {
// statements
}
Example:
If ([Link] == owner) {
Status = true;
} else {
Status = false;
}
a) For Loop
Syntax:
For (initialization; condition; increment) {
// statements
}
Example:
For (uint I = 0; I < 5; i++) {
Count++;
234
} Introduction to Solidity
Programming
b) While Loop:
Syntax:
While (condition) {
// statements
}
Example:
While (balance > 0) {
Balance--;
}
c) Do–while Loop:
Syntax:
Do {
// statements
} while (condition);
Example:
Do {
Balance--;
} while (balance > 0);
Example:
For (uint I = 0; I < 10; i++) {
If (I == 5) {
Break;
}
235
Web3 Technologies }
Example:
Function getBalance() public view returns (uint) {
Return balance;
}
Example:
Require([Link] == owner, “Unauthorized access”);
236
7.8.1 Internal Function Calls: Introduction to Solidity
Programming
Internal function calls occur when a function calls another function within
the same contract or an inherited contract. These calls do not create a new
transaction and are executed within the same execution context.
Example:
Function increment() internal {
Count++;
}
Function update() public {
Increment();
}
Example:
OtherContractoc = OtherContract(contractAddress);
[Link](10);
Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}
Uint result = add(5, 10);
Example:
UintcurrentBalance = getBalance();
237
Web3 Technologies 7.8.5 Payable Function Calls:
Payable function calls allow the transfer of Ether along with the function
call.
Example:
Function deposit() public payable {
}
Deposit{value: 1 ether}();
Example:
(bool success, ) = [Link](
[Link](“setValue(uint256)”, 100)
);
Require(success);
Example:
ChildContract cc = new ChildContract();
Example:
Contract Child {
Uint public value;
Constructor(uint _value) {
Value = _value;
}
}
Contract Parent {
Child public child;
239
Web3 Technologies Function createChild(uint _value) public {
Child = new Child(_value);
}
}
Example:
Address childAddress = address(child);
240
Introduction to Solidity
7.10 ORDER OF EVALUATION OF EXPRESSIONS Programming
Example:
Uint result = 10 + 2 * 5; // result = 20
7.10.2 Associativity:
Associativity determines the direction in which operators of the same
precedence are evaluated.
Left-to-right: +, -, *, /, &&, ||
Right-to-left: assignment operators
Example:
Uint x = 10;
Uint y = x = 5; // x = 5, y = 5
241
Web3 Technologies 7.10.3 Use of Parentheses:
Parentheses can be used to explicitly control the order of evaluation and
improve code clarity.
Example:
Uint result = (10 + 2) * 5; // result = 60
Example:
If (balance > 0 &&[Link] == owner) {
// executed only if both conditions are true
}
Example:
Require(amount > 0 && amount <= balance);
242
Introduction to Solidity
7.11 ASSIGNMENT Programming
Example:
Uint count;
Count = 10;
Example:
Uint total = 50;
Total += 10; // total = 60
Example:
Uint result;
Result = (10 + 5) * 2; // result = 30
243
Web3 Technologies 7.11.4 Multiple Assignment:
Solidity allows assignment of multiple variables at once using tuple
assignment.
Example:
(uint a, uint b) = (5, 10);
Example:
Uint[] storage dataRef = data;
Uint[] memory dataCopy = data;
Example:
Require(amount > 0);
Balance = amount;
244
Introduction to Solidity
7.12 SCOPING AND DECLARATIONS Programming
Example:
Uint public count;
Address private owner;
Example:
Contract Example {
Uint public value;
Function setValue(uint _v) public {
Value = _v;
}
}
Example:
Function calculate(uint a, uint b) public pure returns (uint) {
Uint result = a + b;
245
Web3 Technologies Return result;
}
Example:
Function test() public pure returns (uint) {
Uint sum = 0;
For (uint I = 0; I < 5; i++) {
Sum += I;
}
Return sum;
}
Example:
Function getValue() public view returns (uint) {
Return value;
}
Example:
Uint public data;
246
Function update() public { Introduction to Solidity
Programming
Uint data = 10; // shadows state variable
}
Example:
Uint constant MAX = 100;
Address immutable owner;
7.13 SUMMARY
In this unit, the fundamentals of Solidity programming were discussed as a
core component of Web3 Technologies. The chapter began with an
introduction to Solidity and its role in developing smart contracts for the
Ethereum blockchain. The layout of a Solidity source file and the internal
structure of a contract were explained to provide a clear understanding of
how smart contracts are organized.
The unit covered various data types, built-in units, and globally available
variables, which enable precise handling of Ether, time, and blockchain-
specific information. Concepts related to input and output parameters,
control structures, and function calls were discussed to illustrate how
smart contract logic is implemented and executed.
The creation of contracts using the new keyword highlighted dynamic
contract deployment, while the order of evaluation of expressions,
assignment, and scoping and declarations emphasized correct program
execution and variable management. Overall, this unit provides a strong
foundation in Solidity programming, enabling learners to design, develop,
247
Web3 Technologies and deploy secure, efficient, and reliable smart contracts for decentralized
applications.
7.14 REFERENCES
1. Modi, Ritesh. Solidity Programming Essentials: A Beginner’s Guide
to Build Smart Contracts for Ethereum and Blockchain. Packt
Publishing, Birmingham, UK, 2018.
2. Antonopoulos, Andreas M., and Gavin Wood. Mastering Ethereum:
Building Smart Contracts and DApps. O’Reilly Media, 2018.
3. Dannen, Chris. Introducing Ethereum and Solidity: Foundations of
Cryptocurrency and Blockchain Programming for Beginners. Apress,
2017.
4. Ethereum Foundation. Solidity Documentation. Official Ethereum
Project Documentation.
5. Narayanan, Arvind, et al. Bitcoin and Cryptocurrency Technologies.
Princeton University Press, 2016.
7.15 QUESTION
Long Answer Questions
1. Explain the layout of a Solidity source file with a suitable example.
2. Describe the structure of a Solidity smart contract in detail.
3. Explain the different data types supported by Solidity with
examples.
4. Discuss Ether units, time units, and globally available variables in
Solidity.
5. Explain input and output parameters in Solidity functions with
examples.
6. Describe various control structures used in Solidity.
7. Explain different types of function calls in Solidity.
8. Discuss how new contracts are created using the new keyword.
9. Explain the order of evaluation of expressions in Solidity.
10. Explain assignment, scoping, and declarations in Solidity with
examples.
*****
249
8
ERROR HANDLING AND SMART
CONTRACTS
Unit Structure
8.0 Objective
8.1 Basic of error Handling
8.2 Assert
8.3 Require
8.4 Revert and Exceptions
8.5 Introduction to Smart Contracts
8.6 Solidity Programming –Contracts
8.7 Creating Contracts
8.8 Visibility And Getters
8.9 Function Modifiers
8.10 Constant State Variables
8.11 Functions
8.12 Abstract Contracts
8.13 Interfaces
8.14 Libraries
8.15 Summary
8.16 Reference
8.16 Question
Unauthorized access
Example:
Require([Link] == owner, “Not authorized”);
b) Assert():
251
Web3 Technologies Example:
Assert(balance >= 0);
c) Revert():
Explicitly stops execution and reverts state changes
Can include an error message
Example:
Revert(“Transaction failed”);
Example:
Error InsufficientBalance(uint requested, uint available);
252
Error handling and Smart
8.2 ASSERT Contracts
Unlike require, assert is not used for input validation or user errors.
Example:
Assert(totalSupply>= balances[[Link]]);
253
Web3 Technologies Example:
Function decrement(uint value) public {
Total -= value;
Assert(total >= 0);
}
8.3 REQUIRE
The require statement in Solidity is the most commonly used error-
handling mechanism. It is primarily used to validate conditions, check user
inputs, and enforce access control. If a require condition fails, the
execution of the contract is stopped and all state changes are reverted.
254
8.3.1 Purpose of require: Error handling and Smart
Contracts
The main purposes of require are to:
Example:
Require([Link] == owner, “Unauthorized access”);
b) Access Control:
Require([Link] == owner, “Only owner can call this function”);
c) State Validation:
Require(balance >= amount, “Insufficient balance”);
255
Web3 Technologies 8.3.5 require vs assert:
Aspect require assert
Purpose Input & condition validation Internal error checking
Error type Recoverable Critical
Gas refund Yes No
Usage User-related conditions Invariants
256
An arithmetic error occurs (e.g., division by zero) Error handling and Smart
Contracts
Syntax:
Revert();
Revert(“Error message”);
Example:
If (balance < amount) {
Revert(“Insufficient balance”);
}
257
Web3 Technologies 8.4.5 Exceptions from External Calls:
External contract calls may fail and cause exceptions. Solidity provides
mechanisms to detect and handle such failures.
Example:
(bool success, ) = address(contract).call(data);
Require(success, “External call failed”);
Unauthorized access
Insufficient balance
Logical errors
Enhances security
Faster execution
Elimination of intermediaries
259
Web3 Technologies 8.5.6 Applications of Smart Contracts:
Smart contracts are widely used in:
Contract declaration
State variables
Constructor
Functions
Modifiers
Events
260
Example: Error handling and Smart
Contracts
Pragma solidity ^0.8.0;
Contract SimpleContract {
Uint public value;
Address public owner;
Constructor() {
Owner = [Link];
}
Function setValue(uint _value) public {
Value = _value;
}
}
261
Web3 Technologies 8.6.6 Visibility and Access Control:
Solidity contracts support access control using:
Example:
Pragma solidity ^0.8.0;
Contract Sample {
Uint public value;
Function setValue(uint _value) public {
Value = _value;
}
}
262
8.7.2 Compiling the Contract: Error handling and Smart
Contracts
The Solidity source code is compiled using a Solidity compiler (solc). The
compiler converts the code into Ethereum Virtual Machine (EVM)
bytecode.
Remix IDE
Truffle
Hardhat
Example:
Constructor(uint _value) {
Value = _value;
}
Example:
[Link](10);
Automation of agreements
a) Public:
Example:
Uint public count;
b) Private:
Example:
Uint private secret;
264
c) Internal: Error handling and Smart
Contracts
Accessible within the contract and derived contracts
Example:
Uint internal data;
d) External:
Example:
Function update(uint _value) external {
Value = _value;
}
Example:
Function getValue() public view returns (uint) {
Return value;
}
Example:
Mapping(address =>uint) private balances;
Function getBalance(address user) public view returns (uint) {
Return balances[user];
}
266
8.9.2 Syntax of a Function Modifier: Error handling and Smart
Contracts
A modifier is defined using the modifier keyword. The placeholder
symbol _ represents the location where the function body is executed.
Syntax:
Modifier modifierName() {
// condition
_;
}
Example:
Function withdraw(uint amount) public onlyOwnervalidAmount(amount)
{
Balance -= amount;
}
267
Web3 Technologies 8.9.5 Modifier without _:
A modifier can prevent function execution by not including _.
Example:
Modifier stopExecution() {
Revert(“Function execution stopped”);
}
Ownership validation
Input validation
Improves security
Example:
Uint public constant MAX_LIMIT = 100;
Address public constant ZERO_ADDRESS = address(0);
Version identifiers
Mathematical constants
Example:
Uint constant FEE_PERCENT = 5;
Enhances security
8.11 FUNCTIONS
Functions in Solidity define the behavior and logic of a smart contract.
They are used to perform operations such as modifying state variables,
returning data, transferring Ether, and interacting with other contracts.
Functions are the primary means through which users and other contracts
interact with a smart contract.
Syntax:
Function functionName(parameters) visibility mutability returns
(returnType) {
// function body
}
270
8.11.2 Function Visibility: Error handling and Smart
Contracts
Functions can have the following visibility specifiers:
Example:
Function getValue() public view returns (uint) {
Return value;
}
Example:
Function deposit() public payable {
}
Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}
271
Web3 Technologies Example:
Constructor() {
Owner = [Link];
}
Example:
Receive() external payable {}
Fallback() external payable {}
Example:
Function set(uint a) public {}
Function set(uint a, uint b) public {}
272
used to define common structure, rules, and behavior that must be Error handling and Smart
Contracts
implemented by derived contracts.
Example:
Abstract contract Shape {
Function area() public view virtual returns (uint);
}
Example:
Contract Rectangle is Shape {
Uint length;
Uint width;
Function area() public view override returns (uint) {
Return length * width;
}
}
273
Web3 Technologies Override is used when implementing or redefining a virtual function
Support inheritance
Code reusability
274
Error handling and Smart
8.13 INTERFACES Contracts
Syntax:
Interface InterfaceName {
Function functionName(parameters) external returns (type);
}
Example:
Interface IToken {
Function transfer(address to, uint amount) external returns (bool);
}
Example:
Contract Token is IToken {
275
Web3 Technologies Function transfer(address to, uint amount) external override returns
(bool) {
Return true;
}
}
Example:
IToken token = IToken(tokenAddress);
[Link]([Link], 100);
Contract-to-contract communication
Interoperability
Standardization
Reusability
276
In conclusion, interfaces are essential for building scalable, standardized, Error handling and Smart
Contracts
and interoperable smart contracts, making them a key feature of Solidity
programming in Web3 Technologies.
8.14 LIBRARIES
In Solidity, libraries are special types of contracts that contain reusable
code. They are used to implement common functions that can be shared
across multiple contracts, helping to reduce code duplication and improve
maintainability. Libraries are especially useful for writing utility functions
and safe operations.
Syntax:
Library LibraryName {
Function functionName(uint a, uint b) internal pure returns (uint) {
Return a + b;
}
}
Example:
Library MathLib {
Function add(uint a, uint b) internal pure returns (uint) {
Return a + b;
}
}
Example:
Using MathLib for uint;
277
Web3 Technologies Uint result = [Link](20);
Cannot be destroyed
Improve security
278
In conclusion, libraries provide a powerful mechanism for reusable and Error handling and Smart
Contracts
secure code, making them an essential feature of Solidity programming in
Web3 Technologies.
8.15 SUMMARY
This unit focused on error handling and smart contract development in
Solidity, which are critical aspects of building secure and reliable Web3
applications. The concepts of error handling using assert, require, and
revert were discussed to ensure safe execution and prevention of invalid
state changes.
The unit also introduced smart contracts, explaining their role,
characteristics, and importance in decentralized systems. Solidity
contracts, their creation process, visibility rules, getters, function
modifiers, constant state variables, and functions were explained to
provide a complete understanding of contract development.
Advanced concepts such as abstract contracts, interfaces, and libraries
were covered to demonstrate modularity, reusability, and standardization
in Solidity programming. Overall, this unit equips learners with the
knowledge required to design secure, maintainable, and scalable smart
contracts for Web3 Technologies.
8.16 REFERENCES
1. Modi, Ritesh. Solidity Programming Essentials: A Beginner’s Guide
to Build Smart Contracts for Ethereum and Blockchain. Packt
Publishing, 2018.
2. Antonopoulos, Andreas M., and Gavin Wood. Mastering Ethereum.
O’Reilly Media, 2018.
3. Dannen, Chris. Introducing Ethereum and Solidity. Apress, 2017.
4. Ethereum Foundation. Solidity Documentation. Official Ethereum
Documentation.
5. Buterin, Vitalik. Ethereum White Paper.
8.17 QUESTIONS
A. Long Answer Questions
1. Explain error handling in Solidity with assert, require, and revert.
2. Describe the concept and working of smart contracts.
3. Explain the structure of a Solidity contract.
4. Discuss visibility specifiers and getters in Solidity.
279
Web3 Technologies 5. Explain the role of function modifiers with examples.
6. What are constant state variables? Explain their advantages.
7. Explain different types of functions in Solidity.
8. Describe abstract contracts and their use cases.
9. Explain interfaces and their role in contract interoperability.
10. Discuss the importance and use of libraries in Solidity.
*****
280
While the immutability of blockchain is crucial for security and trust, it poses potential drawbacks, such as the difficulty in correcting errors once data is recorded. Mistaken transactions or data entries cannot be easily reversed. Potential mitigation strategies include implementing governance frameworks that allow for corrective measures via consensus or designing blockchain systems with layers or smart contracts that enable specific reversibility under predefined conditions. These approaches can allow a balance between immutability and necessary flexibility .
Smart contracts are self-executing programs stored on a blockchain that automatically enforce and execute the terms of an agreement when specified conditions are met. They offer significant advantages, such as reducing transaction costs, eliminating intermediaries, faster execution, and providing increased trust and reliability. However, they also present limitations, including difficulties with immutability that make error correction challenging, dependency on data from external oracles, scalability issues, and potential legal and regulatory challenges .
Interoperability solutions like Polkadot and Cosmos are crucial in the blockchain ecosystem as they address the challenge of limited communication and data sharing between different blockchain platforms. These systems enable various blockchains to interconnect, share data, and enhance their capabilities by working together, which facilitates more robust application functionality and wider adoption of blockchain technology. This interoperability helps in building comprehensive networks that can operate efficiently across different blockchain standards, promoting a cohesive ecosystem .
Blockchain systems face significant scalability challenges compared to traditional systems such as Visa, which can handle approximately 24,000 transactions per second (TPS). In contrast, a network like Bitcoin processes only about 7 TPS due to the decentralized consensus-based verification process, which is inherently slower. This limitation is compounded by issues like block size and time between blocks, requiring innovative solutions like sharding or layer 2 protocols to enhance throughput while preserving decentralization and security .
Blockchain addresses trust and decentralization issues through its core principles of decentralization, immutability, transparency, and security. By distributing a ledger across multiple nodes, there is no central authority that can alter data without consensus, which enhances trust. Each transaction is visible and can be audited by participants, ensuring transparency. Additionally, cryptographic methods provide security that maintains data integrity and user privacy .
Public blockchains are open to everyone, decentralized, and allow anyone to participate in the network without permissions, which makes them ideal for applications like cryptocurrencies (e.g., Bitcoin, Ethereum). Conversely, private blockchains are permissioned, controlled by a single organization, restricting access and modifying capabilities to enhance privacy and control, thus making them suitable for businesses needing internal or consortium-based data sharing (e.g., Hyperledger Fabric).
Ethereum's transition from Proof-of-Work (PoW) to Proof-of-Stake (PoS) is expected to bring several benefits to its network operations. PoS is more energy-efficient as it eliminates the need for intensive computational power required in PoW. It also scales better by allowing faster and cheaper transaction processing, and reduces the hardware requirements for validators. This transition is aimed at enhancing Ethereum's scalability, sustainability, and overall network efficiency while maintaining security and decentralization .
The concept of 'trustlessness' in blockchain refers to the system's ability to conduct transactions and verifications without relying on a trusted intermediary or third-party authority. This transformation of traditional transaction systems is achieved by using cryptography and consensus protocols that ensure data integrity, authenticity, and security, allowing participants to interact directly. It reduces dependency on centralized institutions, thereby minimizing costs and potential errors or corruption prevalent in traditional systems. This decentralized trust model enhances transparency and efficiency in transaction systems .
Layer-2 solutions in Ethereum, including State Channels, Plasma, and Rollups, are designed to improve Ethereum's functionality by increasing transaction throughput and reducing gas fees. These solutions operate on top of the main Ethereum blockchain, handling transactions off-chain and settling on-chain only when necessary. This separation allows for more efficient and cost-effective operations without compromising on the blockchain's security, decentralization, and integrity. Layer-2 solutions are essential for scaling Ethereum to handle a larger volume of transactions without congestion .
Consensus mechanisms in blockchain networks are pivotal to maintaining a consistent and secure ledger among distributed nodes. They ensure that all participating nodes agree on a single version of the truth, despite potential faults or malicious actors. Mechanisms like Proof of Work (PoW) and Proof of Stake (PoS) provide network security by making it challenging for any single entity to alter past transactions without significant computational effort or stake, therefore discouraging malicious activities. This process of collective verification and decision-making secures the blockchain against attacks like double spending and ensures data integrity .