0% found this document useful (0 votes)
37 views286 pages

PDF Web3 Technologies

The document outlines the revised syllabus for the M.Sc. Computer Science program at the University of Mumbai, focusing on Web3 Technologies. It covers key topics such as blockchain, Bitcoin, smart contracts, Ethereum, and Solidity programming, with practical applications and assessments detailed. The course aims to equip students with foundational knowledge and skills in decentralized technologies and their applications in various domains.

Uploaded by

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

PDF Web3 Technologies

The document outlines the revised syllabus for the M.Sc. Computer Science program at the University of Mumbai, focusing on Web3 Technologies. It covers key topics such as blockchain, Bitcoin, smart contracts, Ethereum, and Solidity programming, with practical applications and assessments detailed. The course aims to equip students with foundational knowledge and skills in decentralized technologies and their applications in various domains.

Uploaded by

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

MSCCS 3.

[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.

Programe Co-ordinator : Shri. Mandar Bhanushe


Head, Faculty of Science and Technology
CDOE, University of Mumbai, Mumbai.
Course Co-ordinator : Mr. Raju Ramchandra Mane
Asst. Professor Computer Science
CDOE, University of Mumbai.
Course Editor : Mr. Raju Ramchandra Mane
Asst. Professor Computer Science,
CDOE, University of Mumbai.

Course Writer : Prachi Abhijeet Surve


Assistant Professor, Computer Science
Navinchandra Mehta Institute Of Technology
And Development College St, Chandrakant, Dhuru Wadi,
Dadar West, Dadar, Mumbai.
: Archana Rohit Mishra
Assistant Professor, Computer Science
Satish Pradhan Dnyanasadhana College Dnyanasadhana Marg,
off Eastern Express Highway, Dharamveer Nagar, Thane.
: Raju Ramchandra Mane
Assistant Professor, Computer Science
CDOE, University of Mumbai, Dr. Shankar Dayal Sharma
Bhavan, Vidyanagari, Kalina, Santacruz (E), Mumbai.

January 2026, Print I,


ipin Enterprises
Published by
Tantia Jogani Industrial Estate, Unit No. 2,
Director
Ground Floor, Sitaram Mill Compound,
Centre for Distance and Online Education, University of Mumbai,Vidyanagari,
J.R. Boricha
Mumbai - 400Marg,
098. Mumbai - 400 011

DTP COMPOSED AND PRINTED BY


Mumbai University Press,
Vidyanagari, Santacruz (E), Mumbai - 400098.
CONTENTS
Unit No. Title Page No

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

Programme Name: [Link]. Computer


Course Name: Web3 Technologies
Science Semester III
Total Credits: 04 Total Marks: 100
College assessment: 50 University assessment: 50

Prerequisite: Fundamental knowledge of mathematics, blockchain technologies.

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

Prerequisite: Knowledge of Solidity, NodeJS


Course Outcome:
The learner will be able to
 Implement the concept of the docker with respect to BlockChain
Applications
 Implement smart contracts and Ethereum development environment.
 Implement the concept of Ethereum framework, serenity and Tokenization
 Apply Solidity programming for Smart contracts and tokenization.

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 :

 The objective is to provide a foundational understanding of


blockchain technology within the context of Web3.
1
Web3 Technologies  This includes exploring the growth of blockchain, its roots in
distributed systems, the history of Bitcoin, core blockchain concepts,
consensus mechanisms, the CAP theorem’s relevance,
decentralization methods, and the classification of blockchain
algorithms.

 The chapter builds knowledge essential for understanding the


decentralized Web3 ecosystem.

 This chapter serves as an introduction to blockchain technology, its


technical foundations, the theory behind it, and various techniques
that have been combined together to build what is known today as
blockchain.

 In this chapter, we first describe the theoretical foundations of


distributed systems.

 Next, we address the precursors of Bitcoin by which blockchain


technology was introduced to the world.

 Finally, we introduce you to blockchain technology.

 This approach is a logical way to understand blockchain technology,


as the roots of blockchain are in distributed systems.

 To provide a foundational understanding of blockchain technology in


the context of Web3.

 To explain the growth and evolution of blockchain, its origins in


distributed systems, and the history of Bitcoin.

 To introduce core blockchain concepts, architecture, and key


components.

 To explore consensus mechanisms, their design considerations,


classifications, and algorithms.

 To understand related theoretical principles like the CAP theorem and


decentralization models.

 To examine real-world blockchain applications and future directions.

1.1 GROWTH OF BLOCKCHAIN TECHNOLOGY


Introduction:
Blockchain is a distributed ledger technology that allows secure,
transparent, and tamper-proof recording of transactions across a
decentralized network. Initially popularized by Bitcoin in 2008,
blockchain has since expanded to diverse applications including finance,
supply chain, healthcare, voting systems, and more. At its core, blockchain

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.

How has blockchain technology grown since its inception?

 Blockchain technology has evolved from a niche cryptographic


concept into a disruptive force across multiple industries.

 Initially introduced through Bitcoin as a decentralized ledger for


digital currency, blockchain now supports smart contracts,
decentralized finance (DeFi), non-fungible tokens (NFTs), supply
chain traceability, and more.

 The rise of Ethereum in 2015 marked a shift towards programmable


blockchains, expanding use cases beyond payments.

 Today, blockchain innovation continues in scalability, privacy,


interoperability, and governance.

What factors contributed to the widespread adoption of blockchain?

 Key factors include trustlessness, transparency, immutability,


decentralization, and the ability to reduce reliance on intermediaries.

 Moreover, the open-source nature of many blockchain projects


fostered a global developer community, accelerating innovation.

 Economic incentives through tokens and the growing need for secure
digital asset management also fueled adoption.

1.1.1 Distributed systems:


What is a distributed system, and why is it important for blockchain?

 A distributed system consists of multiple independent computers


(nodes) that cooperate to provide a unified service.

 Key properties include no single point of failure, scalability, and fault


tolerance.

 Blockchain is a type of distributed system where nodes collectively


maintain a ledger without centralized control, enabling trustless and
secure transaction recording.
What are the main challenges in distributed systems that blockchain
aims to solve?

 Challenges include achieving consensus despite unreliable


communication, node failures, and malicious actors (Byzantine
faults).
3
Web3 Technologies  Blockchain uses cryptographic techniques and consensus algorithms
to ensure all honest nodes agree on a consistent ledger state,
overcoming these problems.

1.1.2 The History of Blockchain and Bitcoin:

 The history of blockchain and Bitcoin is a blend of cryptographic


innovation, economic theory, and social movements against
centralization.

 From obscure roots in the 1990s to global relevance in the 2020s,


blockchain has evolved into a foundational technology with
applications across finance, governance, and digital identity.

 Understanding its origins and evolution is essential for computer


scientists exploring decentralized systems and the future of secure
digital infrastructure.

Origins of Blockchain Technology:

 Early Cryptographic Foundations (1970s–1990s)

 The concept of blockchain is rooted in cryptographic research dating


back to the 1970s and 1980s.

 Public-key cryptography (Whitfield Diffie and Martin Hellman, 1976)


laid the groundwork for secure communication without a shared
secret.

 In 1991, Stuart Haber and W. Scott Stornetta introduced a method for


time-stamping digital documents using cryptographic hashing and
linked data blocks the conceptual prototype of blockchain.

 In 1992, they added Merkle trees to improve efficiency and store


multiple documents in a single block.

The Cypherpunk Movement:

 A group of privacy-focused technologists called cypherpunks (1990s)


sought to use cryptography to create digital privacy tools.

 Key figures included Timothy C. May, Eric Hughes, and Nick Szabo.

 Szabo proposed “Bit Gold” (late 1990s), a precursor to Bitcoin.

 It introduced ideas such as decentralized digital money, proof of work


(PoW), and immutable ledgers.

4
Emergence of Bitcoin: Blockchain

The Financial Crisis and Motivation

 The 2008 global financial crisis eroded trust in centralized banking


institutions.

 This environment of distrust provided fertile ground for decentralized


financial systems.

Satoshi Nakamoto and the Bitcoin White Paper:

 In October 2008, an anonymous individual or group under the name


Satoshi Nakamoto published the white paper:

 Title: Bitcoin: A Peer-to-Peer Electronic Cash System

 Described a decentralized system for transferring value without a


trusted third party.

 Introduced a consensus mechanism (Proof of Work) to achieve trust


in a distributed environment.

Bitcoin Genesis Block (2009):

 January 3, 2009: The Genesis Block (Block 0) of the Bitcoin


blockchain was mined.

 Embedded message: “The Times 03/Jan/2009 Chancellor on brink of


second bailout for banks” — a political statement and timestamp.

 The first Bitcoin transaction (Block 170) occurred on January 12,


2009, between Satoshi Nakamoto and Hal Finney.

Technical Architecture of Bitcoin:


Key Concepts

 Blockchain: A distributed, append-only ledger of transactions.

 Block: A set of validated transactions; each block contains:

 A reference to the previous block (hash)

 A nonce (used for PoW)

 Merkle root of transactions

 Proof of Work: A consensus algorithm requiring computational effort


to add new blocks. Prevents double-spending.

 Mining: Process of solving PoW to validate transactions and add new


blocks.
5
Web3 Technologies  Reward: Miners receive newly minted Bitcoins + transaction fees.

Supply and Halving:

 Bitcoin has a fixed supply of 21 million coins.

 Block rewards halve approximately every 4 years (every 210,000


blocks).

 Example:

 2009: 50 BTC per block

 2012: 25 BTC

 2016: 12.5 BTC

 2020: 6.25 BTC

 2024: 3.125 BTC

Development and Growth:


Early Adoption

 In 2010, the first recorded commercial transaction was 10,000 BTC


for two pizzas — now celebrated as Bitcoin Pizza Day.

 Developers and cryptography enthusiasts began running nodes,


mining, and contributing to the open-source codebase.

Emergence of Exchanges:

 2010: The first Bitcoin exchange, Mt. Gox, was launched.

 2011–2013: Bitcoin began attracting more attention as it crossed $1,


then $100 per BTC.

Security Incidents:

 Mt. Gox Hack (2014): Lost ~850,000 BTC, shaking public


confidence.

 Prompted focus on secure wallets and decentralized exchanges.

Evolution of Blockchain Beyond Bitcoin:


Altcoins and Forks

 Bitcoin inspired the creation of alternative cryptocurrencies (e.g.,


Litecoin, Peercoin).

 Forks like Bitcoin Cash (2017) attempted to scale by increasing block


size.
6
Ethereum (2015): Blockchain

 Proposed by Vitalik Buterin, Ethereum expanded blockchain use


beyond currency to decentralized applications (dApps).

 Introduced smart contracts: self-executing code on the blockchain.


Institutional Interest and Regulation:
 2017: Bitcoin reached ~$20,000 — gaining mainstream attention.
 Regulators worldwide began addressing cryptocurrency legality,
taxation, and compliance.
 2020 onwards: Large companies (e.g., Tesla, PayPal) began accepting
or holding Bitcoin.
Recent Developments and Outlook:
Bitcoin as “Digital Gold”
 Increasingly seen as a store of value rather than a transactional
currency.
 Adopted by institutions and even El Salvador (2021) as legal tender.
Layer 2 Solutions:
 Scalability issues prompted development of Layer 2 protocols like the
Lightning Network for faster, cheaper transactions.
Blockchain Applications Today:
 Supply chain tracking
 Decentralized finance (DeFi)
 Non-fungible tokens (NFTs)
 Enterprise blockchains (e.g., Hyperledger, Quorum)
Who invented blockchain technology, and what was the original
purpose?
 While foundational cryptographic research existed earlier, blockchain
as we know it was popularized by Satoshi Nakamoto in 2008 with the
Bitcoin whitepaper.
 Its original purpose was to create a decentralized peer-to-peer digital
cash system solving the double-spending problem without a central
authority.

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:

 Blockchain is a distributed ledger technology (DLT) that enables the


secure, transparent, and tamper-proof recording of digital transactions
across a decentralized network of computers.

 Originally developed as the underlying technology for Bitcoin,


blockchain has evolved into a general-purpose technology with
applications in finance, healthcare, supply chain, identity verification,
and more.

 Blockchain technology represents a major shift in how data is stored,


verified, and shared.

 While it faces challenges in scalability and adoption, it has the


potential to disrupt industries by increasing trust, reducing costs, and
enabling decentralization.

 Understanding blockchain offers key insights into distributed systems,


cryptography, and the future of secure computing.
Definition:

 A blockchain is a growing list of records (blocks), linked using


cryptographic hashes, stored in a decentralized network, and
maintained through consensus mechanisms.

Key Concepts:

 Decentralized: No central authority controls the network.

 Immutable: Once recorded, data cannot be altered without


consensus.

 Transparent: All participants can verify and audit transactions.

 Secure: Cryptographic methods ensure data integrity and user


privacy.

Core Features of Blockchain:

 Distributed Ledger: Every participant (node) has a synchronized


copy of the entire ledger.
8
 Immutability: Once data is recorded in a block and confirmed, it Blockchain
cannot be changed.

 Transparency: All transactions are visible to participants in the


network.

 Consensus Mechanisms: Nodes agree on a single version of truth


(e.g., Proof of Work, Proof of Stake).

 Cryptographic Security: Transactions are secured using digital


signatures and hash functions.

 Smart Contracts: Self-executing code that automates processes when


conditions are met.

 Pseudonymity:Users are identified by cryptographic addresses, not


personal info.

Types of Blockchain:

Type Description Example

Public Open to everyone, decentralized, Bitcoin,


Blockchain anyone can participate Ethereum

Private Permissioned, controlled by a single Hyperledger


Blockchain organization. Fabric

Consortium Semi-decentralized, governed by a R3 Corda,


Blockchain group of organizations. Quorum

Hybrid Combines features of public and IBM Food


Blockchain private blockchains. Trust

Advantages of Blockchain:

 Decentralization: Removes the need for intermediaries or central


authorities.

 Transparency: Transactions are visible and auditable by all


participants.

 Security: Strong cryptographic techniques protect data from


tampering and fraud.

 Efficiency and Speed: Reduces paperwork and automates processes


via smart contracts.

 Reduced Costs: Eliminates intermediaries and reduces operational


overhead.

9
Web3 Technologies  Data Integrity: Every change is traceable and recorded in the ledger.

 Fault Tolerance: The network is resilient against node failures or


attacks.

Disadvantages of Blockchain

 Scalability Issues: Processing time is slow (e.g., Bitcoin handles ~7


TPS vs Visa’s ~24,000 TPS).

 Energy Consumption: Consensus mechanisms like PoW consume a


large amount of electricity.

 Complexity: Implementation and integration require technical


expertise.

 Regulatory Uncertainty: Legal frameworks for blockchain vary


widely across countries.

 Immutability Drawback: Data recorded in error cannot be easily


corrected.

 Privacy Concerns: Public blockchains may expose transaction


history to all users.

 Limited Interoperability: Different blockchain platforms often don’t


communicate with each other.

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:

 Cryptographic hash functions (e.g., SHA-256) convert input data into


fixed-length outputs.

 Any slight change in input yields a completely different hash —


essential for data integrity.

10
Consensus Algorithms: Blockchain

Algorithm Description

Proof of Work (PoW) Solves complex puzzles to validate blocks. Secure


but energy-intensive.

Proof of Stake (PoS) Proof of Stake (PoS) Validators are chosen based
on their stake in the network. More efficient.

Proof of Work (PoW) Delegated PoS Stakeholders vote to elect block


producers.

Practical Byzantine Achieves consensus despite malicious actors.


Fault Tolerance Used in private chains.
(PBFT)

Applications of Blockchain:

 Cryptocurrencies: Bitcoin, Ethereum — enable peer-to-peer digital


money.

 Supply Chain Management: Real-time tracking of goods,


verification of authenticity.

 Healthcare: Secure storage and sharing of medical records.

 Voting Systems: Transparent, tamper-proof electoral processes.

 Finance (DeFi): Decentralized lending, insurance, and exchanges.

 Digital Identity: Users control their own identity with secure,


verifiable credentials.

 Smart Contracts: Automated execution of contractual terms.

Future Directions of Blockchain:

 Interoperability Solutions (e.g., Polkadot, Cosmos)

 Green Blockchain with eco-friendly consensus models

 Blockchain-as-a-Service (BaaS) platforms by IBM, Microsoft, AWS

 Integration with AI and IoT

 Regulatory Clarity and Legal Adoption

Consensus:

 Consensus is a foundational concept in both distributed computing


and blockchain technology.
11
Web3 Technologies  It ensures consistency, security, and trust in decentralized
environments.

 Understanding how different algorithms work, their strengths and


limitations, is crucial for exploring fields like blockchain, cloud
computing, and distributed databases.

 In distributed systems, consensus refers to the process of achieving


agreement among multiple nodes on a single data value or system
state.

 In the context of blockchain, consensus ensures that all participating


nodes agree on the same version of the blockchain ledger despite the
absence of a central authority and the presence of potential faults or
malicious actors.

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.

Key Objectives of Consensus:

 Agreement: All honest nodes agree on the same value or transaction


history.

 Termination: Every correct process eventually decides on a value.

 Validity: The agreed value must be one that was actually proposed by
a node.

 Fault Tolerance: System should function even if some nodes fail or


act maliciously (Byzantine faults).

Features of Consensus Mechanisms:

Feature Description

Decentralization No single point of control or failure.

Fault Tolerance Able to handle faulty or malicious nodes.

Immutability Once a decision is made, it cannot be reversed.

Finality Guarantees that a decision is permanent and agreed


upon.

Scalability Efficient operation as network grows.

Security Resistant to attacks like double-spending or Sybil


attacks.
12
Common Consensus Algorithms: Blockchain

Proof of Work (PoW)

 Used in: Bitcoin, early Ethereum

 How it works: Nodes (miners) solve computational puzzles to


propose new blocks.

 Pros: Highly secure, proven.

 Cons: High energy consumption, slow.

Proof of Stake (PoS):

 Used in: Ethereum 2.0, Cardano

 How it works: Validators are selected to create blocks based on their


stake in the network.

 Pros: Energy-efficient, faster.

 Cons: "Nothing at stake" problem, initial distribution fairness.

Delegated Proof of Stake (DPoS):

 Used in: EOS, TRON

 How it works: Token holders elect a small group of delegates to


produce blocks.

 Pros: High throughput, governance via voting.

 Cons: Risk of centralization.

Practical Byzantine Fault Tolerance (PBFT):

 Used in: Hyperledger Fabric, Zilliqa

 How it works: Nodes communicate to reach agreement, tolerates


Byzantine faults.

 Pros: Fast, suitable for permissioned blockchains.

 Cons: Communication overhead increases with network size.

Raft / Paxos:

 Used in: Traditional distributed databases (not blockchain)

 How it works: One leader proposes values and followers replicate


them.

 Pros: Strong consistency.


13
Web3 Technologies  Cons: Not decentralized; vulnerable if leader fails.

Advantages of Consensus Mechanisms:

Advantage Explanation

Trustless Nodes don’t need to trust each other or a central


Environment authority.

Security and Prevents tampering and fraud in the system.


Data Integrity

Fault Tolerance Can continue working even when some nodes are
unreliable.

Decentralized Control is distributed, reducing the risk of censorship.


Governance

Transparency All decisions are publicly verifiable.

Disadvantages of Consensus Mechanisms:


 Performance Limitations: Some consensus types (like PoW) are
slow and resource-heavy.
 Scalability Issues: Communication overhead increases in large
networks.
 Energy Consumption: PoW-based systems consume significant
energy.
 Complexity: Designing and implementing secure consensus is
difficult.
 Centralization Risk (in PoS/DPoS): Large stakeholders may gain
outsized influence.
Real-World Applications:

Domain Use Case Example

Cryptocurrencies Secure transaction validation (e.g., Bitcoin,


Ethereum).

Voting Systems Tamper-resistant digital elections.

Supply Chains Verifiable product tracking and origin verification.

Distributed Ensures consistency and availability of data.


Databases

Healthcare Secured and agreed medical records sharing.


14
Choosing the Right Consensus Algorithm: Blockchain

Criteria Relevant Algorithms

High security (public networks) Proof of Work (PoW)

Energy efficiency Proof of Stake (PoS), PBFT

High throughput Delegated PoS, PBFT

Permissioned environments PBFT, Raft, Paxos

Governance mechanisms DPoS (via community voting)

Future Trends in Consensus:

 Hybrid Consensus: Combining PoW + PoS for optimal tradeoffs.

 Zero-Knowledge Proofs (ZKP): Enhanced privacy with consensus.

 Sharding: Partitioning the network for scalability and parallelism.

 AI-Assisted Consensus: Predictive models for optimizing decision-


making.

What is blockchain in simple terms?


Blockchain is a linked list of blocks, each containing a batch of
transactions, timestamped and cryptographically linked to the previous
block. This structure ensures data integrity and chronological order in a
distributed, append-only ledger.

What are the main components of a blockchain?

 Blocks: Contain transactions and metadata.

 Hash pointers: Link blocks securely.

 Consensus mechanism: Validates new blocks.

 Network nodes: Participants maintaining ledger copies.

 Cryptographic primitives: Hash functions, digital signatures, and


Merkle trees for security.

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.

1.1.5 CAP theorem and blockchain:


Definition:
The CAP Theorem states that a distributed system can only guarantee two
out of the following three properties at any given time:

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.

Availability ● Every request (read/write) receives a response (success


(A) or failure), even if some nodes are unreachable.
● Availability means that all clients who request data
receive a response even if one or more nodes are down.
● In a distributed system, every operational node replies
to each valid request made to it, to put it another way.
● Example:
Imagine you are the customer of a well-known vehicle
company in your city because of the incredible deals and
services it provides. In addition, they provide fantastic
customer service, so you can contact them whenever you
have questions or issues and get answers right away. The
car company is able to connect every consumer who phones
to one of its customer service representatives. Any
information needed by the customer regarding his cars,
such as the service date, the insurance plan, or other details,
can be obtained. Because any customer can connect to the
business or its operator and obtain information about the
user or client, we refer to this as availability.

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.

In the presence of a network partition (P), a distributed system must


choose between Consistency (C) and Availability (A).

CAP Theorem Examples:


Example 1: A mobile phone has been designed in such a way that it has
space for only one sim card which means no sharing.
Solution: This system guarantees Consistency, Availability, and
Tolerance to Partitions.
Example 2: Immediately after sending a message to someone, that
individual might not get it.
Solution: With this system, availability and partition tolerance are
compromised without compromising consistency, or AP.
Example 3: When we build a form for a group of individuals, the others
can only access it once we provide them permission to do so.
Solution: CP, or Consistency and Partition Tolerance without
Compromising Availability, is ensured by this system.

The different database of CAP Theorem fits in different software:


AP: Dynamo, Cassandra, Elastic Search, CouchDB, Riak, MongoDB.
CP: HBase, MongoDB, Redis, Memcached.
CA: Postgres, MySQL.

18
Note: Blockchain

If we opt for CP (consistency and partition tolerance), we sacrifice


availability.
If we opt for AP (availability and partition tolerance), we sacrifice
consistency.
If we opt for AC (availability and consistency), we sacrifice partition
tolerance.

What is the CAP theorem?

 The CAP theorem states that in a distributed system, only two out of
three properties can be guaranteed simultaneously: Consistency,
Availability, and Partition tolerance.

How does blockchain relate to the CAP theorem?

 Blockchains prioritize Partition tolerance due to the inherent


unreliability of networks.

 Depending on design, they balance Consistency and Availability


differently.

 For example, Bitcoin favors consistency (single ledger view),


sometimes sacrificing immediate availability during forks.

Why does Blockchain Violate CAP Theorem?

 Blockchain obviously violates the CAP theorem. As discussed above


both partition tolerance and availability are "income-producing"
characteristics.

 If the blockchain system is unavailable, businesses that use it will


begin to lose money.

 In other words, it's critical to record new transactions on a node in the


blockchain system whenever they are submitted, such as when money
is transferred from one business to another.

 In the absence of blockchain, the new transaction is lost.

 This is the reason why Blockchain violates the CAP theorem.

What is the CAP Theorem in Blockchain?

 CAP Theorem stands for Consistency, Availability, and Partition


Tolerance.

 According to the theory, a distributed system cannot always ensure


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.

 CAP Theorem or Brewer’s theorem states that it is feasible to provide


either consistency or availability but not both—in the event of a
network failure on a distributed database, a theory from theoretical
computer science about distributed data stores.

 In other words, according to the CAP theorem, a distributed database


system that experiences a partition must choose between Consistency
and Availability.

 We must simultaneously communicate over the network and store


data among several nodes in a distributed system.

 A distributed system frequently falls victim to network failures


because of its reliance on network calls in a significant way.

 Tolerance for partitions is crucial.

 In this situation, we must decide, based on our needs, whether to


prioritize consistency or availability.

 With blockchain technology, immediate consistency is frequently


sacrificed for availability and partition tolerance.

 By requiring a specific amount of "confirmations," blockchain


consensus techniques are simply simplified to eventual consistency.

 Network failures can affect any distributed system, hence network


partitioning is usually required.

 There are just two choices remaining in the event of a partition:


consistency or availability.

 The system will return an error or time out if a specific piece of


information cannot be guaranteed to be current owing to network
segmentation when consistency is chosen above availability.

 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.

 Blockchain is a decentralized database that manages a shared ledger


that cannot be altered.

 Transactions are what make up the shared ledger.

 Consensus techniques are used to record transactions inside the shared


ledger.

20
 Sharing distributed transactions naturally raises questions about the Blockchain
CAP theorem.

 Consistency is sacrificed in Blockchain due to the priority given to


Availability and Partition Tolerance.

 In this case, Partition tolerance (P), Availability (A), and Consistency


(C) on the blockchain are not attained simultaneously; instead, they
are acquired over time.

1.2 DECENTRALIZATION USING BLOCKCHAIN,


 Decentralization, according to many investors, is a major aspect of all
cryptocurrencies.

 When you think about it, the decentralization concept has made
Bitcoin the safest, most trusted, and most sought-after money on the
market.

 Despite this, only a tiny percentage of the population today


understands what decentralization is, what its primary characteristics
are, and what benefits it provides.

 Decentralization in blockchain refers to the transfer of authority and


decision-making from a centralized entity (person, organization, or
group thereof) to a distributed network.

 Decentralized networks are designed to reduce the amount of trust


that members must have in one another and to prevent members from
abusing power or authority in ways that undermine the network's
functionality.

Is it necessary for a blockchain to be decentralized?

 A controlled or decentralized blockchain is both possible.

 The phrases decentralized and dispersed, on the other hand, should


not be used interchangeably.

 A blockchain is naturally distributed (i.e., numerous parties hold


copies of the data) but not decentralized.

 Permission less or public blockchains and permission-based or private


blockchains are the two sorts of blockchains.

 Because each node in the network has a complete record of every data
published on the blockchain, public blockchains are now
decentralized.

 Bitcoin is a popular example of a decentralized blockchain.

 Private blockchains, on the other hand, are centralized.


21
Web3 Technologies  Because the network size is managed and the amount of access to
nodes is controlled by a single organization.

 Decentralization should be done only when it is necessary.

 It is not necessary for a blockchain application to be totally


decentralized.

 Any blockchain solution must meet the needs of the user, which may
or may not involve certain decentralization levels.

Why is decentralization important?

 When building a technology solution, three main network


architectures are commonly considered: centralized, dispersed, and
decentralized.

 While decentralized networks are widely employed in blockchain


technology, a blockchain application cannot simply be categorized as
such.

 Rather, decentralization should be gradually expanded to all aspects


of a blockchain program.

 Decentralizing resource management and access in an application can


result in better and more equitable service.

 Although decentralization has certain disadvantages, such as lower


transaction throughput, the advantages of improved stability and
service levels exceed the disadvantages.

Types of decentralization in blockchain:


Before we can comprehend the many sorts of decentralization in
blockchain, we must first comprehend the various levels of
decentralization in general.
Decentralization levels are covered further down.

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

○ A system in which no middlemen are used to govern or administer it.


○ Take Bitcoin, for example.

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.

● Increases the accuracy of data reconciliation:


○ Companies frequently share information with their partners.
23
Web3 Technologies ○ This data is then changed and kept in each party's data silos, only to
be resurfaced when it's time to transfer it downstream.
○ Each time data is converted, the possibility of data loss or inaccurate
data entering the workstream increases.
● Points of vulnerability are reduced:
○ Decentralization can help to mitigate sources of vulnerability in
systems when single actors are overly reliant.
○ Systemic failures might result from these flaws, such as the inability
to provide promised services or inefficient service owing to resource
exhaustion, recurrent outages, bottlenecks, a lack of appropriate
incentives for effective service, or corruption.
● Distributes resources more efficiently:
○ Decentralization may also aid in resource distribution optimization,
ensuring that promised services are delivered with improved
performance and consistency, as well as a lower risk of catastrophic
failure.
● Transparent:
○ Because decentralized blockchains are available to the public, they are
transparent.
○ The blockchain is open to everyone with an internet connection.
○ Each participating node keeps a single copy of the data.
● Full Control:
○ With decentralization, the blockchain's members or users have
complete authority over the activities.
○ Because there is no central authority, all of the blockchain's data,
control, and power are in the hands of its users.
● Immutable:
○ The data contained in a blockchain in a decentralized blockchain is
nearly hard to alter.
○ Because each alteration must be confirmed by each node in the
blockchain network, this is the case.
● Secure:
○ Decentralized blockchains are far more secure than centralized
blockchains because they employ encryption to protect data.
○ Furthermore, the data in the current block requires data from the
preceding block to be cryptographically confirmed.
24
Disadvantages of decentralization in Blockchain: Blockchain

● 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:

 In this method involving competition, different service providers


compete with each other in order to be selected for the provision of
services by the system.

 This paradigm does not achieve complete decentralization. However,


to a certain degree, it ensures that an intermediary or service provider
is not monopolizing the service.

 In the context of blockchain technology, a system can be envisioned


in which smart contracts can choose an external data provider from a
large number of providers based on their reputation, previous score,
reviews, and quality of service.

 This method will not result in full decentralization, but it allows smart
contracts to make a free choice based on the criteria just mentioned.

 This way, an environment of competition is cultivated among service


providers where they compete with each other to become the data
provider of choice.

1.2.2 Routes to decentralization:


Decentralization is not binary but exists on a spectrum.
The route to decentralization involves architectural, governance, and
economic shifts that prioritize transparency, community control, and trust
minimization.
As future computer scientists and developers, understanding and designing
decentralized systems is crucial in shaping secure, open, and democratic
digital ecosystems.

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

○ Start centralized for ease of development, then gradually shift control


to the community.
○ Common in blockchain startups, DAOs, and Web3 apps.
○ Phases:
■ Centralized product development
■ Open governance mechanisms introduced
■ Token or voting-based governance fully activated

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.

 Blockchain is a decentralized ledger that creates an open and shared


database of transactions or records which cannot be altered
retroactively or distributed across multiple networks without the broad
consensus of participants in these networks.

 The blockchain ecosystem is the network of all the participants in the


blockchain network that share the business process and business
objectives.

 The ecosystem encompasses the different governing structures like:


○ Individual participation.
○ Data ownership.
○ Exit and entrance criteria.
○ Information and data shared with the system's participants.

 It can provide immutability, decentralization, flexibility for day-to-


day operations, and scalability.

 The blockchain ecosystem is a boon for startups and new technology


projects as it creates an interconnected network.

Types of Blockchain Ecosystem:


Below are the three different types of blockchain ecosystems:

● Single-party led blockchain ecosystem:


○ This ecosystem is led by a single organization where all the
stakeholders have a mutual benefit for participating in the network.
○ For example, Bumble Bee Foods has created a single-party-led
blockchain ecosystem to improve the traceability of the yellowfin
tuna fish.
○ This helped to improve the buyer's confidence in the fish's freshness.

● Joint venture blockchain ecosystem:


○ This is also known as the Consortium blockchain ecosystem.
○ These are slowly becoming popular and they involve two or more
organizations in the ecosystem.
28
○ The participating organizations have an objective of participating in a Blockchain
common activity or pooling their resources for achieving a common
goal.
○ For example, BunkerTrace a marine fuel tracking solution is a joint
venture blockchain ecosystem between Forecast technology Ltd. and
Blockchain Labs for Open Collaboration (BLOC).

● Regulatory blockchain ecosystem:


○ This ecosystem comprises various government agencies that share a
project and have to self-report for compliance.
○ For example, a shared project between Marine Transport International
and Recycling Association.

Blockchain Ecosystem Benefit to the Organizations:

 Blockchain technology is having a profound effect on every aspect of


our lives and economy, starting with disrupting business processes.

 One of the advantages of blockchains, as opposed to traditional


databases, is that blockchains are decentralized and transparent,
greatly reducing risks while providing complete security.

 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.

Remodel complete workflow:


○ The blockchain ecosystem will revamp the complete workflow and
how projects are developed, from the starting stage to the end.

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.

 One can run as many node applications as likes and is permitted to


use, and each will participate in their respective blockchain
ecosystems.

Consensus algorithms:

 The consensus algorithm is implemented as a part of the node


application in the blockchain ecosystem.

 They provide the rules of the game for how the ecosystem will arrive
at the single view of the ledger.

 Different ecosystems have different ways of attaining consensus.

 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:

 It is the representation of the computer environment created by a


computer program and operated with instructions programmed in a
language.

 The virtual machine implementation happens alongside the node


application.

 For example, in the Ethereum blockchain ecosystem, the EVM resides


inside the node application.

Steps in Forming Blockchain Ecosystem:


The key steps in building and scaling the blockchain ecosystem are:

1. Ecosystem value proposition:

 This step includes defining the fundamental purpose of the ecosystem


actions.

 some of the questions that should be asked in this step are:

 What business problem is addressed by the proposed solution for the


ecosystem?

 How would the blockchain ecosystem impact each of the participants?


31
Web3 Technologies 2. Expected participants:

 This step involves brainstorming for the expected participants to


determine why they want to join the blockchain ecosystem.

 Some of the questions that should be considered in this step are:

 Who are the expected participants and why do they want to join the
ecosystem?

 What are the incentives for each of the expected participants to


engage in the blockchain ecosystem?

3. Ecosystem model:

 Organization will decide to have an idea on which collaboration


model will be the best fit for their purpose. The organization should
consider the following questions:

 Which single-party led, joint venture, or regulatory blockchain


ecosystem is the best model?

 How model might need to change over time?

4. Ecosystem governance:

 This is the most important step as it is very important to consider who


will operate the network and how it will be governed.

 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.

 The organization should consider the questions like.

1.2.4 The consensus problem:

 We know that Blockchain is a distributed decentralized network that


provides immutability, privacy, security, and transparency.

 There is no central authority present to validate and verify the


transactions, yet every transaction in the Blockchain is considered to
be completely secured and verified.

32
 This is possible only because of the presence of the consensus Blockchain
protocol which is a core part of any Blockchain network.

 A consensus algorithm is a procedure through which all the peers of


the Blockchain network reach a common agreement about the present
state of the distributed ledger.

 In this way, consensus algorithms achieve reliability in the


Blockchain network and establish trust between unknown peers in a
distributed computing environment.

 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.

 The Blockchain consensus protocol consists of some specific


objectives such as coming to an agreement, collaboration,
cooperation, equal rights to every node, and mandatory participation
of each node in the consensus process.

 Thus, a consensus algorithm aims at finding a common agreement


that is a win for the entire network.

1.2.5 Analysis and design:


● Core Requirements
● For a valid consensus protocol, the following properties must hold:
○ Agreement – All non-faulty processes must agree on the same value.
○ Termination – Every non-faulty process must eventually decide on a
value.
○ Validity – The agreed value must be one of the proposed values (or
meet problem-specific constraints).
○ Integrity – No process decides more than once.
● System Model Considerations
● When designing consensus algorithms, the model of the system
affects the solution:

○ 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

○ Binary Consensus – Agreement on a value from {0, 1}.


○ Multivalued Consensus – Agreement on any value from a larger set.
○ Approximate Consensus – Agreement within a numerical tolerance
(common in sensor fusion).

● 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

Fault Model Crash (Paxos, Raft), Byzantine (PBFT, Tendermint)

Synchrony Synchronous (Round-based), Asynchronous (Paxos),


Partial (PBFT, Raft)

Decision Type Binary, Multivalued, Approximate

Application Databases, Blockchain, Control Systems


Domain

1.2.7 Algorithms:
Now, we will discuss various consensus algorithms and how they work.

● Proof of Work (PoW):


○ This consensus algorithm is used to select a miner for the next block
generation.
○ Bitcoin uses this PoW consensus algorithm. The central idea behind
this algorithm is to solve a complex mathematical puzzle and easily
give out a solution.
○ This mathematical puzzle requires a lot of computational power and
thus, the node who solves the puzzle as soon as possible gets to mine
the next block.
○ For more details on PoW, please read Proof of Work (PoW)
Consensus

35
Web3 Technologies ● Practical Byzantine Fault Tolerance (PBFT):
○ Please refer to the existing article on practical Byzantine Fault
Tolerance(pBFT).

● Proof of Stake (PoS):


○ This is the most common alternative to PoW.
○ Ethereum has shifted from PoW to PoS consensus.
○ In this type of consensus algorithm, instead of investing in expensive
hardware to solve a complex puzzle, validators invest in the coins of
the system by locking up some of their coins as stakes.
○ After that, all the validators will start validating the blocks.
○ Validators will validate blocks by placing a bet on them if they
discover a block that they think can be added to the chain.
○ Based on the actual blocks added in the Blockchain, all the validators
get a reward proportional to their bets, and their stake increases
accordingly.
○ In the end, a validator is chosen to generate a new block based on its
economic stake in the network.
○ Thus, PoS encourages validators through an incentive mechanism to
reach an agreement.

● Delegated Proof Of Stake (DPoS):


○ This is another type of Proof of Stake consensus algorithm.
○ This type of consensus mechanism depends on the basis of the
delegation of votes. The users delegate their votes to other users.
○ Whichever user then mines the block will distribute the rewards to the
users who delegated to that particular vote.
○ Refer to the article Delegated Proof of Stake for more.

● Proof of Burn (PoB):


○ With PoB, instead of investing in expensive hardware equipment,
validators ‘burn’ coins by sending them to an address from where
they are irretrievable.
○ By committing the coins to an unreachable address, validators earn
the privilege to mine on the system based on a random selection
process.
○ Thus, burning coins here means that validators have a long-term
commitment in exchange for their short-term loss.
36
○ Depending on how the PoB is implemented, miners may burn the Blockchain
native currency of the Blockchain application or the currency of an
alternative chain, such as bitcoin.
○ The more coins they burn, the better their chances of being selected to
mine the next block.
○ While PoB is an interesting alternative to PoW, the protocol still
wastes resources needlessly.
○ And it is also questioned that mining power simply goes to those who
are willing to burn more money.

● 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.

● Proof of Elapsed Time:


○ PoET is one of the fairest consensus algorithms which chooses the
next block using fair means only.
○ It is widely used in permissioned Blockchain networks.
○ In this algorithm, every validator on the network gets a fair chance to
create their own block.
○ All the nodes do so by waiting for a random amount of time, adding
proof of their wait in the block.
○ The created blocks are broadcasted to the network for others'
consideration.
○ The winner is the validator which has the least timer value in the
proof part.
○ The block from the winning validator node gets appended to the
Blockchain.
○ There are additional checks in the algorithm to stop nodes from
always winning the election, and stop nodes from generating the
lowest timer value.

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.

 Referencing Mastering Blockchain (2nd Edition), it lays the


groundwork for understanding how blockchain powers the
decentralized Web3 ecosystem.

 Growth of Blockchain: Evolved from Bitcoin’s peer-to-peer


payment system into a multi-industry disruptive technology
supporting DeFi, NFTs, smart contracts, and supply chain
transparency.

 Distributed Systems: Blockchain is a form of distributed system that


overcomes challenges like unreliable communication, node failures,
and Byzantine faults using cryptography and consensus.

 Consensus Mechanisms: Ensure that all nodes agree on the


blockchain’s state; examples include Proof of Work (PoW), Proof of
Stake (PoS), Delegated PoS (DPoS), PBFT, PoB, PoC, and PoET.

 CAP Theorem: A distributed system can guarantee only two of


Consistency, Availability, and Partition tolerance; blockchain
prioritizes partition tolerance and often availability, sacrificing
immediate consistency.

 Decentralization: Eliminates central control, offering trustlessness,


transparency, security, and improved resource distribution, but may
reduce transaction throughput and increase complexity.

 Consensus Problem: Involves designing algorithms to achieve


agreement in the presence of faults and delays; classified by fault
models, system synchrony, decision type, and application domain.

 Analysis & Design: Key requirements include agreement,


termination, validity, and integrity, considering system type
(synchronous, asynchronous, partially synchronous) and performance
metrics.

 Algorithms: Different approaches offer trade-offs in fault tolerance,


scalability, energy use, and speed, making algorithm selection
application-specific.

38
1.4 EXERCISE WITH SOLUTION (NOTE: ELABORATE Blockchain

THE ANSWER WITH GIVEN POINTERS)


Q1. Define blockchain. List and explain any four of its key features.

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:

 Works in partially synchronous systems.

 Can tolerate up to f faulty nodes in a network of 3f + 1 nodes.

 Uses a voting-based mechanism: pre-prepare → prepare → commit


phases.

 Provides finality in decision-making without probabilistic


confirmations.

Q9. What is decentralization in blockchain? Mention its advantages and


disadvantages.

Answer:

Definition: Removal of central control, distributing authority among


network participants.

Advantages:

 Trustless transactions.

 Improved fault tolerance.

 Greater transparency.

Disadvantages:

 Slower transaction speed.

 Higher resource usage.

 Complex governance.

Q10. Explain approximate consensus and its applications.

Answer:

 Definition: Nodes agree on values within an acceptable error margin,


rather than exact equality.

 Applications: Sensor networks, robotic coordination, distributed


control systems.

 Approach: Iterative averaging or gossip-based protocols.

41
Web3 Technologies Q11. Compare synchronous, asynchronous, and partially synchronous
systems in consensus design.

Answer:

 Synchronous: Fixed time limits for communication and processing;


easier consensus.

 Asynchronous: No timing guarantees; FLP theorem limits fault


tolerance.

 Partially synchronous: Behaves asynchronously but occasionally


meets synchronous assumptions; used in practical protocols like
PBFT.
Q12. Mention any four blockchain applications outside of cryptocurrency.

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:

 Explain the concept and role of cryptographic keys in Bitcoin.

 Describe the structure, components, and lifecycle of Bitcoin


transactions.

 Understand the process and purpose of blockchain mining.

 Identify and differentiate types of nodes in the Bitcoin network.

 Explain Bitcoin wallets, their types, and security measures.

 Illustrate the process and characteristics of Bitcoin payments.

 Discuss key innovations in Bitcoin’s history.

 Understand advanced protocols that extend Bitcoin’s functionality.

 Analyze investment opportunities and risks in Bitcoin.

 Describe the process of buying and selling Bitcoin securely.


43
Web3 Technologies
2.1 CRYPTOGRAPHIC KEYS
 The first Bitcoin protocol and proof of concept was published in a
Whitepaper in 2009 by a shadowy individual or group under the
pseudonym Satoshi Nakamoto.

 Eventually Nakamoto, who remained mysterious, left the project in


late 2010.

 Other developers took over and the Bitcoin community has since
grown exponentially.

 While Satoshi Nakamoto's real identity remains shrouded in mystery,


it is on record that he communicated extensively in Bitcoin's early
days.

 Let us speculate on questions like when he started working on


Bitcoin, to what extent he was inspired by similar ideas and what was
the motivation for bitcoin.

Bitcoin uses public-key cryptography (specifically the Elliptic Curve


Digital Signature Algorithm, ECDSA) to secure transactions, verify
ownership, and control access to funds.

In this system:

 Private keys act as the “password” that allows spending bitcoins.

 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.

Role of Cryptographic Keys in Bitcoin:

 Proof of Ownership: Only the holder of a private key can authorize


spending from a specific Bitcoin address.

 Transaction Signing: Private keys are used to digitally sign


transactions, proving authenticity without revealing the key itself.

 Verification: Public keys are used by the network to verify the


validity of a transaction signature.

 Security: Ensures that funds cannot be stolen without access to the


correct private key.

44
Types of Keys in Bitcoin: Bitcoin

a) Private Key:

 A 256-bit random number, typically represented in hexadecimal or


Wallet Import Format (WIF).

 Must be kept secret; loss means permanent loss of access to funds.

 Example (hex): E9873D79C6D87DC0FB6A5778633389...

 Functions:
○ Generate corresponding public key.
○ Sign transactions.

 Security: Generated using cryptographically secure random number


generators.

b) Public Key:

 Derived from the private key using Elliptic Curve Multiplication


(Bitcoin uses curve secp256k1).

 A point on the elliptic curve (x, y) coordinates.

 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:

 Definition: A shortened, encoded form of the public key (actually the


hash of the public key) to enhance privacy and security.

 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:

Aspect Private Key Public Key Bitcoin Address

Definition Secret 256-bit Derived from private Encoded hash of


number key public key

Purpose Sign Verify signatures Receive bitcoins


transactions

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

A standard Bitcoin transaction consists of the following parts:


a) Transaction Inputs:
● Represent the source of bitcoins being spent.
● Reference previous unspent transaction outputs (UTXOs).
● Each input includes:
○ Transaction ID of the previous transaction.
○ Index number of the output being spent.
○ ScriptSig (digital signature + public key of the spender).

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.

The UTXO Model


● Bitcoin uses the Unspent Transaction Output (UTXO) model:
○ Bitcoins are not stored as account balances.
○ They exist as unspent outputs from previous transactions.
● To spend bitcoins, you must use these outputs as inputs in a new
transaction.
● Any leftover amount is sent back to the sender as “change” in a new
output.

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

○ UTXO from a previous transaction where Alice received 1 BTC.


● Outputs:
○ 0.8 BTC to Bob’s address.
○ 0.199 BTC to Alice’s change address.
● Fee:
○ 0.001 BTC (difference between inputs and outputs).

Types of Bitcoin Transactions:


1. P2PKH (Pay-to-PubKey-Hash) – Standard, most common type;
requires public key & signature to spend.
2. P2SH (Pay-to-Script-Hash) – Allows more complex conditions,
such as multisignature wallets.
3. Coinbase Transactions – Special transactions that create new
bitcoins as block rewards; no inputs.
4. Multisignature Transactions – Require signatures from multiple
private keys.
5. SegWit Transactions – Separate witness data from transaction data,
reducing size and fees.

Transaction Lifecycle
Unconfirmed State:

 Exists in the mempool (memory pool) waiting for a miner to include it


in a block.

Confirmed State:

 Included in a mined block.

 More confirmations increase security (e.g., 6 confirmations = highly


secure for large transactions).

Security Aspects:

 Digital Signatures: Prevent unauthorized spending.

 Public Ledger: All transactions are publicly auditable.

 Consensus: Prevents double-spending.

 Fees: Prevent spam transactions and incentivize miners.

49
Web3 Technologies  Change Addresses: Protect privacy by not reusing addresses.

Transaction Size & Fees:

 Fee often depends on transaction size (in bytes), not amount of BTC
transferred.

 Larger transactions (more inputs) = higher fees.

Summary Table:

Component Description Example

Input Reference to TXID:abc… + Sig


previous UTXO +
signature

Output Destination 1A1zP1… → 0.5 BTC


address + amount

Fee Incentive for 0.0005 BTC


miners

ScriptSig Unlocking script Signature + PubKey


(input)

ScriptPubKey Locking script OP_DUP OP_HASH160


(output) <pubKeyHash>
OP_EQUALVERIFY
OP_CHECKSIG

50
2.3 BLOCKCHAIN MINING Bitcoin

Introduction:
Mining in Bitcoin is the process by which:

 New bitcoins are created (as block rewards).

 Transactions are validated and added to the blockchain.

 Network security is maintained through proof-of-work (PoW).


Miners compete to solve a computational puzzle — finding a hash value
below a certain target — using the SHA-256 hashing algorithm. The first
miner to solve it earns the right to add a block and receive the reward.

Purpose of Mining:
1. Transaction Verification
○ Ensures that only valid transactions are recorded.
○ Prevents double-spending.

2. New Bitcoin Issuance


○ Coins enter circulation through block rewards.

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

 This requires massive trial-and-error, consuming energy and


computational resources.

 Difficulty adjusts every 2016 blocks (~2 weeks) to maintain ~10-


minute block intervals.

Block Structure in Mining


Each mined block contains:
● Block Header (80 bytes) including:
○ Version number.
51
Web3 Technologies ○ Previous block hash.
○ Merkle root (hash of all transactions in the block).
○ Timestamp.
○ Difficulty target.
○ Nonce.
● Transaction List (starting with coinbase transaction).

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.

Mining Process Steps:


1. Transaction Collection
○ Miners gather valid transactions from the mempool.

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:

 Adjusted every 2016 blocks to maintain a constant average block time


(~10 minutes).

 If blocks are mined too quickly → difficulty increases.

 If too slow → difficulty decreases.

52
Rewards & Halving: Bitcoin

 Initial reward: 50 BTC per block.

 Halves every 210,000 blocks (~4 years).


● Current reward (as of 2024): 6.25 BTC per block.

 Halving continues until the maximum supply of 21 million BTC is


reached (expected ~2140).

Mining Hardware Evolution:


1. CPU Mining – Early stage, low hash rate.
2. GPU Mining – Increased parallel processing capability.
3. FPGA Mining – Energy-efficient, programmable hardware.
4. ASIC Mining – Application-Specific Integrated Circuits designed
solely for SHA-256 hashing.

Mining Pools:

 Miners combine computational power to reduce variance in rewards.

 Pool operator distributes rewards proportional to contributed work.

 Common reward systems:


○ Pay-per-Share (PPS)
○ Proportional
○ Pay-per-Last-N-Shares (PPLNS)

Security Role of Mining:

 The 51% Attack concept: If a miner or group controls >50% of hash


power, they could double-spend or censor transactions.

 PoW mining makes such attacks costly and impractical for large
networks like Bitcoin.

Environmental Considerations:

 High energy consumption due to competitive hashing.

 Push toward renewable energy sources and more efficient hardware.

53
Web3 Technologies

Summary Table

Aspect Details

Algorithm SHA-256 (double hashing)

Block Time ~10 minutes

Initial Reward 50 BTC

Reward Halving Every 210,000 blocks (~4 years)

Max Supply 21 million BTC

Difficulty Adjustment Every 2016 blocks

Main Purpose Verify transactions, issue new BTC, secure


network

2.4 BITCOIN NETWORK


Introduction:
The Bitcoin network is a peer-to-peer (P2P) distributed network that
supports:

 The storage of the Bitcoin blockchain.

 Validation and relay of transactions.

 Execution of the consensus mechanism (Proof-of-Work).


No central server controls Bitcoin; instead, thousands of nodes work
together to maintain the ledger.

54
Network Architecture: Bitcoin

 Type: Decentralized P2P overlay network.

 Protocol: Operates over TCP/IP using a custom Bitcoin protocol


(port 8333 by default).

 Nodes: Participants in the network that store and relay blockchain


data.

Node Types:
1. Full Nodes
○ Store the entire blockchain.
○ Verify all transactions and blocks.
○ Example software: Bitcoin Core.

2. Lightweight Nodes (SPV – Simplified Payment Verification)


○ Store only block headers, not full blockchain data.
○ Rely on full nodes for transaction verification.

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.

Communication in the Bitcoin Network:


● Message Types:
○ inv – Announces new transactions or blocks.
○ getdata – Requests specific data.
○ tx – Transaction data.
○ block – Block data.

● 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:

 Decentralization: Prevents single points of failure.

 PoW Consensus: Protects against double-spending and blockchain


tampering.

 Verification Rules: Every node enforces consensus rules


independently.

Scalability and Limitations:

 Block Size Limit: 1 MB (before SegWit; more effective capacity


with SegWit).

 Transaction Throughput: ~7 transactions per second.

 Latency: Depends on block propagation speed (~seconds).

Network Upgrades:

 Soft Forks: Backward-compatible protocol changes (e.g., SegWit).

56
 Hard Forks: Non-backward-compatible changes requiring all nodes Bitcoin
to upgrade.

Summary Table

Component Description

Network Type Decentralized P2P overlay

Protocol Port 8333

Node Types Full, SPV, Mining, Archival, Pruned

Consensus Proof-of-Work

Security Decentralized verification, PoW

Limitations ~7 TPS, block size constraints

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.

Functions of a Bitcoin Wallet:

 Key Management: Generates, stores, and secures private/public keys.

 Transaction Signing: Uses the private key to sign transactions.


57
Web3 Technologies  Address Management: Creates and manages multiple public
addresses.

 Balance Display: Calculates balance by scanning the blockchain for


UTXOs.

 Secure Communication: Interfaces with Bitcoin nodes to


send/receive transactions.

Types of Bitcoin Wallets


A) Based on Storage Location:
1. Hot Wallets (Connected to the internet)
○ Examples: Web wallets, mobile apps, desktop software.
○ Pros: Easy access, convenient for frequent transactions.
○ Cons: Higher risk of hacking/malware.
2. Cold Wallets (Offline storage)
○ Examples: Hardware wallets, paper wallets, air-gapped computers.
○ Pros: High security, immune to online attacks.
○ Cons: Less convenient for daily use.

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.

C) Based on Device Type:


1. Desktop Wallets – Installed on a personal computer.
2. Mobile Wallets – Installed as apps on smartphones.
3. Web Wallets – Accessed via browsers, often hosted by exchanges.
58
4. Hardware Wallets – Physical devices storing keys securely (e.g., Bitcoin
Ledger, Trezor).
5. Paper Wallets – Printed private/public keys, stored physically.

Wallet Security:

 Private Key Protection: Loss of a private key means loss of funds.

 Backups: Store backups offline and securely.

 Encryption: Protect wallet files with strong passwords.

 Two-Factor Authentication (2FA): Adds extra security for online


wallets.

 Seed Phrases: A mnemonic phrase that can restore keys in case of


loss.

Hierarchical Deterministic (HD) Wallets:


● Use BIP-32/BIP-44 standards.
● Generate a tree of keys from a single seed phrase.
● Advantages:
○ Infinite number of addresses from one seed.
○ Easy backup and recovery.
○ Enhanced privacy by avoiding address reuse.

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:

 Use cold storage for large amounts.

 Use hardware wallets for high-value, long-term holdings.

 Regularly update wallet software.

 Avoid key reuse to maintain privacy.


59
Web3 Technologies Summary Table

Wallet Type Storage Security Convenience Example

Hot Wallet Online Lower High Mobile/Web

Cold Wallet Offline Higher Low Hardware/Paper

Full Node Local High Low Bitcoin Core

SPV Wallet Local Medium High Electrum

2.6 BITCOIN PAYMENTS


Introduction:
Bitcoin payments are transactions on the Bitcoin blockchain used to
transfer value from one party to another without the need for a central
authority such as banks or payment processors.
They use public-key cryptography and Proof-of-Work consensus to
ensure secure, peer-to-peer settlement.

Key Characteristics:

 Peer-to-Peer: Payments go directly between sender and receiver


without intermediaries.

 Global: Works across borders without currency conversion.

 Irreversible: Once confirmed on the blockchain, payments cannot be


reversed.

 Transparent: All payment transactions are recorded on a public


ledger.

 Secure: Uses cryptographic signatures for authentication.

Payment Flow in Bitcoin:


1. Invoice Creation (Optional)
○ Merchant generates a payment request with amount, address, and
optional description.

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

○ Wallet signs the transaction using the payer’s private key.

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.

6. Mining & Confirmation


○ Miners include the transaction in a block.
○ Confirmation count increases as new blocks are added (common
threshold: 6 confirmations for high-value payments).

7. Settlement
○ Once confirmed, the merchant considers payment final.

Payment Methods in Bitcoin:


1. On-Chain Payments
○ Standard Bitcoin transactions recorded on the blockchain.
○ Slower (minutes) and incur miner fees.

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.

4. Payment via QR Codes


○ Encodes address and amount for easy scanning.

The Lightning Network for Bitcoin Payments:


● Layer 2 scaling solution enabling instant, low-fee microtransactions.

61
Web3 Technologies ● Works through bi-directional payment channels between parties.

● Only opening and closing transactions are recorded on the blockchain;


intermediate payments occur off-chain.

● Advantages:

○ Near-instant payments

○ Very low fees.

○ Scalable for microtransactions.

Advantages of Bitcoin Payments:

● No chargebacks or reversals.

● Lower transaction costs compared to traditional payment gateways.

● Accessibility for unbanked populations.

● Privacy (if best practices like address reuse avoidance are followed).

Challenges & Limitations:

● Price volatility of BTC affects payment amounts.

● Confirmation delays for on-chain transactions.

● Irreversible payments can be risky without escrow.

● Regulatory restrictions in some regions.

● Merchant adoption still growing.

Example Bitcoin Payment:

● Scenario: Alice buys an online service for 0.015 BTC.

● Wallet selects UTXOs totaling 0.02 BTC.

● Output 1: 0.015 BTC to merchant’s address.

● Output 2: 0.0049 BTC change to Alice’s address

● Fee: 0.0001 BTC.

● Transaction is signed and broadcast → confirmed in ~10 minutes.

62
Summary Table Bitcoin

Step Description

Create Payment Request Merchant generates address and amount

Build Transaction Select UTXOs, define outputs

Sign Transaction Use private key

Broadcast Send to P2P network

Verify Nodes check validity

Confirm Miners include in block

Settle Payment final after confirmations

2.7 INNOVATION IN BITCOIN


Introduction:
Bitcoin, introduced in 2008 by Satoshi Nakamoto, was itself a
groundbreaking innovation—combining cryptography, distributed
computing, and game theory into the first decentralized digital currency.
Over time, additional innovations have emerged to improve Bitcoin’s
scalability, security, privacy, and usability.

Core Innovative Contributions of Bitcoin:


1. Decentralized Digital Currency
○ No central authority; peer-to-peer payment system.

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.

5. Open Source Protocol


○ Encourages global participation and improvement.

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

● Simplifies sending bitcoins to complex scripts.


● Allows recipients to set spending conditions without revealing them
in advance.

F) Hierarchical Deterministic (HD) Wallets:


● Standardized in BIP-32/BIP-44.
● Generate many keys from a single seed phrase.
● Easier backup and improved privacy.

Innovations for Privacy:


● CoinJoin: Combines multiple transactions to obfuscate the
sender/receiver link.
● PayJoin: Enhances privacy by mixing inputs from both sender and
receiver.
● Stealth Addresses: One-time addresses to hide recipient’s identity.

Innovations for Scalability:


● Block Size Optimization via SegWit.
● Layer 2 Solutions (Lightning Network, sidechains like Liquid).
● Batching Transactions to reduce chain load.

Innovations for Security:


● Stronger wallet security via hardware wallets and multisignature
setups.
● Cold storage methods for offline key protection.
● Mining decentralization strategies to reduce concentration of hash
power.

Impact of Bitcoin Innovations:


● Economic Impact: Lower-cost global transactions, financial
inclusion.
● Technological Impact: Inspired entire blockchain and cryptocurrency
ecosystems.
● Regulatory Impact: Challenged traditional finance, prompting new
legal frameworks.

65
Web3 Technologies Summary Table

Innovation Year/Upgrade Benefit

SegWit 2017 More capacity, malleability fix

Lightning Network 2018+ Instant, cheap microtransactions

Taproot 2021 Privacy, efficiency, smart


contracts

Schnorr Signatures 2021 Signature aggregation, better


privacy

P2SH 2012 Easier complex scripts

HD Wallets 2013 Easy key management, privacy

2.8 ADVANCED PROTOCOLS


Introduction:
While Bitcoin’s base layer supports simple peer-to-peer value transfers,
developers have built advanced protocols on top of or alongside Bitcoin
to add functionality, scalability, and privacy.
These protocols often use the blockchain as a secure settlement layer
while enabling more complex applications.

Types of Advanced Protocols


A) Colored Coins:
● Concept: Assign real-world assets (stocks, bonds, property) to
specific satoshis on the Bitcoin blockchain.
● How it Works: Metadata embedded in Bitcoin transactions describes
the asset.
● Use Cases: Asset issuance, tokenized securities.
● Limitations: Requires off-chain agreement for asset enforcement.

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

● Protocol layer on top of Bitcoin.


● Enables creation of custom digital assets and currencies.
● Famous Use Case: Issuance of Tether (USDT) on 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.

G) MAST (Merkelized Abstract Syntax Trees):


● Improves smart contract privacy and efficiency.
● Only the executed branch of a contract is revealed on-chain.
● Integrated into Bitcoin via Taproot upgrade.

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).

Use Cases of Advanced Protocols:


● Asset tokenization.
● Decentralized exchanges.
● Micropayments.
● Confidential transactions.
● Cross-chain interoperability.
● Smart contracts on Bitcoin.

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

Protocol Purpose Example Use Case

Colored Coins Asset tokenization Stocks, property

Counterparty Token creation, DEX Gaming assets

Omni Layer Asset issuance USDT on Bitcoin


68
Bitcoin
Lightning Network Fast micropayments Retail payments

Sidechains Specialized blockchains Liquid Network

MAST Smart contract efficiency Taproot-enabled scripts

2.9 BITCOIN INVESTMENT AND BUYING & SELLING


BITCOIN
Introduction:
Bitcoin is considered both a digital currency and a speculative
investment asset.
Its scarcity (21 million BTC cap), decentralization, and increasing
adoption have made it attractive to investors.

Reasons for Investing in Bitcoin:

 Store of Value: Often compared to “digital gold”.

 Hedge Against Inflation: Fixed supply resists currency devaluation.

 Portfolio Diversification: Low correlation with traditional assets.

 Potential High Returns: Historical price growth has been significant.

 Borderless Asset: Easy to transfer globally without intermediaries.

Investment Methods:
1. Direct Purchase
○ Buy Bitcoin and store in a wallet.

2. Bitcoin Funds & ETFs


○ Indirect exposure through investment products.

3. Bitcoin Mining
○ Invest in hardware to earn block rewards.

4. Derivatives Trading
○ Futures, options, and CFDs for speculative positions.

5. Dollar-Cost Averaging (DCA)


○ Invest fixed amounts at regular intervals to reduce volatility risk.

69
Web3 Technologies Risks in Bitcoin Investment:

 Volatility: Large price swings.

 Regulatory Risk: Changing laws can impact adoption.

 Security Risk: Theft via hacking or phishing.

 Liquidity Risk: In low-volume markets, large trades may move


prices.

 Technology Risk: Protocol changes or competition from other


cryptocurrencies.

Best Practices for Investors:

 Use secure wallets (preferably hardware wallets) for storage.

 Diversify investments; avoid putting all capital into Bitcoin.

 Keep up to date with regulatory developments.

 Avoid panic selling during market dips.

 Use long-term perspective for investment decisions.

Buying and Selling Bitcoin


Buying Bitcoin
A) Through Exchanges:
● Centralized exchanges (CEXs): Coinbase, Binance, Kraken.
● Steps:
1. Create and verify account (KYC process).
2. Deposit fiat currency.
3. Place buy order (market, limit).
4. Withdraw Bitcoin to a personal wallet.
● Decentralized exchanges (DEXs): Peer-to-peer trading without
intermediaries.

B) Peer-to-Peer (P2P) Platforms


● Buyers and sellers connect directly (e.g., LocalBitcoins, Paxful).
● Payment methods: Bank transfer, cash, PayPal, etc.

70
C) Bitcoin ATMs: Bitcoin

● Physical machines that accept cash or cards and send Bitcoin to a


wallet address.

D) Over-the-Counter (OTC) Desks:


● Used for large trades to avoid impacting market price.

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.

Transaction & Fees:


● Exchange fees: Usually 0.1%–1% per trade.
● Network fees: Paid to miners for transaction confirmation.
● Higher fees can speed up confirmations.

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.

Legal and Tax Implications:


● Many jurisdictions treat Bitcoin as taxable property.
● Capital gains tax applies when selling Bitcoin at a profit.
● Investors should keep transaction records for reporting.

Summary Table

Aspect Buying Methods Selling Methods Risks

Exchange CEX, DEX Sell orders on Exchange hacks


CEX/DEX

P2P Direct deals Direct deals Fraud, scams

71
Web3 Technologies
ATM Cash purchase Cash payout (limited) High fees

OTC Large-volume Large-volume sale Counterparty risk


purchase

2.10 SUMMERY
 This chapter covers Bitcoin as the first decentralized cryptocurrency,
focusing on its core components and supporting technologies.

 It begins with cryptographic keys, explaining the use of public and


private keys, Bitcoin addresses, and digital signatures for secure
ownership and transactions.

 It then details transactions, their inputs, outputs, fees, and the UTXO
model, along with the process from creation to confirmation.

 Blockchain mining is explained as a process for validating


transactions, securing the network, and issuing new coins through
Proof-of-Work.

 The Bitcoin network is described as a decentralized P2P system


consisting of full nodes, SPV nodes, and miners.

 Wallets are covered, highlighting types (hot, cold, hardware, paper)


and their security features.

 Bitcoin payments are explained, including on-chain, off-chain


(Lightning Network), and escrow methods.

 The chapter also outlines innovations like SegWit, Taproot, and


Schnorr signatures, and advanced protocols like colored coins, Omni
Layer, and sidechains.

 Finally, Bitcoin investment is discussed, along with buying and


selling methods through exchanges, P2P, ATMs, and OTC desks,
including legal and security considerations.

2.11 EXERCISE WITH SOLUTION.(NOTE:


ELABORATE YOUR ANSWER BASED ON GIVEN
POINTERS)
1. Explain the role of cryptographic keys in Bitcoin:
Answer:
Bitcoin uses public-key cryptography (ECDSA) to secure transactions.

 Private key: A secret 256-bit number used to sign transactions.

72
 Public key: Derived from the private key; used to verify signatures. Bitcoin

 Bitcoin address: Encoded form of the public key’s hash.


Only the holder of the private key can spend bitcoins from an
address.

2. Describe the UTXO model used in Bitcoin transactions.


Answer:
Bitcoin doesn’t store balances but tracks Unspent Transaction Outputs
(UTXOs).
When spending, a transaction uses UTXOs as inputs and creates new
outputs.
Unused funds are returned as “change” in a new UTXO.
This model ensures transparency and prevents double-spending.

3. What is the purpose of mining in Bitcoin?


Answer:
Mining serves three purposes:
1. Validate Transactions – ensuring they are legitimate.
2. Secure the Network – via Proof-of-Work to prevent tampering.
3. Issue New Bitcoins – miners receive block rewards and transaction
fees.
4. Differentiate between full nodes and SPV nodes in the Bitcoin
network.
Answer:

 Full nodes: Store the entire blockchain, validate all transactions


independently.

 SPV nodes: Store only block headers, rely on full nodes for
verification.
Full nodes provide maximum security; SPV nodes are lightweight and
resource-efficient.

5. List and explain types of Bitcoin wallets.


Answer:
1. Hot Wallets: Online, convenient, less secure (e.g., web wallets).
2. Cold Wallets: Offline, highly secure (e.g., hardware wallets).
73
Web3 Technologies 3. Full Node Wallets: Store full blockchain.
4. SPV Wallets: Lightweight, rely on full nodes.
5. Multisignature Wallets: Require multiple keys for spending.

6. Explain the Lightning Network and its advantages.


Answer:
A Layer 2 protocol for Bitcoin enabling fast, low-fee payments via
payment channels.
Advantages:

 Instant transactions.

 Very low fees.

 Scalability (millions of transactions per second).


Only channel opening/closing is on-chain.

7. What is Segregated Witness (SegWit) and why was it introduced?


Answer:
SegWit separates signature data from transaction data.
Benefits:

 Increases block capacity.

 Fixes transaction malleability.

 Enables Layer 2 solutions like Lightning Network.

8. Describe the process of buying Bitcoin through an exchange.


Answer:
1. Create account and complete KYC verification.
2. Deposit fiat currency.
3. Place buy order (market or limit).
4. Withdraw Bitcoin to a secure wallet.

9. State the risks involved in Bitcoin investment.


Answer:

 Volatility: Large price fluctuations.

 Regulatory changes: May impact trading and usage.


74
 Security risks: Theft via hacking or phishing. Bitcoin

 Liquidity risks: Low-volume markets may cause slippage.

 Technology risks: Protocol changes or competitors.

10. Explain Pay-to-Script-Hash (P2SH) in Bitcoin.


Answer:
P2SH allows sending bitcoins to a script hash instead of a public key hash.
The spender must provide the script and satisfy its conditions to unlock
funds.
Used for multisignature and complex spending rules.

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).

12. Explain the concept of transaction fees in Bitcoin.


Answer:
Transaction fee = Total input value − Total output value.
Fees incentivize miners to include transactions in blocks.
Higher fees can lead to faster confirmations.

*****

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.

 To explore Ricardian contracts, smart contract templates, and oracles.

 To learn the process of deploying smart contracts.

 To study The DAO case and its implications on blockchain


governance.

 To gain an overview of Ethereum, its network, components, and the


Ethereum Virtual Machine (EVM).

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.

Conceptual Origin: Nick Szabo (1994)

 Definition: Nick Szabo introduced the term smart contract in 1994,


defining it as:
"A set of promises, specified in digital form, including protocols within
which the parties perform on these promises."

 Primary Goal: Automate and enforce contractual clauses through


computer protocols, reducing reliance on trusted intermediaries.

 Inspiration: Vending machines — an early mechanical example of a


self-executing contract. When correct payment is inserted, the
machine automatically delivers goods without further human
intervention.

Vending Machine as a Primitive Smart Contract:


[User Inserts Coins] --> [Machine Verifies Payment] --> [Dispenses
Product]
Pre-Blockchain Implementations (1990s–2008)
● Smart contracts were attempted via centralized platforms:
○ Online escrow services for digital transactions.
○ Financial derivatives platforms with automated trade settlement.
○ Multi-signature authorization systems for secure fund transfers.

● 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.

● Smart Contract Capabilities in Bitcoin:


○ Multi-signature transactions.
○ Escrow arrangements.
○ Time-locked transactions.

● Limitations:
○ Bitcoin’s scripting language is intentionally non–Turing-complete.
○ Complex contract logic was impractical.

Bitcoin Smart Contract Flow:


[Transaction Script] --> [Validation by Network] --> [Funds Released per
Script Rules]
Ethereum and the EVM Revolution (2013–2015)
● Vitalik Buterin's Proposal (2013): Extend blockchain capabilities
beyond financial transactions to fully programmable applications.

● Ethereum Virtual Machine (EVM):


○ Turing-complete execution environment.
○ Enables deployment of arbitrary, complex logic.
○ Operates in a decentralized, trustless network.
● Ethereum Mainnet Launch (2015): Marked the first large-scale
platform for truly general-purpose smart contracts.

Ethereum Smart Contract Flow


[User Interaction] --> [Transaction Sent to Blockchain] --> [EVM
Executes Contract Code] --> [State Updated & Verified by Network]
Smart Contracts in Practice (2015–Present)

● 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

Diagram 4: Smart Contract Historical Progression


[1994] Vending Machine Analogy (Nick Szabo)
|
[2000s] Centralized Smart Contract Experiments
|
[2009] Bitcoin with Basic Scripted Contracts
|
[2013] Ethereum Proposal by Vitalik Buterin
|
[2015] Ethereum Launch: Fully Programmable Contracts
|
[2017+] DeFi, NFTs, DAOs, and Beyond

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.

3.2 DEFINITION RICARDIAN CONTRACTS


Origin and Purpose:

 Introduced by Ian Grigg in the late 1990s.

 Designed as a bridge between legal contracts and digital execution.


79
Web3 Technologies Aim:
Provide a single document that is both human-readable and machine-
readable, ensuring clarity for both legal professionals and computer
systems.

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.

4. Secure Hash Binding


○ The document is hashed, and this hash is embedded in the blockchain
or transaction, ensuring immutability.

5. Dual Functionality
○ Serves as both the legal agreement and the basis for program
execution.

Structure:
A Ricardian contract typically includes:

 Natural Language Agreement – outlines obligations, rights, and


terms.

 Structured Metadata – terms, identifiers, and variables in machine-


readable form.

 Digital Signatures – for non-repudiation.

80
 Hash Fingerprint – unique ID linking the agreement to blockchain Smart Contracts and
Ethereum
records.

Advantages:

 Bridges legal enforceability and digital automation.

 Reduces disputes by having a single authoritative document.

 Ensures both humans and machines interpret the contract consistently.

 Immutable and verifiable through cryptographic hashing.

 Relation to Smart Contracts

 Smart contracts are executable code; Ricardian contracts are


hybrid documents linking legal prose to code execution.

 Often, Ricardian contracts are used to describe the intended behavior


of a smart contract in a legally binding way.

3.3 SMART CONTRACT TEMPLATES


Introduction:

 Smart contract templates are predefined frameworks that provide a


structured format for creating smart contracts.

 Designed to make contract creation more efficient, less error-prone,


and more understandable for both developers and non-technical
users.

 They act as standardized blueprints for recurring types of


blockchain agreements.

Purpose:

 Reduce development complexity.

 Facilitate interoperability between contracts.

 Ensure legal and operational consistency.

 Provide a bridge between natural language contracts and


executable code.

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.

2. Machine and Human Readability


○ Can be combined with Ricardian contracts to ensure both legal
clarity and code precision.

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:

 Financial contracts – e.g., loan agreements, derivatives.

 Token issuance – ERC-20 or ERC-721 token creation.

 Escrow arrangements – holding funds until conditions are met.

 Supply chain agreements – tracking goods with predefined


milestones.

Advantages:

 Efficiency: Rapid deployment without coding from scratch.

 Reliability: Less room for programming mistakes.

 Clarity: Pre-approved legal wording reduces ambiguity.

 Compliance: Templates can be vetted for regulatory adherence in


advance.

 Auditability: Standard formats make auditing faster.

 Relation to Other Contract Concepts

 Smart Contracts: Templates are a method to produce smart contracts


more reliably.

 Ricardian Contracts: Templates can be designed in Ricardian format


to merge legal enforceability with automated execution.
82
 Smart Legal Contracts: Templates provide the underlying technical Smart Contracts and
Ethereum
structure that can be enriched with legal terms.

3.4 ORACLES
Definition:

 An oracle is a trusted data feed or service that provides smart


contracts with information from the outside world (off-chain data).

 They act as a bridge between blockchain environments (closed


systems) and external data sources.

Purpose:

 Smart contracts alone can only access and act upon data available
within the blockchain.

 Oracles allow them to react to real-world events by importing


verified off-chain information.

 Enable more complex use cases, e.g., settlement based on market


prices, weather data, or sports scores.

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.

Examples of Use Cases:


● DeFi: Price feeds for decentralized exchanges and lending platforms.
● Insurance: Weather data for crop or travel insurance payouts.
● Gaming: Real-world sports scores triggering in-game events.
● Supply Chain: Tracking product location or temperature.
● Prediction Markets: Reporting event outcomes for bets or forecasts.

Relation to Smart Contracts:


● Smart contracts are deterministic and cannot directly fetch off-chain
data.
● Oracles act as trusted intermediaries to provide necessary external
inputs.
● Without oracles, many real-world blockchain applications would not
be possible.

3.5 DEPLOYING SMART CONTRACTS


● Deployment is the process of uploading a smart contract to the
blockchain so it becomes immutable, publicly accessible, and ready
for execution.
● Once deployed, the contract receives a unique address and operates
according to the programmed logic.

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.

3. Creating a Deployment Transaction


○ The bytecode and any constructor parameters are included in a special
transaction without a recipient address.
○ This transaction is signed with the developer’s private key.

4. Broadcasting the Transaction


○ The deployment transaction is sent to the blockchain network.

5. Mining/Validation
○ Miners or validators include the transaction in a block.

6. Contract Address Assignment


○ A unique contract address is generated based on the deployer’s
address and transaction nonce.

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.

Development and Deployment Tools:


● Remix IDE – Web-based Solidity editor and compiler.
● Truffle Suite – Framework for compiling, deploying, and testing
smart contracts.
● Hardhat – Development environment with debugging and testing
capabilities.
● Ganache – Local blockchain for testing deployments.

Step-by-step lifecycle (diagram steps explanation):


1. Write contract (Solidity / Vyper)
Design the contract’s API (functions, events, storage layout), pick
constructor parameters, and plan for security (access control, reentrancy
protection, input validation). Contracts are written in a high-level language
(Solidity or Vyper) before compilation.

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.

3. Prepare deployment transaction


A contract-creation transaction is sent with the contract bytecode (and
encoded constructor args). Unlike a normal transfer, the to field is
empty/zero for contract creation. Deployment also requires specifying gas
limit and gas price (or letting the provider estimate).

4. Sign transaction (wallet / private key)


The deployer signs the transaction with their private key (via a wallet or
programmatic signer). This ensures authenticity and lets the deployer pay
gas for deployment.
5. Broadcast to network (node / provider)
The signed tx is broadcast to an Ethereum node (Infura, Alchemy, local
Geth/Parity, or a dev node like Ganache). Tools/frameworks (Truffle,
Hardhat) wrap this process and manage migrations. Use testnets / local
chains for staging.

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).

7. Contract address assigned


When creation succeeds, the chain records the new contract at an address
deterministically derived from the deployer’s address and their nonce (so
the address can be predicted ahead of time). Save the address and the ABI
for interactions.

8. Verify & register (optional but recommended)


Many teams verify source code on explorers (e.g., Etherscan) so users can
read the source and confirm bytecode matches. Store build artifacts
(bytecode, ABI, metadata) and register the contract in your deployment
records.

9. Interact with contract (calls & transactions)


○ Calls (read-only, local) use the ABI and do not change chain state (no
gas).
87
Web3 Technologies ○ Transactions change state and require gas, are signed and broadcast
like deployments. Use web3 libraries ([Link], [Link]) or
frameworks (Truffle console) to interact.

10. Maintenance & best practices


● Test extensively on local chains and testnets; use migrations to
manage staged deployments.
● Audit contracts; apply gas optimizations carefully.
● Plan for immutability: use proxy patterns or migration plans if
upgrades are needed. Keep migration scripts, artifacts, and access
control policies documented.

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.

3.6 THE DAO


Introduction:
● The DAO (Decentralized Autonomous Organization) was a
pioneering experiment in decentralized governance and venture
funding, launched in 2016 on the Ethereum blockchain.
● Designed as a leaderless investment fund governed entirely by smart
contracts.
● Goal: Allow investors to pool ETH and vote on proposals for funding
projects, with returns distributed automatically.

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.

3. Smart Contract Execution


○ If a proposal passed, ETH would be released to the project’s smart
contract under predefined conditions.

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.

The DAO Hack (2016):


● Vulnerability: A recursive call exploit in the smart contract’s
withdrawal function.
● Exploit allowed attackers to drain funds before the contract updated
their balance.
● Result: About 3.6 million ETH was siphoned into a “child DAO”
controlled by the attacker.
● Ethereum community debated solutions:
○ Code-is-law advocates opposed intervention.
○ Others favored returning stolen funds to investors.

Hard Fork and Split:


● Majority of the Ethereum community voted to implement a hard fork
to reverse the hack and return funds.
● Hard fork created two blockchains:
○ Ethereum (ETH) – with the DAO funds restored.
○ Ethereum Classic (ETC) – continued the original chain without
intervention.

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.

3.7 ETHEREUM OVERVIEW


Introduction:
● Ethereum is a decentralized, open-source blockchain platform
designed for executing smart contracts and decentralized
applications (DApps).
● Proposed by Vitalik Buterin in 2013; development began in early
2014; mainnet launched in July 2015.
● Goes beyond Bitcoin’s transaction system by offering a Turing-
complete programming environment.
Core Features:
1. Smart Contracts
○ Self-executing code stored on the blockchain.
○ Automates transactions and agreements without intermediaries.
2. Ethereum Virtual Machine (EVM)
○ Turing-complete runtime environment.
○ Executes smart contract bytecode on every Ethereum node.
3. Ether (ETH)
○ Native cryptocurrency.
○ Used for transaction fees (gas) and as an incentive for
miners/validators.
4. Gas Mechanism
○ Prevents abuse and allocates network resources.
○ Gas fees are paid in ETH and vary by computational complexity.

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.

3.8 ETHEREUM NETWORK


Definition:
The Ethereum network is a decentralized peer-to-peer network of nodes
running Ethereum software, maintaining a shared, synchronized
blockchain state, and enabling the execution of smart contracts.

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.

Ethereum Account Types:


● Externally Owned Accounts (EOAs)
○ Controlled by private keys.
○ Used by humans or bots to send transactions.
92
● Contract Accounts Smart Contracts and
Ethereum
○ Controlled by smart contract code.
○ Execute automatically when triggered by a transaction.

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.

Public vs. Private Ethereum Networks:


● Mainnet
○ Public, production Ethereum network.
○ Real ETH with economic value.

● 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.

Role in the Ecosystem:


● Provides the backbone for all Ethereum-based DApps, DeFi
platforms, DAOs, NFTs, and other blockchain services.
● Ensures a shared, immutable ledger accessible to all participants.

3.9 COMPONENTS OF THE ETHEREUM ECOSYSTEM


Here are the core components of the Ethereum Network:

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.

Supporting Components of the Ethereum Network:


Here is an overview of the supporting components:
1. Ether (ETH)
2. Decentralized Applications (dApps)
3. Decentralized Finance (DeFi)
DeFi protocols are financial applications built on the Ethereum blockchain
that operate without traditional intermediaries.
1. Lending and Borrowing: Platforms like Aave and Compound allow
users to lend and borrow assets through smart contracts.
2. Decentralized Exchanges (DEXs): Protocols such as Uniswap and
SushiSwap facilitate token trading directly from users’ wallets
without a centralized entity.
3. Yield Farming: Users can earn rewards by providing liquidity to
various pools within these protocols.

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.

3.10 THE ETHEREUM VIRTUAL MACHINE (EVM)


The Ethereum Virtual Machine (EVM) is a decentralized computing
environment that executes smart contracts on the Ethereum Work. It
serves as the runtime environment for all Ethereum accounts and smart
contracts, allowing developers to deploy applications that can run on the
blockchain without requiring a central authority.
1. Decentralization: The EVM operates on a distributed network of
nodes, ensuring that no single entity controls the execution of
contracts.
2. Turing Completeness: The EVM is Turing complete, meaning it can
execute any computation that can be described algorithmically, given
sufficient resources.
3. Smart Contract Execution: When a smart contract is deployed, the
EVM handles the contract’s execution based on the inputs it receives,
managing state changes on the blockchain.
4. Gas Mechanism: To prevent abuse of resources, every operation in
the EVM requires a certain amount of "gas," a measure of
computational effort. Users pay gas fees to incentivize miners to
process their transactions.
5. Isolation: Each smart contract operates in isolation, which means that
the execution of one contract doesn’t directly affect the execution of
another.
96
6. State Management: The EVM maintains a global state, tracking the Smart Contracts and
Ethereum
current state of all accounts and contracts on the Ethereum network.

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.

How Does EVM Work?


The EVM works as follows-
1. Smart Contract Deployment: Developers write smart contracts in
high-level languages (like Solidity), which are compiled into EVM
bytecode. Contracts are deployed to the Ethereum network through
transactions.
2. Transaction Processing: Users create transactions to interact with
deployed contracts. These transactions are propagated to Ethereum
nodes.

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.

Architecture of the EVM


Here is an overview of the architecture of EVM:
1. Stack-Based Architecture: The EVM operates using a stack where
data is pushed and popped. Each stack can hold up to 1024 items,
enabling calculations and control flow during contract execution.
2. Memory: The EVM has a linear memory structure that provides
temporary storage for data during execution. This memory is cleared
after each transaction.
3. Persistent State: Each smart contract has its own storage, which is
persistent and stored on the blockchain. This allows contracts to
maintain their state between transactions.
4. Global State: The EVM maintains a global state that includes all
accounts (both externally owned and smart contracts) and their
balances, as well as the storage of each contract.
5. Instruction Set: The EVM has a set of predefined operations
(opcodes) that dictate how the machine processes data. These include
arithmetic operations, control flow instructions, and interactions with
memory and storage.
6. Gas Management: Each operation consumes gas, a resource that
measures computational work. The gas limit helps prevent excessive
resource usage and protects the network from spam attacks.
7. Execution Environment: The EVM is designed to ensure that
contract execution is deterministic, meaning that the same input will
always produce the same output across all nodes, ensuring consensus.

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.

EVM and Ethereum Blockchain:


The Ethereum Virtual Machine (EVM) and the Ethereum blockchain are
intrinsically linked, functioning together to enable decentralized
applications and smart contracts.
1. Smart Contract Execution: The EVM processes the logic contained
within smart contracts, allowing for automated and trustless
transactions directly on the blockchain.
2. State Management: The EVM maintains the global state of all
accounts and contracts, ensuring that data is consistent and accessible
across the network.
3. Transaction Processing: When a transaction is sent to the Ethereum
network, it is propagated to all nodes, which use the EVM to execute
the transaction. After execution, the results are validated by nodes
through consensus mechanisms (like Proof of Stake), ensuring that
only valid transactions are added to the blockchain.
4. Resource Management: The EVM uses a gas system to allocate
computational resources for transaction processing. Users pay gas
fees, which incentivize miners/validators to include transactions in the
blockchain.
5. Distributed Network: Both the EVM and the Ethereum blockchain
operate on a decentralized network of nodes, meaning no single entity
controls the system, enhancing security and trust.
6. Cross-Chain Compatibility: Many other blockchain networks are
EVM-compatible, allowing developers to deploy Ethereum-based
applications across multiple platforms.

Development of the EVM:


Developing the Ethereum Virtual Machine (EVM) involves creating smart
contracts and decentralized applications (DApps) that run on the Ethereum
blockchain.

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.

3. Testing and Debugging:


1. Unit Testing: Writing tests for smart contracts to ensure they function
as intended. Frameworks like Truffle and Hardhat provide testing
libraries.
2. Debugging Tools: Tools like Remix and Hardhat offer debugging
capabilities to trace errors in smart contracts during development.

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.

5. Interacting with Smart Contracts:


1. [Link]: A JavaScript library that allows web applications to interact
with the Ethereum blockchain, enabling communication with smart
contracts.
2. [Link]: A lightweight alternative to [Link] that also provides
easy interaction with Ethereum, including wallet management and
contract interaction.

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.

How Does Gas Relate Performance Of EVM?


1. Cost of Operations: Every operation in the EVM (like executing a
function or storing data) requires a specific amount of gas. This
creates a direct cost associated with computational resources,
incentivizing efficient coding.
2. Spam Prevention: The gas mechanism helps prevent network abuse
by requiring users to pay for the computational resources their
transactions consume. This discourages spamming the network with
unnecessary transactions.
3. Gas Price: Users can set gas prices to prioritize their transactions.
Higher gas prices may lead miners/validators to include a transaction
sooner, impacting overall transaction throughput on the network.
4. Gas Limit: Each block has a gas limit, which caps the total gas that
can be consumed by all transactions within that block. This limit
affects how many transactions can be processed in a given timeframe,
influencing overall network performance.
5. Smart Contract Optimization: Developers are motivated to write
efficient smart contracts that minimize gas consumption. More
efficient contracts can lead to lower fees and quicker execution times.
6. Scalability Issues: During periods of high demand, gas prices can
rise significantly, leading to higher transaction costs and delays. This
can affect the EVM’s overall performance and user experience.

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.

3.11 SMART CONTRACTS


A Smart Contract (or cryptocontract) is a computer program that directly
and automatically controls the transfer of digital assets between the parties
under certain conditions.
A smart contract works in the same way as a traditional contract while
also automatically enforcing the contract.
Smart contracts are programs that execute exactly as they are set up
(coded, programmed) by their creators.
Just like a traditional contract is enforceable by law, smart contracts are
enforceable by code.
The bitcoin network was the first to use some sort of smart contract by
using them to transfer value from one person to another.
The smart contract involved employs basic conditions like checking if the
amount of value to transfer is actually available in the sender account.

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.

Features of Smart Contracts:


The following are some essential characteristics of a smart contract:
1. Distributed: Everyone on the network is guaranteed to have a copy
of all the conditions of the smart contract and they cannot be changed
by one of the parties. A smart contract is replicated and distributed by
all the nodes connected to the network.
2. Deterministic: Smart contracts can only perform functions for which
they are designed only when the required conditions are met. The
final outcome will not vary, no matter who executes the smart
contract.
3. Immutable: Once deployed smart contract cannot be changed, it can
only be removed as long as the functionality is implemented
previously.
4. Autonomy: There is no third party involved. The contract is made by
you and shared between the parties. No intermediaries are involved
which minimizes bullying and grants full authority to the dealing
parties. Also, the smart contract is maintained and executed by all the
nodes on the network, thus removing all the controlling power from
any one party's hand.
5. Customizable: Smart contracts have the ability for modification or
we can say customization before being launched to do what the user
wants it to do.
6. Transparent: Smart contracts are always stored on a public
distributed ledger called blockchain due to which the code is visible to
everyone, whether or not they are participants in the smart contract.
7. Trustless: These are not required by third parties to verify the
integrity of the process or to check whether the required conditions
are met.
8. Self-verifying: These are self-verifying due to automated
possibilities.
9. Self-enforcing: These are self-enforcing when the conditions and
rules are met at all stages.

Capabilities of Smart Contracts:


1. Accuracy: Smart contracts are accurate to the limit a programmer has
accurately coded them for execution.

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.

Types of Smart Contracts


1. Smart Legal Contract:
There are legal guarantees for smart contracts. They follow the format
seen in contracts: "If this occurs, then this will occur." Legal smart
contracts provide more openness between contracting entities than
traditional documents because they are stored on blockchain and cannot be
altered. Contracts are executed by the parties using digital signatures. If
certain conditions are met, such as paying a debt when a predetermined
date is reached, smart legal contracts may operate on their own. If
stakeholders don't comply, there may be serious legal ramifications.

2. Decentralized Autonomous Organizations (DAOs):


DAOs are democratic organisations with voting powers granted by a smart
contract. A decentralised autonomous organisation, or DAO, is a
blockchain-based entity with a shared goal under collective governance.
There is no such thing as an executive or president. Instead, the
organization's operations and the distribution of assets are governed by
blockchain-based principles that are incorporated into the contract's code.
105
Web3 Technologies One example of this kind of smart contract is VitaDAO, which uses
technology to power a community dedicated to scientific inquiry.

3. Application Logic Contracts:


Application-based code that usually keeps up with multiple other
blockchain contracts makes up application logic contracts, or ALCs. It
permits device-to-device interactions such as blockchain integration and
the Internet of Things. These are signed between computers and other
contracts rather than between people or organisations like other kinds of
smart contracts.

How Do Smart Contracts Work?


A smart contract is just a digital contract with the security coding of the
blockchain.

 It has details and permissions written in code that require an exact


sequence of events to take place to trigger the agreement of the terms
mentioned in the smart contract.

 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:

 IF you send object A, THEN the sum (of money, in cryptocurrency)


will be transferred to you.

 IF you transfer a certain amount of digital assets (cryptocurrency, for


example, ether, bitcoin), THEN the A object will be transferred to
you.

 IF I finish the work, THEN the digital assets mentioned in the


contract will be transferred to me.

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

 Identify Agreement: Multiple parties identify the cooperative


opportunity and desired outcomes and agreements could include
business processes, asset swaps, etc.

 Set conditions: Smart contracts could be initiated by parties


themselves or when certain conditions are met like financial market
indices, events like GPS locations, etc.

 Code business logic: A computer program is written that will be


executed automatically when the conditional parameters are met.

 Encryption and blockchain technology: Encryption provides secure


authentication and transfer of messages between parties relating to
smart contracts.

 Execution and processing: In blockchain iteration, whenever


consensus is reached between the parties regarding authentication and
verification then the code is executed and the outcomes are
memorialized for compliance and verification.

 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.

Applications of Smart Contracts


1. Real Estate: Reduce money paid to the middleman and distribute
between the parties actually involved. For example, a smart contract
to transfer ownership of an apartment once a certain amount of
resources have been transferred to the seller's account(or wallet).
2. Vehicle ownership: A smart contract can be deployed in a blockchain
that keeps track of vehicle maintenance and ownership. The smart

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.

Example Use cases:


1. Smart contracts provide utility to other contracts. For example,
consider a smart contract that transfers funds to party A after 10 days.
After 10 days, the above-mentioned smart contract will execute
another smart contract which checks if the required funds are
available at the source account(let's say party B).
2. They facilitate the implementation of ‘multi-signature’ accounts, in
which the assets are transferred only when a certain percentage of
people agree to do so
3. Smart contracts can map legal obligations into an automated process.
4. If smart contracts are implemented correctly, can provide a greater
degree of contractual security.

Advantages of Smart Contracts:


1. Recordkeeping: All contract transactions are stored in chronological
order in the blockchain and can be accessed along with the complete
audit trail. However, the parties involved can be secured
cryptographically for full privacy.

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.

Challenges of Smart Contracts:


1. No regulations: A lack of international regulations focusing on
blockchain technology(and related technology like smart contracts,
mining, and use cases like cryptocurrency) makes these technologies
difficult to oversee.
2. Difficult to implement: Smart contracts are also complicated to
implement because it's still a relatively new concept and research is
still going on to understand the smart contract and its implications
fully.
3. Immutable: They are practically immutable. Whenever there is a
change that has to be incorporated into the contract, a new contract
has to be made and implemented in the blockchain.
4. Alignment: Smart contracts can speed the execution of the process
that span multiple parties irrespective of the fact whether the smart
contracts are in alignment with all the parties' intention and
understanding.

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.

 Smart contract templates are discussed as standardized, reusable


frameworks to simplify development and ensure consistency.

 The section on oracles highlights their function as data bridges


between blockchains and the outside world, detailing types such as
inbound, outbound, hardware, and software oracles.

 Deploying smart contracts is explained step-by-step, from writing


code to interacting post-deployment, emphasizing gas costs and
immutability.

 The chapter also covers The DAO — its objectives, governance


model, the 2016 hack, and the resulting Ethereum hard fork.

 An Ethereum overview introduces the blockchain’s design, smart


contracts, gas, and consensus mechanisms.

 The Ethereum network is examined in terms of nodes, accounts,


transactions, and public/private setups. Ecosystem components
include clients, the EVM, accounts, tokens, DApps, DAOs, and
development tools.

 The Ethereum Virtual Machine is presented as the execution


environment enabling deterministic, trustless computation.

 The chapter closes by reinforcing Ethereum’s role in enabling


decentralized applications.

3.13 EXERCISE WITH SOLUTION.(NOTE:


ELABORATE THE ANSWER USING GIVEN
POINTERS)
Q1. Explain the history and conceptual origin of smart contracts.

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:

 Dual readability (natural language + code)

 Digital signatures

 Secure hash linking to blockchain transactions

 Serving as both legal agreement and code execution basis


Q3. What are smart contract templates? State their advantages.

Answer:
Smart contract templates are standardized blueprints for creating recurring
blockchain agreements. Advantages include:

 Faster development

 Reduced coding errors

 Consistent legal and operational structure

 Reusability

 Easier auditing and regulatory compliance


Q4. Describe oracles and their importance in smart contracts.

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:

 Externally Owned Accounts (EOAs): Controlled by private keys,


used by individuals or bots to initiate transactions.

 Contract Accounts: Controlled by smart contract code, activated


when triggered by a transaction, cannot initiate without input.
Q9. Explain the structure of the Ethereum network.

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:

 Clients (Geth, Besu)


112
 EVM Smart Contracts and
Ethereum

 Accounts (EOAs, contract accounts)

 Smart Contracts

 Ether (ETH) and Gas

 Tokens (ERC-20, ERC-721, ERC-1155)

 DApps

 DAOs

 Oracles

 Development Tools (Remix, Truffle, Hardhat)


Q11. What is the Ethereum Virtual Machine (EVM), and why is it
important?

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.

4.2 WALLETS AND CLIENT SOFTWARE


Definition:
● Wallet: A tool (software, hardware, or paper) that stores and manages
cryptographic keys (private/public) used to interact with the Ethereum
network.

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.

2. Cold Wallets (offline storage):


○ Examples: Ledger, Trezor hardware wallets.
○ More secure but less convenient for frequent use.

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.

Popular Ethereum Clients:


● Geth (Go Ethereum) – Officially maintained by the Ethereum
Foundation.
● Nethermind – .NET-based Ethereum client.
● Hyperledger Besu – Java-based, enterprise-friendly.
● Erigon – Optimized for fast syncing and archival.

Interaction Between Wallets and Clients:


● Wallets use client software (local or remote) to broadcast signed
transactions.
● Light wallets connect to remote full nodes or use third-party
providers like Infura.

118
● DApps integrate wallets to sign and send transactions via web3 Ethereum And Ethereum
Development Environment
libraries.

4.3 NODES AND MINERS


Ethereum Nodes
● Definition: A node is any computer running Ethereum client
software, participating in the peer-to-peer (P2P) network by storing
blockchain data, verifying transactions, and relaying information.
● Nodes maintain the Ethereum state and ensure network integrity.

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.

Transition to Proof-of-Stake (PoS):


● Under Ethereum 2.0 (The Merge), miners are replaced by validators.
● Validators stake ETH and are selected to propose and attest to blocks.
● PoS reduces energy consumption and hardware requirements.

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.

4.4 APIS, TOOLS, AND DAPPS


4.4.1. APIs (Application Programming Interfaces):
APIs allow software applications to interact with the Ethereum blockchain
and its components.

Key Ethereum APIs:


1. JSON-RPC API:
○ Low-level interface for Ethereum clients.

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.

Popular Development Tools:


1. Remix IDE
○ Web-based Solidity IDE.
○ Supports compilation, deployment, and debugging.

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.

4.4.3 DApps (Decentralized Applications):


● Software applications running on a blockchain backend with smart
contracts.
● Frontend: Traditional web/mobile interface.
● Backend: Smart contracts on Ethereum.
● Data: Stored on-chain or via decentralized storage (IPFS, Swarm).

DApp Characteristics:
● Decentralized control — no single point of failure.
● Open-source code for transparency.
● Incentive systems via tokens.

Examples of Ethereum DApps:


● DeFi: Uniswap, Aave, Compound.
● NFTs: OpenSea, Rarible.
● Gaming/Metaverse: Axie Infinity, Decentraland.

4..4.4 Integration Flow:


1. Frontend (React, Vue, etc.)
2. Blockchain API ([Link], [Link])
3. Smart Contract Interaction (ABI, Ethereum address)
4. Ethereum Node Access (Local client or service like Infura)
5. Ethereum Network (Mainnet or testnets)

4.5 SUPPORTING PROTOCOLS


Supporting protocols are additional communication and data exchange
systems that work alongside the Ethereum main protocol to extend its
functionality, improve performance, or provide new capabilities.
Key Supporting Protocols in Ethereum

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.

c) IPFS (InterPlanetary File System):


● Purpose: Peer-to-peer hypermedia protocol for decentralized file
storage and sharing.

● Functionality:
○ Uses content-addressing (hashes) to identify and retrieve data.
○ Efficient distribution across nodes.

● Integration with Ethereum:


○ Smart contracts can store IPFS hashes to reference large off-chain
data.
○ Commonly used for NFTs and DApp assets.

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.

Role in Ethereum Ecosystem:


● Provide essential functionality not natively built into Ethereum’s core.
● Support scalability, storage, communication, and interoperability.
● Enable richer DApp functionality without overloading the main
blockchain.

4.6 PROGRAMMING LANGUAGES


● Ethereum smart contracts are written in high-level programming
languages designed for blockchain development, then compiled into
Ethereum Virtual Machine (EVM) bytecode.
● These languages are designed for determinism, security, and
compatibility with Ethereum’s architecture.

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.

c) LLL (Low-Level Lisp-like Language):


● Type: Low-level language similar to Lisp.
● Purpose: Offers fine-grained control of contract execution.
● Features:
○ Useful for optimization and minimal bytecode generation.
○ Steeper learning curve.

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.

Language Selection Criteria:


● Security requirements (Vyper for high-assurance contracts).
● Complexity (Solidity for feature-rich projects).
● Optimization needs (LLL, Yul for performance-critical code).
● Developer familiarity (syntax and tooling support).

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.

4.7 ETHEREUM DEVELOPMENT ENVIRONMENT:


OVERVIEW
The Ethereum development environment consists of the tools,
frameworks, libraries, and services used to create, test, deploy, and
maintain smart contracts and decentralized applications (DApps) on the
Ethereum network.

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.

6. APIs and Libraries:


○ [Link], [Link] — enable frontend and backend apps to
communicate with Ethereum nodes.

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.

Version Control and Collaboration:


● Git and GitHub/GitLab for source code management.
● Enables collaboration, issue tracking, and continuous integration.

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.

4.8 TEST NETWORKS


Definition
● Test networks (testnets) are alternative Ethereum blockchains used for
experimenting, testing, and developing smart contracts and DApps
without using real Ether or impacting the main Ethereum network.
● They mimic mainnet behavior but operate with valueless tokens.

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.

3. Legacy Testnets (Deprecated):


○ Ropsten: Proof-of-Work testnet, deprecated after Ethereum’s
Merge.
○ Rinkeby: Proof-of-Authority, deprecated.
○ Kovan: Proof-of-Authority, deprecated.

Getting Test Ether:


● Faucets: Websites that distribute free test ETH.
● Require wallet address and sometimes captcha/human verification.
● Example: Goerli Faucet, Sepolia Faucet.

Testnet vs Mainnet:

Feature Testnet Mainnet


Currency Test ETH (no value) Real ETH (market value)
Purpose Development & testing Production
Risk No financial risk Real financial risk
Network Load Lower, faster Higher, sometimes
congested

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.

● Options for private networks:


○ Proof-of-Authority (PoA) (e.g., Clique, IBFT) for fast block times.
○ Proof-of-Work (PoW) for mining simulation.
○ Custom consensus for specific enterprise needs.

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.

f) Smart Contracts and DApps:


● Can be deployed for internal use.
● Useful for supply chain, asset tracking, or internal payments.

g) Block Explorer:
● Tool for viewing transactions, blocks, and network state.
● Examples: Blockscout, custom explorers.

h) APIs and RPC Interfaces:


● Enable interaction with nodes via JSON-RPC, WebSocket.
● Allow integration with DApps and backend services.

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.

Advantages of Private Networks:


● Controlled participation and access.
● Customizable block time, gas limits, and rules.
● Safe for internal testing before public deployment.
● Enhanced privacy for sensitive transactions.

4.10 STARTING UP THE PRIVATE NETWORK


Steps to Set Up Private Ethereum Network
Below is the step-by-step guide to setting up a private Ethereum network.

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.

● While installing Geth make sure to select both checkboxes as shown


below.

● After installing Geth on your system open PowerShell or command


prompt and type geth and press enter, the following output will be
displayed.

132
Ethereum And Ethereum
Development Environment

Step 2: Create a Folder For Private Ethereum:


Ethereum
● Create a separate folder for this project. In this case,
case, the folder is
MyNetwork.
● Create a new folder inside the folder MyNetwork for the private
Ethereum network as it keeps your Ethereum private network files
separate from the public files. In this example folder is
MyPrivateChain.

Step 3: Create a Genesiss Block:


Block
The blockchain is a distributed digital register in which all transactions are
recorded in sequential order in the form of blocks. There are a limitless
number of blocks, but there is always one separate block that gave rise to
the whole chain i.e.. the genesis block.

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:

Step 5: Initialize the private network:


network
Launch the private network in which various nodes can add new blocks
for this we have to run the command-
command
geth --datadir \path_to_your_data_directory
path_to_your_data_directory\MyPrivateChain --networkid
networkid
8080

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.

Step 6: Create an Externally owned account(EOA)


Externally Owned Account(EOA) has the following features
features-
● Controlled by an External party or person.
● Accessed through private Keys.
● Contains Ether Balance.
● Can send transactions as well as 'trigger' contract
contract accounts.

Steps to create EOA are:


To manage the blockchain network, one need EOA. To create it, run Geth
in two windows. In the second window console enter the following
command-
geth attach \path_to_your_data_directory
path_to_your_data_directory\YOUR_FOLDER
YOUR_FOLDER\[Link]
or
geth attach \\.\pipe
pipe\[Link]
This will connect the second window to the terminal of the first window.
The terminal
inal will display the following:

136
Ethereum And Ethereum
Development Environment

Create an account by using the command-


command
[Link]()
After executing this command enter Passphrase and you will get your
account number and save this number for future use.

To check the balance status of the account execute the following


command-

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.

Step 7: Mining our private chain of Ethereum:


Ethereum
If we mine in the main chain of Ethereum it will require expensive
equipment with powerful graphics processors. Usually, ASICs are used for
this but in our chain high performance is not required and we can start
mining by using the following command-
command
[Link]()

If the balance status is checked after a couple of seconds the account is


replenished with fake ether. After that, one can stop mining by using the
following command-
[Link]()

4.11 MINING ON THE PRIVATE NETWORK


Mining in a private network is used to validate transactions and create new
blocks, simulating Ethereum’s Proof-of-Work
Proof (PoW) or Proof-of--
Authority (PoA) consensus
ensus in a controlled environment.

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)

1. Create and Fund Accounts:


Generate an account:
cpp
geth account new
○ Fund from genesis file or through transactions.

2. Start Geth in Mining Mode:


Example:
yaml
geth --networkid 2025 --mine --[Link]=1 --http --[Link] 8545
○ [Link] sets the number of CPU threads for mining.

3. Monitor Mining:
Attach to the console:
arduino
geth attach ipc:[Link]

Check mining status:


[Link]()
[Link]()
[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.

Mining Setup Steps (PoA Example – Clique)


1. Set Up Validators in Genesis
○ Include validator addresses in extraData field.

2. Run Validator Nodes


○ No high computational cost, blocks created in fixed intervals.

3. Block Creation
○ Validators take turns producing blocks according to configuration.

Use Cases in Private Networks:


● Testing DApps under mining conditions.
● Simulating transaction confirmations.
● Experimenting with block gas limits and difficulty settings.

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.

4.12 REMIX IDE


Steps to Execute Solidity Smart Contract using Remix IDE
Remix IDE is generally used to compile and run Solidity smart contracts.
Below are the steps for the compilation, execution, and debugging of the
smart contract.
Step 1: Open Remix IDE on any of your browsers, select on New File and
click on Solidity to choose the environment.

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.

Step 5: For debugging click on the Debug button corresponding to the


method call in the console. Here you can check each function call and
variable assignments.

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:

Step 2: Write the following


following sample code for testing and compile by
clicking on the compile button as shown:
// SPDX-License
License-Identifier: MIT
pragma solidity ^0.8.17;
// Creating a contract
contract shreyansh_05
{
// Defining a function
function get_output() public pure returns
returns (string memory){
return ("Hi, your contract ran successfully");
}
}

Compile the [Link] file

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 -

Select the Injected Provider - Metamask


Step 4: Now your contract is ready to be deployed. Click on deploy button
and the MetaMask will ask for confirmation as follows –
145
Web3 Technologies

Click the Confirm Button


Step 5: After confirmation, the deployed contract will look like –

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.

4.14 USING METAMASK AND REMIX IDE TO DEPLOY


A SMART CONTRACT
MetaMask and Remix IDE are two essential tools for Ethereum smart
contract development and deployment:
● MetaMask: A browser extension wallet used to interact with the
Ethereum blockchain, manage accounts, and sign transactions
securely.
● Remix IDE: A web-based Ethereum Integrated Development
Environment that allows you to write, compile, test, and deploy
Solidity smart contracts.
Combining MetaMask and Remix IDE provides a complete environment
for developing, testing, and deploying smart contracts on Ethereum
testnets or the mainnet.
Setting up MetaMask
MetaMask is a cryptocurrency wallet and gateway to blockchain
applications, available as:
● Browser extensions (Chrome, Firefox, Brave, Edge)
● Mobile apps (Android, iOS)

Features:
● Manage Ethereum accounts and keys
● Send/receive ETH and tokens
● Connect to decentralized applications (DApps)
● Switch between Ethereum mainnet, testnets, or custom networks

Installation and Configuration:


1. Install MetaMask Extension:
○ Go to the official MetaMask website
○ Install the browser extension

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

4. Fund with Test ETH:


○ Use a faucet to get free ETH for testing
○ Example: Sepolia Faucet
Using Remix IDE

Remix IDE is a browser-based Solidity development environment:


● Write Solidity smart contracts
● Compile contracts
● Deploy and interact with them
● Debug and test
Website: [Link]

Key Sections of Remix IDE:


● File Explorer – Create, open, and manage Solidity files (.sol)
● Solidity Compiler – Compile contracts and check for errors
● Deploy & Run Transactions – Deploy contracts to various
environments
● Terminal/Console – View transaction logs, compilation messages
Writing a Simple Smart Contract
Example: [Link]
solidity
// SPDX-License-Identifier: MIT
150
pragma solidity ^0.8.0; Ethereum And Ethereum
Development Environment
contract HelloWorld {
string public message = "Hello, Ethereum!";
function setMessage(string memory newMessage) public {
message = newMessage;
}
}

Steps in Remix:
1. Create new file [Link]
2. Paste the contract code
3. Save the file

Compiling the Contract in Remix:


1. Go to Solidity Compiler tab
2. Select compiler version (e.g., 0.8.0)
3. Click Compile [Link]
4. Check for compilation success or errors

Connecting Remix to MetaMask:


1. Open MetaMask and ensure you are on the correct network (e.g.,
Sepolia testnet)
2. In Remix:
○ Go to Deploy & Run Transactions
○ Under Environment, select Injected Provider - MetaMask

3. Allow Connection:
○ MetaMask will prompt you to connect
○ Select your account and approve

Deploying the Smart Contract:


1. Ensure correct contract is selected in the Remix Contract dropdown
2. Click Deploy
3. MetaMask will open a transaction confirmation popup
151
Web3 Technologies 4. Review gas fees and click Confirm
5. Wait for transaction confirmation on the blockchain
6. Deployed contract appears in the Deployed Contracts section

Interacting with the Deployed Contract:


● Use the buttons under the deployed contract in Remix
● Example:
○ message (getter) – Reads the current message
○ setMessage – Sets a new message (triggers a MetaMask transaction)
● Each state-changing function requires:
○ A blockchain transaction
○ Gas fees
○ MetaMask confirmation

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.

4.16 EXERCISE WITH SOLUTION.(NOTE:


ELABORATE YOUR ANSWER AS PER GIVEN
POINTERS.)
Q1. Explain the structure of an Ethereum block.
Answer:
An Ethereum block consists of:
● Block Header: Includes Parent Hash (link to previous block),
Ommers Hash, Beneficiary Address, State Root, Transactions Root,
Receipts Root, Logs Bloom, Difficulty, Number, Gas Limit, Gas
Used, Timestamp, Extra Data, Mix Hash, and Nonce.
● Transactions: A list of state-changing operations.
● Ommers (Uncles): Valid blocks mined almost simultaneously but
excluded from the main chain.
The block structure ensures immutability, verifiability, and consensus
compliance.

Q2. Differentiate between hot wallets and cold wallets in Ethereum.


Answer:
● Hot Wallets: Connected to the internet (e.g., MetaMask,
MyEtherWallet). Offer convenience for frequent transactions but are
more vulnerable to hacking.
● Cold Wallets: Offline storage (e.g., Ledger, Trezor hardware
wallets). Highly secure for long-term storage but less convenient for
everyday use.
Both store private/public keys, not Ether directly, and are used to sign
transactions and interact with smart contracts.

Q3. Describe the role of nodes in the Ethereum network.


Answer:
Nodes run Ethereum client software and maintain the blockchain by:
● Storing the blockchain data.
154
● Verifying transactions and smart contract execution. Ethereum And Ethereum
Development Environment
● Propagating transactions and blocks.
● Executing EVM code.
Types include full nodes (store complete blockchain), light nodes (store
headers only), and archive nodes (store all historical states). Nodes ensure
network integrity and decentralization.

Q4. Outline the mining process in Ethereum’s Proof-of-Work system.


Answer:
1. Collect pending transactions from the mempool.
2. Verify transaction validity and gas payments.
3. Assemble a candidate block with transactions, ommers, and
metadata.
4. Perform Ethash PoW to find a nonce meeting the difficulty target.
5. Broadcast the block to peers.
6. Receive block rewards, uncle rewards, and transaction fees.
Mining secures the network by making block creation computationally
costly.

Q5. List and explain key Ethereum development tools.


Answer:
● Remix IDE: Web-based Solidity IDE for writing, compiling, and
deploying smart contracts.
● Truffle Suite: Framework for smart contract development, testing,
and migration; includes Ganache.
● Hardhat: Advanced environment with debugging and mainnet
forking.
● Ganache: Local Ethereum blockchain for testing.
● MythX/Slither: Security analysis tools for detecting vulnerabilities.

Q6. What is IPFS and how is it integrated with Ethereum?


Answer:
IPFS (InterPlanetary File System) is a decentralized storage protocol
using content addressing via hashes.
Integration with Ethereum:
155
Web3 Technologies ● Large data stored off-chain in IPFS.
● Only the hash (CID) is stored in a smart contract.
● Used in NFTs, DApp assets, and decentralized websites.
This reduces blockchain storage costs while retaining verifiable access to
the data.

Q7. Compare Solidity and Vyper programming languages.


Answer:
● Solidity: Most popular, feature-rich language inspired by JavaScript,
C++, and Python. Supports inheritance, libraries, modifiers, and
events.
● Vyper: Python-like syntax, minimal features for better security and
auditability, excludes inheritance/modifiers.
Choice depends on project complexity and security requirements.

Q8. Explain the purpose of Ethereum test networks.


Answer:
Testnets simulate the Ethereum mainnet without real ETH. Purposes:
● Risk-free smart contract testing.
● Deployment script verification.
● DApp integration trials.
Examples: Goerli (multi-client PoS), Sepolia (fast sync). Test ETH is
acquired via faucets. Testnets avoid financial risk and prepare projects for
mainnet deployment.
Q9. Describe the steps to set up a private Ethereum network.
Answer:
1. Install Geth.
2. Create project folders.
3. Create a genesis block JSON file.
4. Initialize with geth init.
5. Launch private network with a custom network ID.
6. Create EOAs.
7. Start mining (PoW or PoA).
156
A private network allows controlled participation, custom rules, and Ethereum And Ethereum
Development Environment
internal DApp deployment.
Q10. How do you deploy a smart contract using MetaMask and
Remix IDE?
Answer:
1. Install MetaMask and set up a testnet account with faucet ETH.
2. Open Remix IDE, write and compile the smart contract.
3. Select Injected Provider – MetaMask in the Deploy section.
4. Confirm MetaMask’s connection prompt.
5. Click Deploy and approve the transaction in MetaMask.
6. Interact with the deployed contract via Remix.
This method integrates wallet-based signing with a development IDE for
seamless deployment.
Q11. What are Layer-2 protocols and why are they important for
Ethereum?
Answer:
Layer-2 protocols operate on top of Ethereum to increase throughput and
reduce gas costs.

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.

5.1 INTRODUCTION TO WEB3


Web3 refers to the next evolution of the internet, built on decentralized
technologies. It moves away from centralized platforms and services
(Web2) and leverages blockchain, smart contracts, and peer-to-peer
networks.

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.

5.1.2 Why is Web3 important?


Ownership:
 Web3 gives you ownership of your digital assets in an unprecedented
way. For example, say you're playing a web2 game. If you purchase
an in-game item, it is tied directly to your account. If the game
creators delete your account, you will lose these items. Or, if you stop
playing the game, you lose the value you invested into your in-game
items.
 Web3 allows for direct ownership through non-fungible tokens
(NFTs). No one, not even the game's creators, has the power to take
away your ownership. And, if you stop playing, you can sell or trade
your in-game items on open markets and recoup their value.

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.

 DAOs are defined technically as agreed-upon smart contracts that


automate decentralized decision-making over a pool of resources
(tokens). Users with tokens vote on how resources get spent, and the
code automatically performs the voting outcome.
 However, people define many Web3 communities as DAOs. These
communities all have different levels of decentralization and
automation by code.

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.

5.1.3 Limitations of Web3:


1. Accessibility:
Important Web3 features, like Sign-in with Ethereum, are already
available for anyone to use at zero cost. But, the relative cost of
transactions is still prohibitive to many. Web3 is less likely to be utilized
in less-wealthy, developing nations due to high transaction fees. On
Ethereum, these challenges are being solved through the
roadmap and layer 2 scaling solutions. The technology is ready, but we

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:

Web3 introduces new paradigms that require learning different mental


models than the ones used in Web2.0. A similar education drive happened
as Web1.0 was gaining popularity in the late 1990s; proponents of the
world wide web used a slew of educational techniques to educate the
public from simple metaphors (the information highway, browsers, surfing
the web) to television broadcastsopens in a new tab. Web3 isn't difficult,
but it is different. Educational initiatives informing Web2 users of these
Web3 paradigms are vital for its success

4. Centralized infrastructure:

The Web3 ecosystem is young and quickly evolving. As a result, it


currently depends mainly on centralized infrastructure (GitHub, Twitter,
Discord, etc.). Many Web3 companies are rushing to fill these gaps, but
building high-quality, reliable infrastructure takes time.

5.1.4 Exploring web3 with Geth(Generation of web3):

1. Web 1.0: Read-Only (1990-2004):

In 1989, at CERN, Geneva, Tim Berners-Lee was busy developing the


protocols that would become the World Wide Web. His idea? To create
open, decentralized protocols that allowed information-sharing from
anywhere on Earth.

The first inception of Berners-Lee's creation, now known as 'Web 1.0',


occurred roughly between 1990 to 2004. Web 1.0 was mainly static
websites owned by companies, and there was close to zero interaction
between users - individuals seldom produced content - leading to it being
known as the read-only web.

161
Web3 Technologies

2. Web 2.0: Read-Write (2004-now):


The Web 2.0 period began in 2004 with the emergence of social media
platforms. Instead of a read-only, the web evolved to be read-write.
Instead of companies providing content to users, they also began to
provide platforms to share user-generated content and engage in user-to-
user interactions. As more people came online, a handful of top companies
began to control a disproportionate amount of the traffic and value
generated on the web. Web 2.0 also birthed the advertising-driven revenue
model. While users could create content, they didn't own it or benefit from
its monetization.

3. Web 3.0: Read-Write-Own:


The premise of 'Web 3.0' was coined by Ethereum co-founder Gavin
Wood shortly after Ethereum launched in 2014. Gavin put into words a
solution for a problem that many early crypto adopters felt: the Web
required too much trust. That is, most of the Web that people know and
use today relies on trusting a handful of private companies to act in the
public's best interests.

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.6 Contract deployment:


Contract deployment is a special Ethereum transaction sent to the address
0. It creates bytecode at a specific address, which creates a smart contract
account. Contracts are deployed at predictable addresses based on the
address and nonce of the account creating the contract. To deploy a smart
contract, you merely send an Ethereum transaction containing the
compiled code of the smart contract without specifying any recipient.
 Contract deployment is a special Ethereum transaction sent to the
address 0.
 The deployment has the side effects of creating bytecode at a specific
address (i.e, it creates a smart contract account).
 Contracts are deployed at predictable addresses based on the address
and nonce of the account creating the contract.
The Ethereum network has only one transaction mechanism, which is
overloaded to handle three distinct kinds of transactions:
 A simple ether transfer to an externally owned account
 Invocation of code associated with a previously deployed smart
contract (and possibly an ether transfer).
163
Web3 Technologies  Deployment of a smart contract (and possibly an ether transfer to the
corresponding deployed contract).
 Contract deployment is by far the most subtle operation. To
understand it, let’s review the components of a transaction message:
 recipient
 value
 data
 gas limit
 gas price
 nonce
 signature
For contract deployment, there is nothing unique about the value (attached
ether), the gas limit and price, the nonce, or the signature. The recipient
and the data, however, are special:
 recipient For contract deployment, the recipient address is 0. This
signifies that the transaction creates a contract.
 data For contract deployment, the data field holds code to be
executed during deployment.

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.

5.1.8 Contract Initialization:


The data field of a contract deployment transaction is code to be executed
during contract initialization. It is not the code that is executed on
subsequent transactions sent to the contract. That code is returned by the
initialization code. Essentially, the code in the data field is a program that
is going to write a program that gets deployed as a smart contract.
Although that sounds fairly open-ended and complex, in practice it is
164
typically quite straightforward. The standard initialization code generated Web3, Serenity, Ethereum
by the Solidity compiler does the following:
1. Runs the code in the contract’s constructor, setting storage values, etc.
2. Copies the code for the rest of the contract into memory and returns it.
The code to be copied is simply appended to the constructor’s code in the
data field.
Constructor parameters are handled similarly. They are stored last in the
data field, and the initialization code reads them from there.

5.1.8.1interacting with contracts via frontend:


To interact with a smart contract via the frontend, follow these steps:
 Set Up Your Environment: Use frameworks like React or [Link] to
create a frontend application. Ensure you have the necessary libraries
installed, such as [Link] or [Link].
 Connect to the Smart Contract: Use the smart contract's contract
address to interact with it. This involves reading data from the
blockchain and managing transactions.
 User Interaction: Implement user interfaces that allow users to
interact with the smart contract, such as submitting data or sending
transactions. This can be done using libraries like MetaMask or
Wallet Connect.
 Real-Time Updates: Use event listeners to manage real-time updates,
ensuring that the frontend reflects the latest state of the smart
contract.
 Testing and Deployment: Test your integration thoroughly and
deploy your frontend application to interact with the smart contract.
These steps will help you create a seamless interaction between your
frontend application and a smart contract.
Interacting with Hyperledger Sawtooth smart contracts from a
frontend involves connecting your web application to the Sawtooth
REST API, signing transactions with a user's private key, and submitting
them to the blockchain.
Unlike Ethereum, Sawtooth doesn’t use the EVM or Solidity—it uses
transaction families and transaction processors written in languages like
Python, Rust, or Go. So interacting from a frontend requires handling the
custom transaction format, signing, and encoding.

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] What is Ethereum 2.0?


Ethereum 2.0 is not a new blockchain but rather a set of interconnected
upgrades to the existing Ethereum network. These upgrades aim to
enhance the network’s scalability, security, and sustainability without
compromising on decentralization.

The main components of Ethereum 2.0 include:


1. The Beacon Chain
2. The Merge
3. Sharding

1. The Beacon Chain: The Backbone of Ethereum 2.0:


Key Point: The Beacon Chain is the cornerstone of Ethereum 2.0.
Launched on December 1, 2020, it introduced the Proof-of-Stake (PoS)
consensus mechanism to the Ethereum ecosystem.

Key features of the Beacon Chain:


 Coordinates the network of stakers
 Manages the registry of validators
 Implements the PoS consensus mechanism
Key Point: The introduction of PoS is a game-changer for Ethereum.
Unlike the energy-intensive Proof-of-Work (PoW) system, PoS allows
participants to validate transactions and create new blocks based on the
amount of cryptocurrency they “stake” as collateral.

2. The Merge: A Milestone in Crypto History:


Key Point: The Merge was arguably the most significant event in
Ethereum’s history since its creation. Completed on September 15, 2022,
it marked the joining of the original Ethereum mainnet with the Beacon
Chain, officially transitioning Ethereum from PoW to PoS.

Benefits of The Merge:


 99.95% reduction in energy consumption
166
 Laying the groundwork for future scaling solutions Web3, Serenity, Ethereum

 Potential for increased security and decentralization


Key Point: The successful completion of The Merge was a testament to
the Ethereum community’s ability to coordinate and execute complex
upgrades on a live, high-value network.

3. Sharding: The Key to Scalability:


Key Point: While The Merge brought significant improvements, the next
major upgrade on the Ethereum 2.0 roadmap is sharding. Sharding is a
scaling solution that involves splitting the network into multiple segments
(shards) that can process transactions and smart contracts in parallel.
How sharding works:
1. The network is divided into 64 shard chains
2. Each shard processes its own set of transactions and smart contracts
3. The Beacon Chain coordinates all the shards, ensuring they remain in
sync

[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.

[Link]. History of Ethereum 2.0:

Date Event Description

Ethereum 1.0 launches with


its Proof of Work consensus
Ethereum Launch mechanism and the
Ethereum Virtual Machine
July 2015 (EVM).

December Ethereum 2.0 Ethereum Foundation


2017 Announcement announces Ethereum 2.0.

Development starts on the


Beacon Chain Beacon Chain, the PoS
January Development Begins blockchain coordinating
2018 Ethereum 2.0.

Ethereum 2.0 research


Eth2 Research Phase
phases reach important
Completion
June 2019 milestones.

January Launch of the first Ethereum


First Eth2 Testnet Launch
2020 2.0 testnet (Medalla).

December 1, Beacon Chain goes live as


Beacon Chain Launch
2020 Phase 0 of Ethereum 2.0.

168
Web3, Serenity, Ethereum
Date Event Description

Altair, the first upgrade to


the Beacon Chain, is
Altair Upgrade
December implemented to improve
2021 performance and fix issues.

Shapella upgrade adds the


Shapella Upgrade
ability to withdraw staked
(Shanghai/Capella)
June 2022 ETH.

The Merge integrates


Ethereum 1.0 and Ethereum
Merge Event
September 2.0 by transitioning
2022 Ethereum from PoW to PoS

Ethereum 1.0 and 2.0 begin


operating together
Phase 1.5 Introduction
seamlessly, marking the
2023 transition to full PoS.

Full implementation of shard


Phase 2 and Full Sharding chains and the execution
Rollout engine, completing
2024 Ethereum 2.0's upgrade.

[Link] Phases of Ethereum 2.0:


The phases of Ethereum 2.0, also known as Serenity, are designed to
enhance the network's scalability, security, and efficiency. The upgrade
will be rolled out in phases, each introducing new features and
improvements. Here are the key phases of Ethereum 2.0:
1. Phase 0: Introduction of the Beacon Chain, which implements the
Proof of Stake (PoS) consensus mechanism. This phase establishes
the foundation for PoS and begins the transition from Proof of Work
(PoW) to PoS.
2. Phase 1: Introduction of Shard Chains, which improve scalability by
splitting the Ethereum network into multiple smaller chains (shards)
that can process transactions and data in parallel.

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.

 Functions: Finalize scalability enhancements and support advanced


smart contract functionalities.

[Link]. Architecture of Ethereum 2.0:

Here is an overview of the architecture 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.

3. Execution Layer: ensure layer handles the execution of smart


contracts and transactions. It includes the Ethereum Virtual Machine
(EVM) or eventually eWASM for enhanced performance.

4. Proof of Stake (PoS): PoS is the consensus mechanism replacing


Proof of Work (PoW). In this, validators stake ETH to propose and
validate blocks, earning rewards and facing penalties for misconduct.

5. Slashing and Penalties: Slashing and Penalties ensure network


security and integrity. Validators can lose a portion of their staked
ETH (slashing) or face penalties for being offline or misbehaving.

6. Cross-Chain Communication: Cross-chain communication


facilitates interaction between the Beacon Chain, shard chains, and
Ethereum 1.0. It ensures smooth transactions and data sharing across
different chains.

7. Client Software: Client software allows participants to interact with


the Ethereum 2.0 network. It includes Beacon Chain clients, shard
chain clients, and execution layer clients.

171
Web3 Technologies

Fig:[Link]. Architecture of Ethereum 2.0


[Link]. Benefits of Ethereum 2.0:

There are several benefits associated with Ethereum 2.0, which is also
known as Serenity.

1. Improve Scalability: Ethereum 2.0 helps to improve scalability by


moving from the Proof-of-Work consensus algorithm to a Proof-of-
Stake algorithm. This allows more transactions to be processed on the
Ethereum network without running into the same scalability issues
that have plagued other blockchain networks.

2. Improve Security: Ethereum 2.0 helps to improve security by


making it more difficult for bad actors to 51% attack the network.
This is because Proof-of-Stake requires participants to lock up a
significant amount of their Ether to participate in block validation,
which disincentivizes attacks on the network.

3. Reduce Costs: Ethereum 2.0 helps to reduce costs by reducing the


amount of energy required to run the network.

4. Improved Efficiency: Ethereum 2.0 is expected to improve the


efficiency of the Ethereum network by reducing the amount of energy
required to process transactions.

5. More Decentralized: Ethereum 2.0 is more decentralized than the


current Ethereum network, as it has more nodes.

6. More Flexible: Ethereum 2.0 is more flexible than the older


Ethereum network, as it can support a wider range of applications.

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:

Ethereum 2.0, also known as Eth2 or “Serenity,” is an upgrade to the


Ethereum blockchain. It aims to enhance the speed, efficiency, and
scalability of the Ethereum network by shifting from a proof-of-work
(PoW) algorithm to a proof-of-stake (PoS) model.

Ethereum is a decentralized blockchain with smart contract functionality.


Ether is the native cryptocurrency of the platform. Among
cryptocurrencies, ether is second only to bitcoin in market capitalization. It
is open-source software.

5.3 SERENITY

5.3.1 What is Serenity?

Serenity is a blockchain-powered platform helping individuals and


businesses to protect their sensitive data with our patent pending
[Link] is revolutionizing secure data storage and access
through decentralized blockchain solutions. Our suite of products is built
to empower individuals and enterprises with complete control over their
digital assets.

Serenity is committed to revolutionizing data security by offering multi-


chain solutions customize for both Web2 and Web3 users.

The future of digital privacy is being driven by Serenity, which offers a


suite of secure and scalable solutions for data access, storage, and
recovery.

Serenity Shield's web3 data storage solution will allow this content to be
uploaded and permanently saved.

Serenity is the codename for Ethereum 2.0, a major upgrade to the


Ethereum blockchain that aims to improve scalability, security, and
energy efficiency. It represents a shift from the original Ethereum
network's consensus mechanism (Proof of Work) to a new one called
Proof of Stake (PoS).

Serenity, also widely known as Ethereum 2.0 or Eth2, represents a


significant and complex series of upgrades to the Ethereum blockchain.
The primary goals of Serenity are to enhance the network’s scalability,
allowing it to process a much larger number of transactions per second;
improve its security against various attacks; and increase its sustainability
by transitioning its consensus mechanism.

173
Web3 Technologies 5.3.2. Importance of Serenity:

1. Bridges the Gap Between Business and Technical Teams:

 Serenity integrates seamlessly with Cucumber, allowing tests to be


written in Gherkin (natural language).

 This makes it easier for non-technical stakeholders (like business


analysts or product owners) to understand and contribute to the test
cases.

2. Improves Test Clarity and Reusability:

 Tests are structured into steps, tasks, and actions, making them easier
to maintain and read.

 Supports Screenplay Pattern, which encourages reusable components


and clean separation of concerns.

3. Supports Multiple Test Types:

 Web UI tests (via Selenium WebDriver)

 REST API tests (via RestAssured)

 Database checks

 Integration with JUnit, TestNG, and Cucumber

4. Promotes Best Practices in Test Automation:

 Encourages modularity, reusability, and abstraction through the


Screenplay and Page Object models.

 Reduces code duplication and enhances test stability.

5. Supports Agile and Continuous Delivery:

 Aligns with Agile practices by tying tests to user stories or


requirements.

 Easy integration with CI/CD pipelines (e.g., Jenkins, GitLab CI).

5.3.3. Uses of Serenity:

1. Automated Acceptance Testing:

Serenity is primarily used for writing acceptance tests that verify if a


system behaves as expected based on business requirements.

174
2. Behavior-Driven Development (BDD): Web3, Serenity, Ethereum

Serenity integrates with Cucumber, allowing you to write tests in Gherkin


syntax (Given, When, Then), which non-developers can read and
understand.

3. Web UI Testing (with Selenium WebDriver):

You can use Serenity to automate browser-based tests with Selenium,


including handling forms, navigation, assertions, and user flows.

4. REST API Testing:

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:

Serenity supports running tests across different browsers (e.g., Chrome,


Firefox, Edge) using Selenium Grid or tools like Sauce Labs or
BrowserStack.

5.3.4 Architectureof Serenity:

[Link]. Main Components of Serenity Architecture:


1. Feature Files (Optional - BDD Only):
 Written in Gherkin syntax (Given, When, Then).
 Define scenarios based on user stories or requirements.
 Located under src/test/resources/features/.

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.

3. Tasks / Actions (Screenplay Pattern):


 Describe high-level business actions (e.g., [Link](User)).
 Reusable and readable test logic.

4. Page Objects / Interactions


 Encapsulate the structure and behavior of UI elements.
 Use Selenium WebDriver under the hood.

5. Drivers / API Clients


 Handles actual interaction with:
o Web browsers (via Selenium WebDriver)
o REST APIs (via Rest-Assured)
o Databases or other systems

6. Serenity Core & Report Generator


 Collects metadata during test execution:
o Steps performed
o Screenshots
o Pass/fail results
o Requirements coverage
 Generates HTML, JSON, and XML reports.

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.

5.5.1. Multiple Choice Questions:


1. Which year was Blockchain technology created?
a) 2008.
b) 2009.
c) 2010.
d) 2015.
2. Which year was Ethereum created?
a) 2017.
b) 2018.
c) 2015.
d) 2020.
3. Which among the following is a difference between Bitcoin and
Ethereum?
a) Ethereum uses PoS while Bitcoin uses PoW.

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

9. Which of these is a synonym of "serenity"?


a) Anger
b) Peacefulness
c) Disturbance
d) Chaos
10. In which context is "serenity" most appropriate?
a) A busy marketplace
b) A quiet mountain landscape
c) A noisy party
d) A hectic city street

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.

6.1 INTRODUCTION TO HYPERLEDGER


Hyperledger is an open-source collaborative project hosted by the
Linux Foundation that aims to advance cross-industry blockchain
technologies. It provides a framework for developing enterprise-grade,
permissioned blockchain networks.

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.

2. Smart Contract Layer:


 The smart contract layer verifies each transaction by guaranteeing that
it adheres to the transaction's policy and contract and invalid
transactions are denied and may be removed from consideration for
inclusion in a block.
 Smart contracts are classified into two types:
o installed smart contracts- Before the network is launched, installed
smart contracts implement business logic on the validators.
o On-chain smart contracts- On-chain smart contracts implement
business rules in the form of a transaction that is committed to the
181
Web3 Technologies blockchain and then invoked by subsequent transactions. The code
that describes the business logic forms part of the ledger with on-
chain smart contracts.
 Responsible for executing transaction requests and determining
transaction validity through the use of business logic.
 In Hyperledger Fabric, a smart contract is a program known as
chaincode. Chaincode can be developed in Go, JavaScript (node. js),
and, in the future, additional programming languages such as Java that
define a predefined interface. Chaincode is run in a secure Docker
container that is separate from the endorsing peer process.

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.

4. Data Store Abstraction:


 Allows other modules to use alternative data stores.
 the actual private data is kept in a private database on authorized
organizations' peer nodes and accessed via chaincode on these
authorized peers; and a hash of the secret data, which has been
endorsed, sorted, and recorded to the ledgers of every peer on the
channel.
 As state databases, the Hyperledger fabric supports LevelDB and
CouchDB. LevelDB is the default state database integrated into the
peer activity and stores chaincode data as key-value pairs.
 CouchDB is an optional external state database that adds query
capability when your chaincode data is modeled as JSON, allowing
for rich queries of the JSON content.
 When a deploy transaction succeeds, the chaincode is installed "on"
the blockchain.

182
5. Crypto Abstraction: Hyperledger & tokenization

 Allows for the substitution of alternative crypto techniques or


modules without disrupting other modules.
 Because Fabtoken, a new functionality in Hyperledger Fabric
version 2.0 (alpha), allows you to generate native cryptocurrencies
or coins.
 Besu Hyperledger is a public Ethereum codebase that is open source
and may run on individual permissionless platforms or the Ethereum
public network. The Ethereum Virtual Machines (EVM), consensus
mechanisms, user-facing APIs, and monitoring are all included.
 CPU and GPU mining is supported by Hyperledger Besu and can be
enabled using command-line arguments. Ethminer with both the
stratum+tcp and getwork schemes was utilized for GPU mining
support testing.
 It does not support cryptocurrencies such as bitcoin, but it functions
by providing the infrastructure and standards required for the
development of various blockchain-based applications and systems
for industrial usage.

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. Productivity Enhancement: To accelerate project development,


Hyperledger employs the division of labor technique. It determines
everyone's strong suits and, based on that, places them in specialized
fields.
2. Handling Of Intellectual Property: Hyperledger functions as a
blockchain greenhouse by bringing vendors, developers, and
consumers from all around the world together on a single platform.
3. Data On A Need-To-Know Basis: Data partitioning on the
blockchain allows for the privacy of data pieces. It provides physical
isolation of sensitive data. Hyperledger-supported channels allow
data to be distributed exclusively to people that need to know.
4. Rich Querying Capability: It is made up of a key-value database.
CouchDB is also an option. It is a document database that stores
content in JSON format. This allows for simple database queries. Its
data model works with the current key/value programming
approach.
5. Anonymity: The network only allows signature read-write sets to
pass through. This helps to ensure anonymity because only the
users and peers committing the transactions can see the transactions.

[Link] Limitations of Hyperledger Architecture:


1. Lack of Developers: It lacks highly qualified programmers due to
its origin, whereas Ethereum has a greater number of developers
because of its popularity.
2. Lack of use-cases: It has shown a lack of use cases such that more a
lack of awareness of technology and its possibilities, a scarcity of
personnel and skill sets in IT and business.
3. Complex architecture: It has a sophisticated design, while
Hyperledger, which is backed by IT titans, is only focused on
enterprise transaction-based [Link]
4. Minimum APK: API allows client apps to communicate with
Hyperledger Fabric blockchain network smart contracts, but with
fewer APIs.
5. Less fault tolerance: The job of Byzantine fault tolerance is to
ensure that each peer has the same list of transactions on its ledger,
however, it is not suited for network use.

[Link] Application of Hyperledger


1. Finance: Hyperledger can be used to streamline the settlement of
transactions, improved liquidity, and provide increased transparency
185
Web3 Technologies by eliminating the need for accounts on particular payment systems
at a low cost.
2. Healthcare: Hyperledger can be utilized to cut expenses, improve
patient care, and increase data accessibility.
3. Supply Chain: Using Hyperledger, organizations may create
initiatives that aim to limit the prevalence of counterfeit goods while
also tracing the provenance of components and services.
4. Insurance: The Insurance firm can refer to the transaction data
recorded in the ledger using Hyperledger. Hyperledger Fabric may
also use chain code to speed up claim processing and automate
payment.
5. Digital payment: Interledger and other Hyperledger applications
have the potential to set new standards in the finance sector. More
importantly, it has the potential to revolutionize two-party cross-
border payments.
Summary: Hyperledger is not a blockchain, but a hub of tools and
frameworks for building secure, customizable blockchain solutions
tailored to business needs.

[Link] Hyperledger projects:


Below are some of the hyperledger projects:

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

 Hyperledger Indy is a distributed ledger designed specifically for


decentralized identification. Evernym contributed the indy code base
that he created to the Sovrin foundation.
 It offers tools, frameworks, and reusable components for developing
and deploying autonomous digital identities based on blockchains or
other distributed ledgers. Hyperledger Indy is a distributed ledger
designed specifically for decentralized identity.

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:

 Manages identities of network participants.

 Uses PKI (Public Key Infrastructure) and digital certificates.

 Provides authentication, authorization, and access control.

Policy Services:
 Defines network rules like:
o Access policies
o Consensus rules
o Endorsement policies
 Controls who can do what on the network.

Blockchain & Transactions Layer:


This is the core blockchain layer, consisting of:

Component Description

Ensures agreement on transaction order (pluggable


Consensus
algorithms supported).

188
Hyperledger & tokenization
Component Description

Stores the blockchain data (immutably) + current


Ledger Store
world state.

P2P Network Allows communication between all nodes.

Smart Contracts (Chaincode):


 Business logic written in Go, [Link], Java.
 Chaincode is deployed in secure containers.
Smart contracts define how state should change when a transaction is
executed.

6.2 HYPERLEDGER FABRIC


6.2.1 Introduction:
Hyperledger Fabric is an open-source, permissioned blockchain
framework designed for enterprise use. Its architecture allows for the
creation of private, secure, and scalable blockchain networks tailored to
specific business needs. Fabric offers a modular and extensible approach,
making it a popular choice for various industries, including finance,
supply chain, healthcare, and more. HF allows organizations to create
private networks where participants are known and must be granted
permission to join. This enables confidentiality and control over who can
participate and access data on the network.

6.2.2 Core Components:


 Peers – maintain ledgers and run chaincode.
 Orderers – manage the consensus and broadcast transactions to
peers.
 Certificate Authority (CA) – issues cryptographic identities to
participants.
 Ledger – includes both a blockchain (immutable log) and a world
state (current data).

189
Web3 Technologies

6.2.3 Benefits of Hyperledger Fabric Architecture:


Some of the common benefits of HF architecture are as under:

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.

b. Privacy and Confidentiality:


The concept of channels provides data segregation and privacy, enabling
secure collaboration between specific network participants. It provides a
modular architecture that allows for the separation of components such as
consensus, membership services, and smart contracts. This modularity
enables organizations to tailor the blockchain network to their specific
needs. Fabric, in addition, supports private transactions by utilizing
channels and endorsing peers. Private data can be shared only with
authorized participants, ensuring confidentiality and privacy within the
network.

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.

e. Auditability and Transparency:


Hyperledger Fabric maintains an immutable ledger that records the
complete history of transactions. This transparent and auditable ledger
enables organizations to trace and verify every transaction that has
occurred within the network. The ability to audit and verify transactions is
crucial for compliance, accountability, and regulatory purposes.

f. Smart Contracts Support:


Hyperledger Fabric employs smart contracts, also known as 'chaincode', to
define the transaction logic and business rules. Smart contracts enable
automation and enforce consistency in business processes across the
network. Fabric supports multiple programming languages for developing
smart contracts, such as Go, JavaScript, and Java, allowing developers to
leverage their preferred language and existing codebase.

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.

6.3 HYPERLEDGER SAWTOOTH


6.3.1 Introduction:
Hyperledger Sawtooth is an open-source blockchain framework designed
to make building and deploying distributed ledger applications easier. It
offers a modular architecture that separates the core functions of a
blockchain from the business logic, making it flexible and adaptable to
191
Web3 Technologies various use cases. Sawtooth supports custom transaction processing,
allowing developers to define how transactions are validated and
processed.
Hyperledger Sawtooth is an open-source enterprise blockchain-as-a-
service platform that can run customized smart contracts without knowing
the core system's underlying design.
1. It is part of the Hyperledger project, a collaborative effort to advance
cross-industry blockchain technologies.
2. Sawtooth provides a modular and flexible framework allowing
organizations to build and manage blockchain solutions tailored to
their needs.

6.3.2 Features of the Hyperledger Sawtooth


1. Separation of Concerns: Separates the
core blockchain functionality from the application logic, allowing
for customization and extension.
2. Flexibility: Modular design enables the integration of various
components and transaction processors tailored to specific needs.
3. Transaction Processors: Developers can create custom transaction
processors to define how transactions are validated and applied.
4. Proof of Elapsed Time (PoET): A consensus algorithm that uses a
lottery-based approach to select block leaders, designed to be
energy-efficient and scalable.
5. Global State: Maintains a consistent global state of the blockchain,
ensuring that all transactions update the state in a synchronized
manner.
6. Efficient State Updates: The state changes are efficiently managed
and validated to maintain consistency and integrity.
7. High Throughput: Designed to handle high volumes of
transactions and support large-scale deployments.

6.3.3 Core Components of Hyperledger Sawtooth:


Here is an overview of the key components of Hyperledger Sawtooth:
1. Transaction Processor: It handles the business logic of transactions
by validating and applying them to the blockchain state. Developers
can implement custom transaction processors to define how
transactions are processed based on specific application needs. It
includes built-in transaction families and allows the creation of new
ones.

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.

6.3.5 Challenges in Hyperledger Sawtooth:


1. Customization: Customizing and integrating various components,
such as transaction families and consensus algorithms, requires in-
depth knowledge and expertise.
2. Scalability: Scaling the network to accommodate increasing numbers
of nodes and transactions may require careful tuning and optimization
of network and consensus parameters.
3. Testing and Validation: Ensuring the correctness and security of
custom transaction processors is critical. Inadequate testing can lead
to vulnerabilities and errors in transaction processing.
4. Data Protection: While Sawtooth provides mechanisms for securing
data, ensuring data privacy and protection against various attacks such
as Sybil attacks, DDoS requires ongoing vigilance and robust security
practices.

194
5. Interoperability: Integrating Sawtooth with existing enterprise Hyperledger & tokenization
systems and technologies may require custom adapters and significant
development effort.

6.3.6 Limitations of Hyperledger Sawtooth:


1. Multi-Component Setup: Sawtooth's modular architecture,
involving components like validators, transaction processors, and
state databases, can lead to complex setup and configuration
processes.
2. Transaction Throughput: While Sawtooth aims to support high
transaction throughput, achieving optimal performance at scale can be
difficult, particularly with complex transaction families and large
networks.
3. Consensus Overhead: Some consensus algorithms, such as PBFT,
may incur significant communication overhead and computational
resources, affecting overall network performance and scalability.
4. Data Migration: Migrating data from traditional systems to a
Sawtooth blockchain can be challenging, involving data
transformation and validation.
5. Node Management: Maintaining node health, handling failures, and
managing upgrades in a distributed network can be challenging and
require effective operational procedures.

6.3.7 Setting Up a Sawtooth Application Development Environment:


Before you can start developing for the Sawtooth platform, you'll need to
set up and run a local validator to test your application against. Once
running, you will be able to submit new transactions and fetch the
resulting state and block data from the blockchain using HTTP and the
Sawtooth REST API. The methods detailed here will apply to the included
example transaction families, IntegerKey and XO, as well as any
transaction families you might write yourself.
You can install and run a simple, single-node Sawtooth application
development environment on one of the following platforms:
 Docker: Run Sawtooth from prebuilt Docker containers.
 Ubuntu: Install Sawtooth natively using Ubuntu 16.04.
 Amazon Web Services (AWS): Launch Sawtooth in AWS from
the AWS Marketplace.
 Kubernetes: Run Sawtooth in a single-node Kubernetes cluster inside
a virtual machine on your computer.

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.

Recommended: Docker-Based Setup:


Prerequisites:
 Docker
 Docker Compose
 Git
 Bash or compatible shell

Step 1: Clone the Sawtooth Repository


bash
CopyEdit
git clone [Link]
cd sawtooth-core

Step 2: Run the Sawtooth Default Network


The Sawtooth repo includes a docker-compose setup with a validator,
REST API, transaction processor, and other components.
bash
CopyEdit
cd docker
docker-compose -f [Link] up

This will spin up the following components:


 Validator
 REST API
 Devmode consensus engine
 Settings TP
 Integer key TP (demo)
 Shell for interaction
196
You can view logs: Hyperledger & tokenization

bash
CopyEdit
docker-compose -f [Link] logs -f

To stop the network:


bash
CopyEdit
docker-compose -f [Link] down

Step 3: Interact With the Network


Once running, you can open a shell to a container:
bash
CopyEdit
docker exec -it sawtooth-shell-default bash
Try running a command:
bash
CopyEdit
sawtooth keygen my_key
Or use sawtooth transaction and sawtooth block commands to explore the
ledger.

Step 4: Build a Sample Transaction Processor


You can use the intkey example to get started, or build your own. Here's
the sample TP in Python:
bash
CopyEdit
cd ../sdk/examples/intkey_python
python3 [Link] install

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

Tokenization involves representing assets—whether physical (like real


estate) or intangible (like copyrights)—as digital tokens. These tokens are
managed using smart contracts, which are self-executing programs on the
blockchain. Smart contracts ensure secure and automated transactions by
verifying business rules and transferring value between wallets.

There are two primary models for token transactions:


 UTXO Model: Used in Bitcoin, it tracks unspent transaction outputs
to determine account balances.
 Account-Based Model: Used in Ethereum, it updates account
balances directly during transactions.
1. Asset Identification: Choose the asset to be tokenized.
2. Legal Wrapping: Establish a legal framework to link token
ownership to actual asset ownership (often via smart contracts and
legal custodians).
3. Token Creation: Use a blockchain platform (e.g., Ethereum,
Polygon, Avalanche) to issue the token via a smart contract.
4. Token Distribution: Sell or distribute tokens to users (via exchanges,
token sales, or direct transfers).
5. Trading & Transfer: Tokens can be traded peer-to-peer or on
platforms, with ownership recorded immutably on-chain.

6.4.3 Types of Tokenization:

199
Web3 Technologies

1. Word Tokenization: This is the most common method where text is


divided into individual words. It works well for languages with clear
word boundaries, like English.
2. Character Tokenization: In this method, text is split into individual
characters. This is particularly useful for languages without clear
word boundaries or for tasks that require a detailed analysis, such as
spelling correction.
3. Sub-word Tokenization: Sub-word tokenization strikes a balance
between word and character tokenization by breaking down text into
units that are larger than a single character but smaller than a full
word.
4. Sentence Tokenization: Sentence tokenization is also a common
technique used to make a division of paragraphs or large set of
sentences into separated sentences as tokens.
5. N-gram Tokenization: N-gram tokenization splits words into fixed-
sized chunks (size = n) of data.

6.4.4 Benefits of Tokenization:


 Liquidity: Illiquid assets (e.g., real estate, art) become tradable in
smaller units.
 Accessibility: Allows fractional ownership, opening investment to a
broader audience.
 Transparency: Blockchain provides a tamper-proof record of
ownership and transactions.
 Efficiency: Automates settlement, reduces intermediaries and
[Link] Ownership: Enables dividing high-value assets,
such as real estate, into smaller, affordable shares.
 Increased Liquidity: Broadens the market for traditionally illiquid
assets by making them accessible globally.

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.

6.4.5 Challenges of tokenization:


 Regulation: Legal uncertainty in many jurisdictions; securities laws
may apply.
 Custody: Who holds the actual asset, and how is it secured?
 Technology risks: Smart contract bugs, blockchain scalability,
network fees.
 Market adoption: Liquidity may depend on user adoption and trusted
infrastructure.
 Regulatory Uncertainty: Many jurisdictions lack clear rules for
tokenized assets, leading to legal complexities.
 Asset Management: Questions arise about managing tokenized
assets, especially when owned by multiple parties.
 Security Risks: If the underlying asset (e.g., gold) is lost or
mismanaged, the token's value is compromised

In spite of its importance, tokenization faces several challenges:


1. Ambiguity: Human language is inherently ambiguous. A sentence
like "I saw her duck" can have multiple interpretations depending on
the tokenization and context.
2. Languages Without Clear Boundaries: Languages like Chinese and
Japanese do not have clear word boundaries, making tokenization
more complex.

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.

Examples of Tokenized Assets:

Asset Type Example Token Description

Fractional ownership of rental


Real Estate RealT
properties in the U.S.

Tokenized shares of valuable


Art Particle, Masterworks
artwork

FTX (before collapse),


Stocks Synthetic stock tokens
Synthetix

Commodities Paxos Gold (PAXG) Gold-backed token

Music Fans can buy shares of


[Link]
Royalties streaming royalties

6.4.6 Types of Tokens:


 Security Tokens: Represent ownership of an asset, such as real estate
or stocks, and can be programmed with unique features.
 Utility Tokens: Provide access to blockchain services, power
consensus mechanisms, and enable governance in decentralized
systems.
 Platform Tokens: Facilitate interactions within decentralized
applications (DApps), such as Ethereum's Dai token.
 Fungible Tokens: Interchangeable and divisible, like gold or
cryptocurrencies.
 Non-Fungible Tokens (NFTs): Unique and indivisible, representing
assets like art or collectibles.

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

o ETH (on Ethereum) – used to pay for gas/transactions.


o BAT (Basic Attention Token) – rewards for viewing ads on Brave
browser.
o Chainlink (LINK) – used in smart contract oracle services.

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).

5. Non-Fungible Tokens (NFTs)


 Purpose: Represent unique, indivisible assets like digital art, music,
or collectibles.
203
Web3 Technologies  Each token is distinct.
 Examples:
o CryptoPunks, Bored Ape Yacht Club – digital art.
o NBA Top Shot – sports highlights as collectibles.

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.

6.4.7 The Tokenization Process:


At the heart of tokenization lies a multi-step process that transforms
sensitive data into secure tokens. Let’s explore the key stages of this
process:

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

The next stage involves developing a unique, blockchain-based token to


represent the asset. This process begins by selecting an appropriate
blockchain platform that offers the necessary security features and
scalability. By leveraging the inherent security and transparency of the
distributed ledger, the token becomes a secure and tamper-resistant digital
proxy for the original sensitive data.
Each token is cryptographically linked to the underlying asset, ensuring
that any attempt to alter the token would be immediately detectable. This
cryptographic linkage not only protects the token from tampering but also
provides a transparent and verifiable record of ownership and transaction
history. The creation of these tokens can involve smart contracts, which
automate and enforce the terms of the agreement related to the asset,
further enhancing security and efficiency.

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.

6. Token Storage and Retrieval:


After the tokens are generated, they need to be securely stored in a
centralized token vault or repository. This repository acts as a secure
storage location where all tokens are kept safe. To protect the tokens from
unauthorized access or data breaches, strong access controls and security
measures are put in place. These controls include strict authentication
procedures, encryption of stored tokens, and regular security audits to
detect and address any vulnerabilities..

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.

Tokenization Process (Example: Word Tokenization):


Input: "Tokenization is essential."

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

Output: ["Tokenization", "is", "essential", "."]

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.

6.4.8 Token Offerings:


A token offering is a way for blockchain-based projects to raise funds by
issuing and selling cryptographic tokens to investors or the public. These
tokens can represent a wide range of assets or utilities and are often sold in
exchange for cryptocurrencies like Bitcoin (BTC) or Ethereum (ETH), or
even fiat currency.

[Link] Types of Token Offerings:


1. Initial Coin Offering (ICO):
 The first and most well-known form.
 Similar to an IPO but for crypto.
 Investors buy tokens that may have utility on a platform or
speculative value.

2. Security Token Offering (STO):


 Tokens are backed by real-world assets (like stocks, real estate).
 Regulated — must comply with securities laws.
 Investors have legal rights (e.g., dividends, voting).

3. Initial Exchange Offering (IEO):


 Conducted through a cryptocurrency exchange.
 The exchange handles vetting and selling tokens.
 Often seen as more trustworthy due to the exchange’s involvement.

4. Initial DEX Offering (IDO):


 Hosted on decentralized exchanges (DEXs).
 Instant trading and liquidity.
 Lower entry barriers but potentially higher risk.

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.

[Link] Key Components of a Token Offering:

Component Description

A document that outlines the project’s vision,


Whitepaper
technology, tokenomics, and roadmap.

The economic model behind the token —


Tokenomics
supply, distribution, incentives, etc.

Code that handles token issuance and rules


Smart Contracts
automatically on the blockchain.

KYC/AML Many offerings require identity checks to


Compliance comply with laws.

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.

6.5 TOKEN STANDARDS


Token standards are sets of rules and specifications that define how tokens
operate on blockchain platforms, ensuring compatibility and
interoperability among various tokens and applications.

6.5.1What Are Token Standards?


A token standard is a set of specific rules and protocols that determine the
way a cryptocurrency token is created, behaves, and functions on a
blockchain network.
208
Cryptocurrency tokens represent digital assets that can be created, Hyperledger & tokenization
transferred, and stored on a blockchain. They enable various on-chain
functionalities, such as paying transaction fees, securing the network via
staking, running liquidity pools, and voting on governance proposals.

Definition and Purpose:


Token standards are essentially guidelines that dictate the creation,
issuance, and management of tokens on a blockchain. They establish a
common framework that developers can follow, which facilitates the
development of applications and services that can interact with these
tokens. This standardization is crucial for ensuring that tokens can work
seamlessly across different platforms and wallets, enhancing user
experience and security.

6.5.2 Common Token Standards:


1. ERC-20: This is the most widely used token standard on the
Ethereum blockchain for creating fungible tokens. It defines a set of
functions that allow tokens to be transferred, approved, and queried,
making it easy for wallets and exchanges to support these tokens.
2. ERC-721: This standard is used for non-fungible tokens (NFTs),
allowing for the creation of unique digital assets. Each token under
this standard has distinct properties, making it suitable for
collectibles, art, and other unique items.
3. ERC-1155: This standard combines the features of both fungible and
non-fungible tokens, allowing a single contract to manage multiple
token types. It is designed to be more efficient in terms of gas costs
and is particularly useful for gaming applications.
4. BEP-20: Similar to ERC-20, this is a token standard on the Binance
Smart Chain (BSC) that allows for the creation of fungible tokens. It
is designed to be compatible with the Ethereum ecosystem, enabling
easy token transfers between the two platforms.

6.5.2 Importance of Token Standards:

 Interoperability: Token standards ensure that tokens created on one


platform can interact with applications and wallets that support the
same standard. This interoperability is essential for trading and
managing multiple cryptocurrencies without needing separate wallets
for each token.

 Development Efficiency: By adhering to established standards,


developers can save time and resources. They can leverage existing
functionalities instead of building from scratch, allowing for more
innovation and experimentation in the blockchain space.

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.3 Why Are Token Standards Important?


Token standards play a fundamental role in the development of blockchain
ecosystems. Standards create a basic framework that simplifies token
development throughout the blockchain space and enhances liquidity.
They ensure that cryptocurrency tokens are interoperable, compatible, and
can be easily integrated into dApps, wallets, and exchanges.
Token standards foster innovation by enabling developers to build on
existing standards rather than reinventing the wheel. Similarities between
token standards, such as ERC-20 and BEP-20, make it easier for
developers to transfer tokens and applications across multiple blockchains,
accelerating deployment and adoption.

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.

6.6 TRADING AND FINANCE IN TOKENIZATION


Tokenization in Trading and Finance is one of the most transformative
applications of blockchain technology. It involves converting rights to an
asset into a digital token on a blockchain. These tokens can represent a
wide range of assets — from real estate and company shares to artwork
and commodities — and they can be traded on various platforms.

6.6.1 How Tokenization Impacts Finance and Trading?


1. Increased Liquidity:
 Traditional assets like real estate or art are illiquid (hard to sell
quickly).
 Tokenization enables fractional ownership, letting investors buy
small portions and trade them on secondary markets, increasing
liquidity.

2. 24/7 Markets:
 Tokenized assets can trade 24/7, similar to crypto markets, unlike
traditional stock exchanges that have fixed hours.

3. Lower Barriers to Entry


 Investors no longer need large capital to access high-value assets.
210
 Retail investors can diversify portfolios by owning small fractions of Hyperledger & tokenization
various tokenized assets.

4. Improved Transparency and Security:


 Blockchain provides a tamper-proof and auditable record of
ownership and transactions.
 Smart contracts can automate settlement, reducing fraud and
counterparty risk.

5. Faster Settlement:
 Traditional trading often has a T+2 settlement time.
 Tokenized assets can settle almost instantly with fewer
intermediaries.

6.6.2 Types of Tokenized Assets in Trading & Finance:

Asset Type Example Uses

Tokenized stocks that represent company


Equities
shares

Bonds Tokenized debt instruments

Real Estate Fractional ownership in property

Commodities Tokens backed by gold, oil, etc.

Funds Tokenized ETFs or hedge funds

Tokenized art, sports memorabilia, luxury


Collectibles
goods

Carbon
Traded in environmental finance markets
Credits

6.6.3 Platforms and Protocols Supporting Tokenization:


 Ethereum (via ERC-20, ERC-1400 for security tokens)
 Polymath – Platform for creating compliant security tokens
 Securitize – Manages tokenized securities
 Tokeny – Token issuance and lifecycle management
 INX, tZERO – Regulated tokenized asset trading platforms

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.).

[Link] Step-by-Step Guide to Building an ERC-20 Token:


1. Define the Purpose of Tokenization:
Before coding anything, clarify:
 What asset is being tokenized? (e.g., Real estate, shares, debt)
 Who can hold the tokens? (Public, whitelisted investors)
 What compliance rules apply? (SEC, MiCA, etc.)
You’ll likely want more than a basic ERC-20 — adding KYC, transfer
restrictions, and compliance logic using smart contracts.

2. Write the ERC-20 Smart Contract:


Here’s a simple ERC-20 implementation in Solidity (v0.8.x), using
OpenZeppelin for security and reliability.
solidity
CopyEdit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/[Link]";
contract RealEstateToken is ERC20 {
address public admin;
constructor() ERC20("RealEstateToken", "RET") {
admin = [Link];
_mint([Link], 1000000 * 10 ** decimals()); // 1 million tokens
}
function mint(address to, uint256 amount) external {
require([Link] == admin, "Only admin can mint");
212
_mint(to, amount); Hyperledger & tokenization

}
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

[Link] Emerging concepts:


Emerging Concepts in Tokenization (2025)
1. Real-World Asset (RWA) Tokenization:
What it is: Converting real assets like real estate, treasury bills, credit, or
invoices into blockchain-based tokens.
Why it matters:
 Gives DeFi access to $trillions in traditional assets
 Enables yield generation from real-world cash flows (e.g., tokenized
T-Bills)

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

3. Programmable Money and Tokens:


"Money that acts on its own."
What it is: Tokens that execute specific rules autonomously.
Examples:
 Tokenized bond that automatically pays interest every 30 days
 Token that becomes transferable only after KYC approval
Tools:

 Smart contracts
 ERC-777, ERC-4626 (for tokenized vaults)

4. Tokenized Carbon Credits & ESG Assets


"Verifiable, traceable sustainability assets on-chain."
Why now: Rising pressure for sustainability and transparency.
How it works:
 Token represents a carbon offset unit (1 ton CO₂)
 Issued, tracked, and retired on-chain
Key players:
 Toucan Protocol, Regen Network, KlimaDAO

5. Interoperable Token Standards:


"Cross-chain and cross-platform tokenization."
Problem: Fragmented ecosystems = limited liquidity.
Solutions:
 ERC-6900 / ERC-7621 (modular, interoperable token logic)
 Layer 2s & modular chains (Arbitrum, Polygon CDK, Cosmos
SDK)

214
 Token bound accounts (ERC-6551) for advanced identity + Hyperledger & tokenization
ownership

6. Tokenized Intellectual Property (IP) & Royalties:


"IP rights on-chain."
Use cases:
 Music streaming rights
 Patents & trademarks
 Book or film royalties
Benefits:
 Transparent revenue splits
 Secondary market for royalties
Platforms:
 [Link], Async Art, Opulous

7. AI-Generated Asset Tokenization:

"Synthetic tokenization of AI-created value."


Emerging idea: Tokenize AI models, datasets, or output (like videos or
images).
Examples:
 Sell AI-generated content via NFTs
 Share revenue from AI agents via tokens
Intersection:
 AI + Web3 (e.g., Ocean Protocol for data marketplaces)

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?

6.8.1 Multiple Choice Questions:


1. In Hyperledger Fabric, what initiates the transaction process?
a) The Ordering Service receives a transaction request
b) The client application sends a transaction proposal to endorsing peers
c) A peer node creates a new block of transactions
d) The Endorsement Policy is automatically triggered

2. What is the default database used for the world state in


Hyperledger Fabric?
a) Oracle
b) MySQL
c) LevelDB
216
d) MongoDB Hyperledger & tokenization

3. What is a Channel in Hyperledger Fabric?


a) A communication protocol between nodes
b) A private subnet within the network for a specific set of participants
to conduct transactions
c) The entire blockchain network
d) A smart contract function

4. Which of the following best describes a Hyperledger network?


a) It's a public blockchain where anyone can join
b) It's a consortium of known organizations with identified identities
c) It's a network where identities are anonymous
d) It's a network primarily used for mining cryptocurrencies

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

6. What type of blockchain is Hyperledger Fabric?


a) Public
b) Permissionless
c) Permissioned
d) Private-only

7. What is the function of the Orderer node in Hyperledger Fabric?


a) Validates transactions
b) Executes smart contracts
c) Orders and bundles transactions into blocks
d) Stores chaincode

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

9. What are the two main types of blockchain tokens?


a) Credit tokens and debit tokens
b) Real tokens and fake tokens
c) Security tokens and utility tokens
d) Mining tokens and trading tokens

10. What is a security token?


a) A token used to login securely
b) A token representing access to a dApp
c) A token that represents ownership in a real-world asset like equity,
real estate, or debt
d) A token that provides loyalty points

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

7.1 INTRODUCTION TO SOLIDITY PROGRAMMING


Solidity is a high-level, contract-oriented programming language
specifically designed for writing smart contracts that run on the Ethereum
blockchain. Smart contracts are self-executing programs in which the
terms of the agreement are directly written into code and automatically
enforced when predefined conditions are met.

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.

Solidity is widely used for building:

 Cryptocurrencies and tokens (ERC-20, ERC-721, ERC-1155)

 Decentralized finance (DeFi) applications

 Non-Fungible Tokens (NFTs)

 Voting systems and governance applications

 Supply chain and identity management systems


The language provides built-in security features and allows developers to
define precise rules for transactions, helping to reduce fraud,
intermediaries, and operational costs. Due to its importance in blockchain-
based systems, Solidity has become a core component of Web3
Technologies.

7.1.1 Basis of Solidity Programming:


The foundation of Solidity programming lies in the principles of
blockchain technology, smart contracts, and the Ethereum Virtual
Machine (EVM). Solidity programs are written as smart contracts that
define the data structure and business logic governing decentralized
applications.

Key basics of Solidity programming include:

 Smart Contracts: Programs that execute automatically on the


blockchain when conditions are satisfied.

 Ethereum Virtual Machine (EVM): A runtime environment that


executes compiled Solidity bytecode.

 Accounts: Externally Owned Accounts (EOA) and Contract


Accounts that interact with smart contracts.

 Gas Mechanism: A fee system used to measure and pay for


computational work on the Ethereum network.

220
 Immutability: Once deployed, smart contracts cannot be altered, Introduction to Solidity
Programming
ensuring transparency and trust.

 Decentralization: Contracts are executed across distributed nodes,


eliminating central authority.
Understanding these fundamentals is essential for writing efficient, secure,
and reliable smart contracts. A strong grasp of Solidity basics enables
developers to build robust decentralized applications within the Web3
ecosystem.

7.2 LAYOUT OF A SOLIDITY SOURCE FILE


A Solidity source file defines the structure and components of a smart
contract program. It follows a well-defined layout that helps the compiler
understand the code and improves readability, security, and
maintainability. Solidity source files usually have the extension .sol and
may contain one or more smart contracts.
The general layout of a Solidity source file includes the following
elements, written in a specific order:

7.2.1 SPDX License Identifier:


Every Solidity source file should begin with an SPDX license identifier. It
specifies the software license under which the source code is released and
helps avoid legal ambiguity.

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;

7.2.3 Import Statements:


Import statements allow a Solidity file to reuse code from other files or
libraries. They promote modular programming and reduce code
duplication.

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{ }

7.2.5 State Variables:


State variables are declared inside the contract and store data permanently
on the blockchain. Their values are saved in the contract’s storage.

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;
}

7.2.10 Complete Example of Solidity Source File Layout:


// SPDX-License-Identifier: MIT
Pragma solidity ^0.8.0;
Contract SimpleStorage {
Uint public value;
Constructor() {
Value = 0;
}
Function setValue(uint _value) public {
Value = _value;
}
}

7.3 STRUCTURE OF A CONTRACT


A smart contract in Solidity is a collection of code and data that resides at
a specific address on the Ethereum blockchain. The structure of a contract
defines how data is stored, how functions are executed, and how external
users interact with the contract. A well-defined contract structure improves
readability, security, and maintainability.
A Solidity contract consists of several key components, each serving a
specific purpose.

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 {
}

7.3.2 State Variables:


State variables store the permanent data of the contract. Their values are
recorded on the blockchain and persist between function calls.

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);

7.3.7 Structs and Enums:


Structs group related variables, while enums define a set of predefined
values. They help in organizing contract data.

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.3.10 Complete Example of Contract Structure:


Pragma solidity ^0.8.0;
Contract BankAccount {
Address public owner;
Uint public balance;
Event Deposit(address indexed user, uint amount);
Modifier onlyOwner() {
Require([Link] == owner, “Not owner”);
_;
}
Constructor() {
Owner = [Link];
Balance = 0;
}
Function deposit(uint amount) public {
Balance += amount;
Emit Deposit([Link], amount);
}
}
The structured organization of a Solidity contract ensures secure
execution, clear logic flow, and efficient interaction, making it a
fundamental concept in Solidity programming.

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.

7.4.1 Value Types:


Value types store data directly and are passed by value. They occupy a
fixed amount of memory.

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;

d) Fixed-Size Byte Arrays:


Used to store fixed-length byte data.

Example:
Bytes32 hash;

e) Enum:
Defines a user-defined type with a fixed set of named values.

Example:
Enum Status { Pending, Approved, Rejected }

7.4.2 Reference Types:


Reference types store the location (reference) of data rather than the actual
value. They are more complex and dynamic.

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;

7.4.3 Special Types:


Special types are used for specific purposes in Solidity programming.
a) String:
Used to store text data.
Example:
String public name;

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);

7.4.4 Default Values:


Solidity assigns default values to uninitialized variables.

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.

7.5 UNITS AND GLOBALLY AVAILABLE VARIABLES


Solidity provides built-in units and globally available variables that help
developers work efficiently with Ether values, time calculations, and
blockchain-specific information. These features allow smart contracts to
interact with the Ethereum environment in a secure and standardized
manner.

7.5.1 Ether Units:


Solidity supports predefined units to represent Ether and its sub-
denominations. These units improve code readability and reduce
calculation errors.

Common Ether units include:


Wei – smallest unit of Ether
Gwei – commonly used for gas price
Ether – standard unit of Ether

Example:
Uint amount = 1 ether;
UintgasFee = 10 gwei;

7.5.2 Time Units:


Solidity also supports time units that make time-based operations more
readable. Internally, time is measured in seconds.

229
Web3 Technologies Common time units:
Seconds
Minutes
Hours
Days
Weeks

Example:
UintlockTime = 7 days;

7.5.3 Globally Available Variables:


Globally available variables provide information about the current
transaction, block, and message sender. These variables are accessible
from any Solidity contract.
7.5.4 Message Variables:
Message variables give details about the function call and sender.
[Link] – address of the caller
[Link] – amount of Ether sent
[Link] – complete call data

Example:
Address sender = [Link];
UintvalueSent = [Link];

7.5.5 Block Variables:


Block variables provide information related to the current block.
[Link] – current block number
[Link] – time of block creation
[Link] – current chain ID

Example:
UintcurrentBlock = [Link];

7.5.6 Transaction Variables:


Transaction variables give information about the transaction execution.

230
[Link] – gas price of the transaction Introduction to Solidity
Programming
[Link] – original external account that started the transaction

Example:
UintgasPrice = [Link];

7.5.7 Use of Units and Global Variables:


Units and globally available variables are widely used in:
Payment and fund transfer contracts
Time-locked smart contracts
Access control and authorization
Auditing and logging blockchain activity
By using built-in units and global variables, Solidity enables precise
financial calculations, secure access control, and reliable interaction with
the blockchain environment, making them essential components of smart
contract development.

7.6 INPUT PARAMETERS AND OUTPUT


PARAMETERS
In Solidity, functions can accept input parameters and return output
parameters. These parameters allow smart contracts to receive data from
users or other contracts and return results after execution. Proper use of
input and output parameters improves flexibility, reusability, and clarity of
smart contract functions.

7.6.1 Input Parameters:


Input parameters are variables passed to a function when it is called. They
allow external users or contracts to provide data to the smart contract for
processing.

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.

7.6.2 Multiple Input Parameters:


A function can accept more than one input parameter.

Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}

7.6.3 Output Parameters:


Output parameters are values returned by a function after execution. They
allow the function to send results back to the caller.

Syntax:
Function functionName() public returns (type) {
}

Example:
Function getValue() public view returns (uint) {
Return value;
}

7.6.4 Named Output Parameters:


Solidity allows naming the output parameters, which can improve code
readability.

Example:
Function getSum(uint a, uint b) public pure returns (uint result) {
Result = a + b;
}

7.6.5 Multiple Output Parameters:


A function can return multiple values using tuples.

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];
}

7.6.7 Importance of Parameters:


Input and output parameters are essential for:
User interaction with smart contracts
Data exchange between contracts
Implementing business logic
Improving modularity and reusability
By effectively using input and output parameters, Solidity functions can
communicate efficiently, perform meaningful operations, and return
accurate results, making them a fundamental part of smart contract
programming.

7.7 CONTROL STRUCTURES


Control structures in Solidity determine the flow of execution of a smart
contract. They allow the contract to make decisions, repeat operations, and
manage execution paths based on conditions. Solidity control structures
are similar to those found in traditional programming languages such as C
and JavaScript, making them easy to understand.

7.7.1 Conditional Statements:


Conditional statements are used to execute code based on a condition.

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;
}

7.7.2 Looping Statements:


Looping statements are used to execute a block of code repeatedly.

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);

7.7.3 Loop Control Statements:


Loop control statements change the normal flow of loop execution.
Break – exits the loop immediately
Continue – skips the current iteration

Example:
For (uint I = 0; I < 10; i++) {
If (I == 5) {
Break;
}

235
Web3 Technologies }

7.7.4 Return Statement:


The return statement exits a function and optionally returns a value.

Example:
Function getBalance() public view returns (uint) {
Return balance;
}

7.7.5 require, assert, and revert (Control Flow Safety):


Although mainly used for error handling, these statements also control
execution flow.
Require() – checks conditions and refunds remaining gas
Assert() – checks internal errors
Revert() – stops execution and reverts state changes

Example:
Require([Link] == owner, “Unauthorized access”);

7.7.6 Importance of Control Structures:


Control structures are essential for:
Decision-making in smart contracts
Implementing business logic
Managing repetitive tasks
Ensuring contract safety and correctness
Control structures enable Solidity contracts to execute logic efficiently and
securely, forming a core part of smart contract development in Web3
Technologies.

7.8 FUNCTION CALLS


Function calls in Solidity allow the execution of code defined within the
same contract or in other deployed contracts. They enable interaction
between different parts of a smart contract and between multiple smart
contracts, forming the backbone of decentralized application logic.

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();
}

7.8.2 External Function Calls:


External function calls are used to call functions of other contracts or the
same contract using its address. These calls may involve Ether transfer and
gas usage.

Example:
OtherContractoc = OtherContract(contractAddress);
[Link](10);

7.8.3 Calling Functions with Parameters:


Functions can be called by passing the required input parameters.

Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}
Uint result = add(5, 10);

7.8.4 Calling Functions with Return Values:


A function call can return a value which can be stored or used in
expressions.

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}();

7.8.6 Low-Level Function Calls:


Solidity provides low-level functions for advanced contract interactions:
Call()
Delegatecall()
Staticcall()

Example:
(bool success, ) = [Link](
[Link](“setValue(uint256)”, 100)
);
Require(success);

7.8.7 Function Call Safety:


To ensure secure function calls:
Always check return values
Avoid unnecessary external calls
Prevent re-entrancy vulnerabilities
Use require() for validation

7.8.8 Importance of Function Calls:


Function calls are essential for:
Code reuse and modular design
Contract-to-contract communication
Implementing complex workflows
Enabling decentralized application interaction
238
Function calls in Solidity enable efficient execution, secure Introduction to Solidity
Programming
communication, and modular smart contract design, making them a
fundamental concept in Web3 application development.

7.9 CREATING CONTRACTS VIA NEW


In Solidity, new smart contracts can be created dynamically from within
an existing contract using the new keyword. This feature allows one
contract to deploy another contract on the blockchain, enabling modular
design, factory patterns, and scalable decentralized applications.

7.9.1 Purpose of Creating Contracts via new:


Creating contracts using new is commonly used to:
Deploy multiple instances of a contract
Implement factory contracts
Create child or dependent contracts
Enable dynamic and scalable contract architectures

7.9.2 Syntax for Creating a Contract:


The basic syntax for creating a contract using new is:
ContractTypevariableName = new ContractType(constructorArguments);

Example:
ChildContract cc = new ChildContract();

7.9.3 Creating Contracts with Constructor Parameters:


If the contract has a constructor with parameters, they must be passed
during creation.

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);
}
}

7.9.4 Address of Newly Created Contract:


When a new contract is created, it is deployed to a new blockchain
address. This address can be stored and used for future interactions.

Example:
Address childAddress = address(child);

7.9.5 Gas Cost and Deployment Considerations:


Creating contracts via new consumes significant gas because:
Contract bytecode is stored on the blockchain
Constructor code is executed during deployment
Therefore, contract creation should be done cautiously to avoid high costs.

7.9.6 Security Considerations:


While creating contracts dynamically:
Ensure proper access control
Avoid creating untrusted contracts
Validate constructor inputs
Prevent misuse of factory contracts

7.9.7 Use Cases:


Creating contracts via new is widely used in:
Token factories
Crowdfunding platforms
DAO contract creation
NFT minting systems
Creating contracts using the new keyword enables dynamic deployment,
modularity, and scalable design, making it an important feature of Solidity
programming in Web3 Technologies.

240
Introduction to Solidity
7.10 ORDER OF EVALUATION OF EXPRESSIONS Programming

The order of evaluation of expressions in Solidity determines how


operators and operands are processed to produce a result. Understanding
this order is essential to avoid logical errors, ensure correctness, and write
secure smart contracts. Solidity follows a well-defined operator
precedence and associativity, similar to languages such as C and
JavaScript.

7.10.1 Operator Precedence:


Operator precedence defines the order in which different operators are
evaluated in an expression. Operators with higher precedence are
evaluated before operators with lower precedence.

General precedence order (high to low):


1. Parentheses ( )
2. Unary operators (!, ++, --, -)
3. Multiplication, Division, Modulus (*, /, %)
4. Addition and Subtraction (+, -)
5. Relational operators (<, >, <=, >=)
6. Equality operators (==, !=)
7. Logical AND (&&)
8. Logical OR (||)
9. Assignment operators (=, +=, -=, *=, /=)

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

7.10.4 Short-Circuit Evaluation:


Logical operators in Solidity use short-circuit evaluation:
In &&, if the first condition is false, the second is not evaluated.
In ||, if the first condition is true, the second is not evaluated.

Example:
If (balance > 0 &&[Link] == owner) {
// executed only if both conditions are true
}

7.10.5 Evaluation and Gas Optimization:


Proper ordering of expressions can reduce gas consumption. Place cheaper
conditions first in logical expressions to minimize unnecessary
computation.

Example:
Require(amount > 0 && amount <= balance);

7.10.6 Importance of Expression Evaluation Order:


Understanding the order of evaluation helps in:
Avoiding logical and arithmetic errors
Writing predictable and correct expressions
Improving smart contract security
Optimizing gas usage
A clear understanding of the order of evaluation of expressions ensures
accurate computation, reliable logic flow, and secure execution of Solidity
smart contracts in Web3 Technologies.

242
Introduction to Solidity
7.11 ASSIGNMENT Programming

Assignment in Solidity refers to the process of storing values in variables


using assignment operators. Assignment statements are fundamental to
smart contract programming, as they allow contracts to update state
variables, manage data, and implement business logic.

7.11.1 Assignment Operator:


The basic assignment operator in Solidity is =. It assigns the value on the
right-hand side to the variable on the left-hand side.

Example:
Uint count;
Count = 10;

7.11.2 Compound Assignment Operators:


Solidity supports compound assignment operators that combine arithmetic
operations with assignment.
Common compound assignment operators include:
+= (addition and assignment)
-= (subtraction and assignment)
*= (multiplication and assignment)
/= (division and assignment)
%= (modulus and assignment)

Example:
Uint total = 50;
Total += 10; // total = 60

7.11.3 Assignment with Expressions:


Assignments can include expressions that are evaluated before the
assignment takes place.

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);

7.11.5 Assignment and Storage Location:


Assignment behavior depends on the storage location of variables:
Storage: Assigns references for complex data types
Memory: Creates copies of data

Example:
Uint[] storage dataRef = data;
Uint[] memory dataCopy = data;

7.11.6 Assignment Safety:


To ensure safe assignment:
Avoid unintentional overwriting of state variables
Use require() to validate values before assignment
Be careful with reference assignments in storage

Example:
Require(amount > 0);
Balance = amount;

7.11.7 Importance of Assignment:


Assignment is essential for:
Updating contract state
Managing user balances
Implementing logical operations
Controlling data flow within contracts
Proper use of assignment ensures correct data storage, predictable
execution, and secure smart contract behavior, making it a core concept in
Solidity programming.

244
Introduction to Solidity
7.12 SCOPING AND DECLARATIONS Programming

Scoping in Solidity defines the region of the program where a variable or


function is accessible, while declarations specify the type, name, and
storage behavior of variables and functions. Proper understanding of
scoping and declarations helps in writing secure, efficient, and well-
structured smart contracts.

7.12.1 Variable Declarations:


Variables in Solidity must be declared with a data type before use.
Variable declarations may include visibility and storage location.

Example:
Uint public count;
Address private owner;

7.12.2 Scope of Variables:


The scope of a variable determines where it can be accessed within a
contract.

7.12.3 State Variable Scope:


State variables are declared outside functions and are accessible
throughout the contract.

Example:
Contract Example {
Uint public value;
Function setValue(uint _v) public {
Value = _v;
}
}

7.12.4 Local Variable Scope:


Local variables are declared inside functions and are accessible only
within that function.

Example:
Function calculate(uint a, uint b) public pure returns (uint) {
Uint result = a + b;

245
Web3 Technologies Return result;
}

7.12.5 Block Scope:


Variables declared inside control structures such as if, for, or while blocks
are accessible only within that block.

Example:
Function test() public pure returns (uint) {
Uint sum = 0;
For (uint I = 0; I < 5; i++) {
Sum += I;
}
Return sum;
}

7.12.6 Function Declarations:


Functions are declared with:
Function name
Parameter list
Visibility specifier
State mutability specifier
Return type

Example:
Function getValue() public view returns (uint) {
Return value;
}

7.12.7 Declaration Order and Shadowing:


Solidity allows variable shadowing, where a local variable has the same
name as a state variable. However, this practice is discouraged as it may
lead to confusion and errors.

Example:
Uint public data;
246
Function update() public { Introduction to Solidity
Programming
Uint data = 10; // shadows state variable
}

7.12.8 Constants and Immutable Variables:


Constants and immutable variables improve safety and gas efficiency.

Example:
Uint constant MAX = 100;
Address immutable owner;

7.12.9 Importance of Scoping and Declarations:


Proper scoping and declarations help in:
Avoiding naming conflicts
Enhancing code readability
Improving contract security
Optimizing gas usage
Understanding scoping and declarations ensures controlled access to
variables, predictable behavior, and maintainable smart contract code,
making it an essential concept in Solidity programming.

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.

Practical / Application-Based Questions:


1. Write a Solidity program to demonstrate the layout of a source file.
248
2. Write a smart contract to demonstrate the use of different data types. Introduction to Solidity
Programming
3. Write a Solidity contract using input and output parameters.
4. Write a program demonstrating conditional and looping control
structures.
5. Write a Solidity contract to demonstrate internal and external
function calls.
6. Write a program to demonstrate Ether units and time units.
7. Write a Solidity contract that creates another contract using the new
keyword.
8. Write a program to demonstrate the use of globally available
variables.
9. Write a Solidity contract to illustrate assignment and expression
evaluation.
10. Write a program demonstrating variable scope and declarations in
Solidity.

*****

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

8.1 BASICS OF ERROR HANDLING


Error handling in Solidity is the mechanism used to detect, manage, and
respond to abnormal conditions that occur during the execution of smart
contracts. Since smart contracts operate on a blockchain where
transactions are irreversible and costly, proper error handling is essential
to ensure security, correctness, and reliability.
When an error occurs in Solidity, the execution of the contract is stopped,
all state changes are reverted, and the remaining gas (except the gas
250
already used) is returned to the caller. Solidity provides built-in functions Error handling and Smart
Contracts
and statements for handling errors effectively.

8.1.1 Need for Error Handling:

 Error handling is important in Solidity because:

 Smart contracts handle financial transactions

 Deployed contracts are immutable

 Incorrect logic may lead to loss of funds

 Errors must prevent invalid state changes

8.1.2 Types of Errors in Solidity:

 Errors in Solidity can occur due to:

 Invalid input values

 Unauthorized access

 Arithmetic overflow or underflow

 Failed external contract calls

 Logical and runtime errors

8.1.3 Error Handling Mechanisms in Solidity:


Solidity provides three main mechanisms for error handling:
a) Require():

 Used to validate conditions such as input values and access control

 Reverts the transaction if the condition fails

 Remaining gas is refunded

Example:
Require([Link] == owner, “Not authorized”);

b) Assert():

 Used to check internal errors and invariants

 Indicates a serious bug if it fails

 Consumes all remaining gas

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”);

8.1.4 Custom Errors (Introduction):


Solidity also supports custom errors, which are more gas-efficient than
string-based error messages.

Example:
Error InsufficientBalance(uint requested, uint available);

8.1.5 Effects of Error Handling:

 When an error occurs:

 Contract execution is stopped

 State changes are reverted

 Error message is returned (if provided)

 Gas refund rules are applied

8.1.6 Importance of Error Handling:

 Effective error handling helps in:

 Preventing unauthorized actions

 Maintaining contract integrity

 Reducing financial risk

 Improving contract reliability


Error handling forms the foundation for writing secure and robust smart
contracts, making it a critical topic in Solidity programming and Web3
Technologies.

252
Error handling and Smart
8.2 ASSERT Contracts

The assert statement in Solidity is used to check internal errors and


invariants within a smart contract. It is intended to detect conditions that
should never be false during correct program execution. If an assert
statement fails, it indicates a serious bug in the contract logic.

8.2.1 Purpose of assert:

 The main purpose of assert is to:

 Verify internal consistency of the contract

 Check conditions that must always be true

 Detect logical errors during development

 Unlike require, assert is not used for input validation or user errors.

8.2.2 Behavior of assert:

 When an assert condition fails:

 Contract execution is immediately stopped

 All state changes are reverted

 All remaining gas is consumed

 It indicates a critical failure

 This makes assert suitable only for checking invariants.


8.2.3 Syntax of assert:
Syntax:
Assert(condition);

Example:
Assert(totalSupply>= balances[[Link]]);

8.2.4 Use of assert in Smart Contracts:

 Common uses of assert include:

 Ensuring arithmetic correctness

 Verifying invariants after state updates

 Detecting unreachable code paths

253
Web3 Technologies Example:
Function decrement(uint value) public {
Total -= value;
Assert(total >= 0);
}

8.2.5 Difference between assert and require:


Aspect assert require
Purpose Internal error checking Input and condition validation
Gas refund No refund Remaining gas refunded
Error type Critical bug Recoverable error
Usage Invariants User-defined conditions

8.2.6 Best Practices for Using assert:

 Use assert only for conditions that should never fail

 Avoid using assert for user input validation

 Prefer require for access control and input checks

 Use sparingly to avoid unnecessary gas consumption

8.2.7 Importance of assert:

 The assert statement helps developers:

 Identify serious bugs early

 Maintain contract correctness

 Ensure logical consistency


In summary, assert is a powerful tool for internal safety checks in Solidity,
but it must be used carefully to avoid excessive gas consumption and
unintended contract failures.

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:

 Validate function input parameters

 Enforce access control rules

 Check conditions before execution

 Prevent invalid state changes

 Unlike assert, require is designed to handle expected and


recoverable errors.

8.3.2 Behavior of require:

 When a require condition fails:

 Contract execution stops immediately

 All state changes are reverted

 Remaining gas is refunded to the caller

 An optional error message is returned

 This makes require suitable for user-level validations.

8.3.3 Syntax of require:


Syntax:
Require(condition);
Require(condition, “Error message”);

Example:
Require([Link] == owner, “Unauthorized access”);

8.3.4 Common Uses of require


a) Input Validation:
Require(amount > 0, “Amount must be greater than zero”);

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

8.3.6 Best Practices for Using require:

 Use require for all external input checks

 Validate conditions at the beginning of functions

 Provide meaningful error messages

 Combine with modifiers for reusable checks

8.3.7 Importance of require:

 The require statement helps in:

 Preventing unauthorized access

 Avoiding invalid transactions

 Improving contract security

 Reducing unexpected failures


In summary, require is an essential tool for writing safe, user-friendly, and
reliable smart contracts, making it a cornerstone of error handling in
Solidity.

8.4 REVERT AND EXCEPTIONS


In Solidity, exceptions are runtime errors that occur during the execution
of a smart contract. When an exception occurs, the execution is halted, all
state changes are reverted, and control is returned to the caller. The revert
statement is an explicit way to trigger an exception and undo contract
execution.

8.4.1 Concept of Exceptions in Solidity:


An exception in Solidity occurs when:

 A require or assert condition fails

 A revert statement is executed

256
 An arithmetic error occurs (e.g., division by zero) Error handling and Smart
Contracts

 An external contract call fails

 Exceptions ensure that invalid operations do not change the


blockchain state.

8.4.2 revert Statement:


The revert statement is used to explicitly stop execution and revert all state
changes. It is useful when complex conditions cannot be easily handled by
require.

Syntax:
Revert();
Revert(“Error message”);

Example:
If (balance < amount) {
Revert(“Insufficient balance”);
}

8.4.3 Behavior of revert:


When revert is executed:

 Contract execution stops immediately

 All state changes are reverted

 Remaining gas is refunded

 An optional error message is returned

8.4.4 revert vs require:


Although both revert execution, they differ in usage.
Aspect revert require
Usage Explicit error handling Condition checking
Error message Optional Optional
Readability Used in complex logic Simpler conditions
Gas refund Yes Yes

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”);

8.4.6 Common Causes of Exceptions:


Exceptions may occur due to:

 Invalid input values

 Unauthorized access

 Insufficient balance

 Logical errors

 Failed external calls

8.4.7 Importance of revert and Exceptions:


Using revert and proper exception handling:

 Prevents invalid state updates

 Protects user funds

 Improves contract reliability

 Enhances security

8.5 INTRODUCTION TO SMART CONTRACTS


A smart contract is a self-executing computer program that runs on a
blockchain and automatically enforces the terms of an agreement when
predefined conditions are met. Smart contracts eliminate the need for
intermediaries by ensuring that transactions are transparent, secure, and
tamper-proof.
In the context of Web3 Technologies, smart contracts form the core layer
that enables decentralized applications (DApps) and trustless interactions
among users.

8.5.1 Definition of Smart Contract:


A smart contract is a set of rules and logic written in code that is deployed
on a blockchain network. Once deployed, the contract executes
automatically and cannot be altered.
258
8.5.2 Characteristics of Smart Contracts: Error handling and Smart
Contracts
Smart contracts have the following key characteristics:

 Automation: Executes automatically without human intervention

 Immutability: Cannot be modified after deployment

 Transparency: Contract code and transactions are publicly


verifiable

 Security: Cryptographic protection ensures tamper resistance

 Decentralization: Executed by multiple nodes in the network

8.5.3 Working of Smart Contracts:


The working of a smart contract involves:
1. Writing contract code using Solidity
2. Compiling the code into EVM bytecode
3. Deploying the contract on the blockchain
4. Triggering functions through transactions
5. Automatic execution and state updates

8.5.4 Advantages of Smart Contracts:


Smart contracts offer several advantages:

 Reduced transaction cost

 Faster execution

 Elimination of intermediaries

 Improved trust and reliability

 Reduced risk of fraud

8.5.5 Limitations of Smart Contracts:


Despite their benefits, smart contracts have limitations:

 Immutability makes error correction difficult

 Dependence on external data (oracles)

 Scalability and gas cost issues

 Legal and regulatory challenges

259
Web3 Technologies 8.5.6 Applications of Smart Contracts:
Smart contracts are widely used in:

 Decentralized Finance (DeFi)

 Token and cryptocurrency systems

 NFTs and digital assets

 Supply chain management

 Voting and governance systems

8.5.7 Importance in Web3 Technologies:


Smart contracts are the backbone of Web3 as they enable trustless
execution, decentralized governance, and programmable digital assets,
making them essential for modern blockchain-based systems.

8.6 SOLIDITY PROGRAMMING – CONTRACTS


In Solidity, a contract is the fundamental building block used to create
smart contracts on the Ethereum blockchain. A contract defines the data
(state variables) and behavior (functions) that govern how a decentralized
application operates. Solidity contracts are similar to classes in object-
oriented programming but are executed in a decentralized and immutable
environment.

8.6.1 Definition of a Solidity Contract:


A Solidity contract is a collection of code and data deployed at a specific
address on the blockchain. Once deployed, the contract code cannot be
changed, ensuring transparency and trust.

8.6.2 Structure of a Solidity Contract:


A Solidity contract typically consists of:

 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;
}
}

8.6.3 Types of Contracts in Solidity:


Solidity supports different types of contracts, such as:

 Basic contracts – single standalone contracts

 Inherited contracts – contracts derived from other contracts

 Abstract contracts – contracts with unimplemented functions

 Interface contracts – define function signatures only

 Library contracts – reusable code without state

8.6.4 Contract Deployment:


Solidity contracts are deployed to the blockchain through transactions.
Deployment assigns the contract a unique address and executes its
constructor.

8.6.5 Interaction with Contracts:


Contracts can interact:

 With users (Externally Owned Accounts)

 With other contracts through function calls

261
Web3 Technologies 8.6.6 Visibility and Access Control:
Solidity contracts support access control using:

 Visibility specifiers (public, private, internal, external)

 Modifiers for authorization

8.6.7 Importance of Solidity Contracts:


Solidity contracts are essential because they:

 Enable decentralized logic execution

 Ensure trustless transactions

 Form the core of DApps and Web3 systems


In conclusion, Solidity contracts provide a secure, programmable, and
decentralized framework for building blockchain applications, making
them central to Solidity programming and Web3 Technologies.

8.7 CREATING CONTRACTS


Creating a smart contract is the process of writing, compiling, deploying,
and initializing a contract on a blockchain network. In Solidity, smart
contracts are written as source code files and deployed to the Ethereum
blockchain, where they receive a unique address and become immutable.

8.7.1 Writing a Smart Contract:


The first step in creating a contract is writing the contract code using
Solidity. The code defines the contract’s data and behavior.

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.

8.7.3 Deploying the Contract:


After compilation, the contract is deployed to the blockchain network.
Deployment:

 Creates a new contract address

 Executes the constructor

 Stores bytecode on the blockchain

 Deployment can be done using tools such as:

 Remix IDE

 Truffle

 Hardhat

8.7.4 Constructor Execution:


The constructor is executed once during deployment and is used to
initialize state variables.

Example:
Constructor(uint _value) {
Value = _value;
}

8.7.5 Contract Address:


Once deployed, the contract is assigned a unique blockchain address. This
address is used to interact with the contract.

8.7.6 Interacting with the Contract:


After deployment, users and other contracts can interact with the contract
by calling its functions through transactions.

Example:
[Link](10);

8.7.7 Gas Cost and Considerations:


Creating contracts consumes gas because:
263
Web3 Technologies  Code storage is expensive

 Constructor execution requires computation

 Efficient design helps reduce deployment cost.

8.7.8 Importance of Contract Creation:


Creating contracts enables:

 Deployment of decentralized logic

 Automation of agreements

 Secure and trustless applications


In summary, creating smart contracts is a fundamental process that
transforms Solidity code into executable blockchain applications, forming
the foundation of Web3 Technologies.

8.8 VISIBILITY AND GETTERS


In Solidity, visibility specifiers control where functions and variables can
be accessed from, while getter functions allow reading the values of state
variables. Proper use of visibility and getters improves security,
encapsulation, and controlled access to smart contract data.

8.8.1 Visibility Specifiers:


Solidity provides four visibility specifiers for functions and state variables:

a) Public:

 Accessible from anywhere (inside the contract, derived contracts,


and externally)

 Automatically creates a getter function for state variables

Example:
Uint public count;

b) Private:

 Accessible only within the same contract

 Not accessible from derived contracts or externally

Example:
Uint private secret;

264
c) Internal: Error handling and Smart
Contracts
 Accessible within the contract and derived contracts

 Similar to protected in other languages

Example:
Uint internal data;

d) External:

 Accessible only from outside the contract

 Cannot be called internally without using this

Example:
Function update(uint _value) external {
Value = _value;
}

8.8.2 Visibility of Functions:


Function visibility determines how and where a function can be invoked.

Example:
Function getValue() public view returns (uint) {
Return value;
}

8.8.3 Getter Functions:

 Getter functions are used to retrieve the values of state variables


without modifying the contract state.

 Solidity automatically creates getters for public state variables

 Custom getters can be written for private or complex data

Example (Automatic Getter):


Uint public balance;

Example (Custom Getter):


Uint private secret;
Function getSecret() public view returns (uint) {
Return secret;
265
Web3 Technologies }

8.8.4 Getters for Complex Data Types:


For arrays, mappings, and structs, Solidity provides limited automatic
getters. Custom getter functions are often required.

Example:
Mapping(address =>uint) private balances;
Function getBalance(address user) public view returns (uint) {
Return balances[user];
}

8.8.5 Importance of Visibility and Getters:

 Proper use of visibility and getters:

 Prevents unauthorized access

 Protects sensitive data

 Improves contract security

 Enhances code clarity and maintainability


In summary, visibility specifiers define access control, while getter
functions enable safe data retrieval, making both essential components of
secure Solidity smart contract design.

8.9 FUNCTION MODIFIERS


Function modifiers in Solidity are used to change or restrict the behavior
of functions by adding predefined conditions. They help in code reuse,
access control, and validation, making smart contracts more secure and
readable.

8.9.1 Purpose of Function Modifiers:

 Function modifiers are mainly used to:

 Enforce access control

 Validate conditions before function execution

 Reduce code duplication

 Improve readability and maintainability

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
_;
}

8.9.3 Example of a Function Modifier:


Contract Example {
Address public owner;
Constructor() {
Owner = [Link];
}
Modifier onlyOwner() {
Require([Link] == owner, “Not owner”);
_;
}
Function setValue(uint _value) public onlyOwner {
Value = _value;
}
}

8.9.4 Multiple Modifiers:


A function can have more than one modifier. They are executed in the
order they are specified.

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”);
}

8.9.6 Common Use Cases of Modifiers:


Modifiers are commonly used for:

 Ownership validation

 Role-based access control

 Input validation

 Pausing and resuming contracts

8.9.7 Advantages of Function Modifiers:

 Improves security

 Enhances code reusability

 Simplifies function logic

 Makes contracts easier to audit

8.9.8 Best Practices:

 Keep modifiers simple and readable

 Avoid complex logic inside modifiers

 Use meaningful names

 Prefer modifiers over repeated require statements


In conclusion, function modifiers are a powerful feature in Solidity that
help enforce rules and constraints across functions, ensuring secure and
maintainable smart contract design.

8.10 CONSTANT STATE VARIABLES


In Solidity, constant state variables are variables whose values are fixed at
compile time and cannot be modified after declaration. They are used to
represent values that remain unchanged throughout the lifetime of a smart
contract. Using constants improves code clarity, safety, and gas efficiency.
268
8.10.1 Definition of Constant State Variables: Error handling and Smart
Contracts
A constant state variable is declared using the constant keyword. Its value
must be assigned at the time of declaration and cannot be altered later.

Example:
Uint public constant MAX_LIMIT = 100;
Address public constant ZERO_ADDRESS = address(0);

8.10.2 Characteristics of Constant Variables:


Constant state variables:

 Must be initialized during declaration

 Cannot be modified after deployment

 Are replaced directly in the bytecode

 Do not occupy storage space


8.10.3 Difference between constant and Regular State Variables:
Aspect constant Regular Variable
Modifiable No Yes
Storage No storage Stored on blockchain
Gas cost Lower Higher
Initialization At declaration In constructor or functions

8.10.4 Use Cases of Constant Variables:


Constants are commonly used for:

 Fixed limits and thresholds

 Version identifiers

 Addresses that never change

 Mathematical constants

Example:
Uint constant FEE_PERCENT = 5;

8.10.5 constant vs immutable:


Solidity also provides immutable variables, which are assigned once
during deployment (constructor).
269
Web3 Technologies Example:
Address public immutable owner;
Constructor() {
Owner = [Link];
}

8.10.6 Advantages of Constant State Variables:

 Prevents accidental modification

 Improves contract readability

 Reduces gas consumption

 Enhances security

8.10.7 Importance in Smart Contracts:


Constant state variables help define fixed rules and parameters in smart
contracts, ensuring predictable behavior and efficient execution.
In summary, constant state variables provide a safe and efficient way to
represent unchangeable values, making them an essential feature in
Solidity programming.

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.

8.11.1 Definition of a Function:


A function in Solidity is a named block of code that can accept input
parameters, execute statements, and optionally return output values.

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:

 Public – accessible from anywhere

 Private – accessible only within the contract

 Internal – accessible within the contract and derived contracts

 External – accessible only from outside the contract

Example:
Function getValue() public view returns (uint) {
Return value;
}

8.11.3 State Mutability Specifiers:


State mutability specifies whether a function can modify or read the
contract state.

 View – reads state but does not modify it

 Pure – does not read or modify state

 Payable – can receive Ether

Example:
Function deposit() public payable {
}

8.11.4 Input and Output Parameters:


Functions may accept input parameters and return output values.

Example:
Function add(uint a, uint b) public pure returns (uint) {
Return a + b;
}

8.11.5 Constructor Functions:


A constructor is a special function that is executed only once during
contract deployment.

271
Web3 Technologies Example:
Constructor() {
Owner = [Link];
}

8.11.6 Fallback and Receive Functions:


Special functions used to handle Ether transfers.

 Receive() – called when Ether is sent with empty data

 Fallback() – called when no matching function exists

Example:
Receive() external payable {}
Fallback() external payable {}

8.11.7 Function Overloading:


Solidity allows multiple functions with the same name but different
parameters.

Example:
Function set(uint a) public {}
Function set(uint a, uint b) public {}

8.11.8 Importance of Functions:


Functions are essential for:

 Implementing contract logic

 Enabling user interaction

 Managing state changes

 Supporting contract interoperability


In summary, functions form the core operational units of Solidity smart
contracts, enabling secure, flexible, and efficient execution of
decentralized logic.

8.12 ABSTRACT CONTRACTS


In Solidity, abstract contracts are contracts that contain at least one
function without an implementation. They serve as blueprints for other
contracts and cannot be deployed directly. Abstract contracts are mainly

272
used to define common structure, rules, and behavior that must be Error handling and Smart
Contracts
implemented by derived contracts.

8.12.1 Definition of Abstract Contract:


A contract is considered abstract if:

 It has one or more functions declared but not implemented, or

 It is explicitly marked using the abstract keyword

 Abstract contracts help in achieving abstraction and code reuse.

8.12.2 Syntax of Abstract Contracts:


Syntax:
Abstract contract ContractName {
Function functionName() public virtual returns (type);
}

Example:
Abstract contract Shape {
Function area() public view virtual returns (uint);
}

8.12.3 Implementing Abstract Contracts:


A contract that inherits an abstract contract must implement all its
unimplemented functions, otherwise it will also be abstract.

Example:
Contract Rectangle is Shape {
Uint length;
Uint width;
Function area() public view override returns (uint) {
Return length * width;
}
}

8.12.4 Use of virtual and override:

 Virtual allows a function to be overridden in a derived contract

273
Web3 Technologies  Override is used when implementing or redefining a virtual function

8.12.5 Characteristics of Abstract Contracts:


Abstract contracts:

 Cannot be deployed directly

 Can contain implemented and unimplemented functions

 Support inheritance

 Promote modular design

8.12.6 Difference between Abstract Contracts and Interfaces:


Aspect Abstract Contract Interface
Function implementation Allowed Not allowed
State variables Allowed Not allowed
Constructors Allowed Not allowed
Deployment Cannot deploy Cannot deploy

8.12.7 Use Cases of Abstract Contracts:


Abstract contracts are commonly used for:

 Defining base contract logic

 Enforcing implementation rules

 Creating extensible frameworks

 Building upgradeable contract designs

8.12.8 Importance of Abstract Contracts:


Abstract contracts enable:

 Code reusability

 Clear contract architecture

 Standardized behavior across contracts


In conclusion, abstract contracts provide a powerful mechanism for
abstraction and inheritance, making them an essential feature in Solidity
programming and Web3 Technologies.

274
Error handling and Smart
8.13 INTERFACES Contracts

In Solidity, an interface is a contract-like structure that defines only


function declarations without any implementation. Interfaces are used to
specify how other contracts should interact, enabling standardization and
interoperability between smart contracts.

8.13.1 Definition of Interface:


An interface is a collection of function signatures that a contract must
implement. It acts as a contractual agreement that enforces consistent
behavior across different contracts.

8.13.2 Syntax of Interfaces:


Interfaces are declared using the interface keyword.

Syntax:
Interface InterfaceName {
Function functionName(parameters) external returns (type);
}

Example:
Interface IToken {
Function transfer(address to, uint amount) external returns (bool);
}

8.13.3 Rules of Interfaces:


Interfaces in Solidity follow strict rules:

 Functions must be declared as external

 No function implementation is allowed

 No state variables are allowed

 No constructors are allowed

 Functions can be inherited and implemented

8.13.4 Implementing an Interface:


A contract implementing an interface must define all its functions.

Example:
Contract Token is IToken {

275
Web3 Technologies Function transfer(address to, uint amount) external override returns
(bool) {
Return true;
}
}

8.13.5 Using Interfaces to Interact with Contracts:


Interfaces allow interaction with already deployed contracts without
knowing their internal code.

Example:
IToken token = IToken(tokenAddress);
[Link]([Link], 100);

8.13.6 Difference between Interfaces and Abstract Contracts


Aspect Interface Abstract Contract
Function implementation Not allowed Allowed
State variables Not allowed Allowed
Constructors Not allowed Allowed
Function visibility External only Any

8.13.7 Use Cases of Interfaces:


Interfaces are widely used in:

 ERC token standards (ERC-20, ERC-721)

 Contract-to-contract communication

 Standardized APIs for DApps

 Modular smart contract design

8.13.8 Importance of Interfaces:


Interfaces promote:

 Interoperability

 Loose coupling between contracts

 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.

8.14.1 Definition of a Library:


A library is a collection of functions that can be called by other contracts.
Libraries cannot hold state and cannot receive Ether. They are deployed
only once and reused by multiple contracts.

8.14.2 Syntax of a Library:


Libraries are declared using the library keyword.

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;
}
}

8.14.3 Using Libraries in Contracts:


Libraries can be used by calling their functions directly or by attaching
them to a data type using using for.

Example:
Using MathLib for uint;
277
Web3 Technologies Uint result = [Link](20);

8.14.4 Characteristics of Libraries


Libraries:

 Cannot have state variables

 Cannot receive Ether

 Cannot be destroyed

 Promote code reuse

 Improve security

8.14.5 Internal and External Library Functions:


Internal functions are embedded into the calling contract
External functions require deployment and are called via
DELEGATECALL

8.14.6 Difference between Libraries and Contracts:


Aspect Library Contract
State variables Not allowed Allowed
Ether handling Not allowed Allowed
Deployment Reusable Per instance
Code reuse High Limited
8.14.7 Use Cases of Libraries:
 Libraries are commonly used for:
 Mathematical operations
 Data structure management
 Security utilities
 Standard reusable logic
8.14.8 Advantages of Libraries:
 Reduces code duplication
 Improves maintainability
 Enhances security
 Saves gas

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.

B. Practical / Application-Based Questions


1. Write a Solidity program demonstrating the use of require.
2. Write a contract to show the use of function modifiers.
3. Write a smart contract using constant state variables.
4. Write a Solidity program to demonstrate function visibility.
5. Write a contract using getter functions.
6. Write a Solidity program implementing an abstract contract.
7. Write a contract that implements an interface.
8. Write a Solidity program using a library.
9. Write a program to demonstrate error handling using revert.
10. Write a simple smart contract and explain its working.

*****

280

Common questions

Powered by AI

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 .

You might also like