0% found this document useful (0 votes)
2 views

unit-i-introduction-to-blockchain

The document provides an introduction to blockchain technology, detailing its decentralized nature, key components, and essential features such as transparency, security, and immutability. It explains the importance of blockchain in real-time applications across various industries and outlines the structure of a blockchain block, including its header and body. Additionally, it discusses different types of blockchains, consensus mechanisms, and the role of smart contracts and tokenization.

Uploaded by

yasodhan736
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit-i-introduction-to-blockchain

The document provides an introduction to blockchain technology, detailing its decentralized nature, key components, and essential features such as transparency, security, and immutability. It explains the importance of blockchain in real-time applications across various industries and outlines the structure of a blockchain block, including its header and body. Additionally, it discusses different types of blockchains, consensus mechanisms, and the role of smart contracts and tokenization.

Uploaded by

yasodhan736
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

lOMoARcPSD|47707557

UNIT I Introduction TO Blockchain

cryptocurrency and Blockchain technologies (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by S. Amirthavarshinii ([email protected])
lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

CCS339 CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

UNIT I INTRODUCTION TO BLOCKCHAIN

Blockchain- Public Ledgers, Blockchain as Public Ledgers - Block in a Blockchain, Transactions-


The Chain and the Longest Chain - Permissioned Model of Blockchain, Cryptographic - Hash
Function, Properties of a hash function-Hash pointer and Merkle tree

CO1: Understand emerging abstract models for Blockchain Technology

Blockchain

Blockchain is a decentralized and distributed ledger technology that records transactions across
multiple computers in a secure, immutable, and transparent manner. Unlike traditional centralized
systems, blockchain eliminates the need for a trusted intermediary, relying instead on cryptographic
methods and consensus mechanisms.

Why Do We Require Blockchain in Real-Time?


Blockchain is crucial for solving speciÞc real-time challenges in various industries:
1. Transparency: Provides a tamper-proof and publicly veriÞable transaction history.
2. Security: Prevents unauthorized access and data tampering using cryptographic techniques.
3. EfÞciency: Reduces delays in processes like cross-border payments, supply chain
management, and identity veriÞcation.
4. Decentralization: Removes the need for central authorities, reducing the risks of single
points of failure.
5. Trust: Creates trust among participants in systems where trust is traditionally lacking (e.g.,
Þnance, supply chain).

The key elements of Blockchain are the foundational components that enable its functionality and
distinct characteristics. Here's a breakdown:

1. Distributed Ledger
¥ A shared database where all participants have access to the same version of data.
¥ Each transaction is recorded only once, eliminating duplication.
¥ Example: In Bitcoin, every node has a complete copy of the blockchain.

2. Blocks
¥ The basic units of a blockchain, containing:
◦ Data: Information about the transaction (e.g., sender, receiver, amount).
◦ Hash: A unique identiÞer for the block, generated using cryptography.
◦ Previous BlockÕs Hash: Links the current block to the previous one, forming a
chain.

3. Cryptography
¥ Blockchain uses cryptographic techniques to secure data and ensure its integrity.
¥ Hash Functions: Algorithms like SHA-256 create Þxed-size output (hash) from input data.
¥ Digital Signatures: Verify the authenticity of transactions and participants.

4. Consensus Mechanism
¥ The process used to agree on the validity of transactions.
¥ Ensures trust in a decentralized network without a central authority.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 1 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

¥ Common mechanisms include:


◦ Proof of Work (PoW): Solving computational puzzles (e.g., Bitcoin).
◦ Proof of Stake (PoS): Validators based on ownership of tokens (e.g., Ethereum 2.0).
◦ Delegated Proof of Stake (DPoS): Voting-based system.

5. Peer-to-Peer (P2P) Network


¥ Blockchain operates over a P2P network where each node is equal.
¥ Nodes communicate directly, share data, and validate transactions collaboratively.
¥ Decentralized architecture ensures no single point of failure.

6. Immutability
¥ Once data is recorded in a block and added to the chain, it cannot be altered.
¥ Ensured by cryptographic hashing and the consensus mechanism.
¥ Provides a tamper-proof record of transactions.

7. Smart Contracts
¥ Self-executing programs stored on the blockchain that automatically enforce agreements.
¥ Triggered when predeÞned conditions are met.
¥ Example: Releasing funds only when goods are delivered.

8. Tokenization
¥ The process of converting assets into digital tokens on a blockchain.
¥ Tokens can represent ownership, value, or access rights.
¥ Example: Cryptocurrencies, Non-Fungible Tokens (NFTs).

9. Timestamping
¥ Every transaction on the blockchain is time-stamped, providing an accurate and
chronological order of events.
¥ Ensures data authenticity and enables traceability.

10. Nodes
¥ Computers or devices that participate in the blockchain network.
¥ Types of nodes:
◦ Full Nodes: Maintain a complete copy of the blockchain.
◦ Lightweight Nodes: Rely on full nodes for transaction validation.

11. Decentralization
¥ Removes the need for a central authority, distributing control among participants.
¥ Increases system resilience and reduces the risk of corruption or failure.

12. Validation Process


¥ Every transaction must be validated before being added to the blockchain.
¥ Validation ensures that only legitimate transactions are recorded.

13. Transparency and Privacy


¥ Transactions are visible to participants, promoting transparency.
¥ Cryptographic methods ensure user privacy by concealing identities.

14. Forks
¥ A fork occurs when thereÕs a divergence in the blockchain, leading to multiple versions.
¥ Types of forks:
◦ Soft Fork: Backward-compatible updates.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 2 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Hard Fork: Non-backward-compatible changes, resulting in separate blockchains


(e.g., Bitcoin and Bitcoin Cash).

15. Incentive Mechanism


¥ Participants (e.g., miners, validators) are incentivized with rewards (cryptocurrencies or
tokens) for their contributions to the network.

Key Components of a Blockchain Block:

1. Block Header
The header contains metadata about the block, which is essential for identifying, validating, and
linking blocks together. It includes the following:

¥ Version:
◦ Defines the protocol version used for the current block.
◦ Allows the blockchain protocol to be updated over time (backward compatibility).

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 3 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Example: Bitcoin uses version numbers (e.g., 0x20000000) to signify changes in the
protocol.

¥ Previous Block Hash:


◦ The cryptographic hash of the previous block in the blockchain.
◦ This ensures that all blocks are securely linked in a chain (thus ensuring
immutability).
◦ If even one block is altered, its hash will change, breaking the entire chain's integrity.
◦ Example: In a Bitcoin block, this could be something like:
00000000000000000004f4fd6e7f6d2d4608db4c869db95f0399b1b82b245f3a.

¥ Merkle Root:
◦ The root of a Merkle tree that represents a cryptographic summary of all transactions
in the block.
◦ ItÕs a hash value that ensures integrity by providing a compact representation of the
block's transactions.
◦ Allows efficient and secure verification of transactions without downloading the
entire block.
◦ Example: A Merkle Root could be something like:
f59c699acfd9c9c9ec2c6d22acfa989d44cda9067959ffdf3d5d9703ab7a1d9.

¥ Timestamp:
◦ The time the block was created, typically in seconds from the Unix epoch (1970).
◦ This is important for maintaining the chronological order of blocks in the chain.
◦ Example: 1609459200 represents a timestamp corresponding to January 1, 2021.

¥ Difficulty Target:
◦ Represents the target value that the blockÕs hash must be lower than to be considered
valid.
◦ The difficulty level adjusts over time to ensure that blocks are mined at a steady rate
(e.g., every 10 minutes in Bitcoin).
◦ Example: In Bitcoin, this could be represented by a value like
0000000000000000000ffff.

¥ Nonce:
◦ A random number that miners alter in order to find a valid hash that meets the
difficulty target.
◦ In Proof of Work (PoW), miners iterate different nonce values to discover a hash
below the target, thus solving the puzzle.
◦ Example: 1762347 is an example nonce used to mine a block in Bitcoin.

2. Block Body
The body of the block contains the actual data, specifically the transactions, and it is the part that
miners validate. This data typically includes the following:

¥ Transactions:
◦ A list of all transactions included in the block.
◦ Each transaction includes the following details:
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 4 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

▪ Sender's address (public key or wallet address).


▪ Receiver's address.
▪ Amount (in terms of cryptocurrency, e.g., Bitcoin, Ether).
▪ Digital Signature to validate the authenticity of the transaction.

◦ Example: A typical transaction might look like:


▪ Sender: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
▪ Receiver: 1B7YaA6E8rTfp4Jh8Kyj4gdZP78RQJdpfY
▪ Amount: 0.5 BTC

◦ Transaction IDs:
▪ Each transaction has a unique identifier, calculated by hashing the transaction
data.
▪ Example: A transaction ID could look like:
e3c7df6bc3b062b41f4e2c1efbcfa4a5d77b9d47bb6c000d1b56a5fd4d05dca3.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 5 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Key Features of Blockchain

1. Decentralization
¥ Blockchain eliminates the need for a central authority or intermediary by distributing data
across a network of nodes.
¥ Each participant (node) has access to the entire ledger, ensuring transparency and reducing
dependency on a single entity.
¥ Example: Bitcoin transactions occur directly between parties without involving banks.

2. Transparency
¥ All transactions recorded on the blockchain are visible to participants, ensuring
accountability.
¥ Public blockchains, like Ethereum, allow anyone to verify transaction details while
maintaining user anonymity.

3. Immutability
¥ Once a transaction is recorded on the blockchain, it cannot be altered or deleted.
¥ This feature ensures the integrity of data, making blockchain resistant to fraud and
tampering.
¥ Changes, if necessary, require consensus from the network, maintaining security.

4. Security
¥ Transactions are encrypted using advanced cryptographic algorithms, making them highly
secure.
¥ Features like cryptographic hashing, digital signatures, and consensus mechanisms protect
the network against unauthorized access and attacks.
¥ Example: SHA-256 hash function used in Bitcoin ensures data security.

5. Distributed Ledger
¥ Blockchain is a shared ledger distributed across a network of nodes, ensuring redundancy
and eliminating single points of failure.
¥ Every node maintains a synchronized copy of the ledger, which updates in real time with
new transactions.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 6 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

6. Consensus Mechanisms
¥ Blockchain relies on consensus mechanisms to validate and agree on the state of the ledger.
¥ Popular consensus algorithms include:
◦ Proof of Work (PoW): Used in Bitcoin.
◦ Proof of Stake (PoS): Used in Ethereum 2.0.
◦ Delegated Proof of Stake (DPoS) and Byzantine Fault Tolerance (BFT) for faster
validation.

7. Anonymity and Privacy


¥ Blockchain ensures user anonymity by using alphanumeric public keys instead of personal
details.
¥ Users can conduct transactions without revealing their identity, although public blockchains
may still expose some transaction details.

8. Traceability
¥ Every transaction is time-stamped and recorded in a chronological order, creating a
complete history of activities.
¥ This is particularly useful in supply chain management, where products can be tracked from
origin to destination.

9. Smart Contracts
¥ A smart contract is a self-executing program with predeÞned conditions that automatically
enforces agreements.
¥ These contracts eliminate the need for intermediaries, reducing costs and enhancing
efÞciency.
¥ Example: Escrow services for digital payments using Ethereum.

10. Programmability
¥ Blockchain can be programmed to execute custom operations, such as triggering payments
or notiÞcations based on certain conditions (via smart contracts).
¥ This feature enables the creation of decentralized applications (DApps).

11. High Availability


¥ Blockchain networks remain operational as long as at least one node is active.
¥ This resilience ensures continuous service, even during network attacks or node failures.

12. Tokenization
¥ Blockchain allows the creation of digital assets or tokens representing ownership, rights, or
value.
¥ Tokens can represent physical assets (e.g., real estate), digital assets (e.g., NFTs), or access
rights.

13. Reduced Costs


¥ By eliminating intermediaries and automating processes, blockchain reduces transaction
costs signiÞcantly.
¥ For example, cross-border payments using blockchain are faster and cheaper than traditional
banking systems.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 7 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Type of
Description Access Control Use Cases Examples
Blockchain
Fully decentralized network - Cryptocurrencies
where anyone can join, read, (Bitcoin,
Public Open to anyone; - Bitcoin
write, and validate Ethereum).
Blockchain no restrictions. - Ethereum
transactions. Transactions - Decentralized
are visible to all participants. Þnance (DeFi).
Centralized network
- Supply chain
controlled by a single Limited to
Private management. - Hyperledger
organization. Access is authorized
Blockchain - Internal enterprise - Quorum
restricted to selected users.
operations.
participants.
Partially decentralized - Interbank
Consortium network managed by a group Restricted to payment systems. - R3 Corda
(Federated) of organizations. Pre- member - Collaborative - Energy Web
Blockchain selected participants validate organizations. enterprise Chain
transactions. applications.
Combines elements of public - Healthcare
and private blockchains. systems.
Hybrid Access control
Some data is public, while - Government - Dragonchain
Blockchain is customizable.
sensitive information is records (e.g., voting
restricted. systems).
A blockchain connected to a
main chain, used for speciÞc - Scalability - Liquid
Dependent on
purposes or scalability. solutions. Network
Sidechain the main chainÕs
Assets can move between - Gaming - Loom
conÞguration.
the main chain and applications. Network
sidechain.
Controlled by a single - Banking systems
organization but allows Restricted; for external audits. - Ripple
Semiprivate
speciÞc authorized limited public - Government and (partially
Blockchains
participants for external participation. NGO semiprivate)
collaboration. collaborations.
Blockchain where
participants need permission Restricted; only - Enterprise supply
Permissione - Hyperledger
to join or validate approved chains.
d Ledger Fabric
transactions. Provides participants. - Financial services.
controlled transparency.
A distributed ledger shared - Distributed data
Depends on
Shared across multiple participants storage.
conÞguration - MultiChain
Ledger in a network, promoting - Collaborative
(public/private).
collaboration. applications.
Fully Controlled and operated - Internal record- - IBM
Fully restricted
Private and entirely by a single entity. keeping. Blockchain
to the
Proprietary No external access or - Compliance (private
organization.
Blockchains participation allowed. tracking. solutions)
Blockchains that use tokens Open or
- Cryptocurrencies.
Tokenized or cryptocurrencies to restricted based - Bitcoin,
- Decentralized
Blockchains incentivize transactions and on blockchain Ethereum
Þnance (DeFi).
provide economic value. type.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 8 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Blockchains that do not rely - Enterprise


Open or
Tokenless on tokens; focus on applications. - Hyperledger,
restricted based
Blockchains decentralized data - Data integrity Quorum
on use case.
management and trust. systems.

How Blockchain Differs From Other Technologies

Traditional Cloud Distributed


Aspect Blockchain
Databases Computing Systems

Linked blocks using Centralized or Distributed but


Data Structure Tables and rows
cryptographic hashes hybrid centralized control
Partially
Decentralization Fully decentralized Centralized Hybrid
decentralized
Cryptographic Vulnerable to Security
Varies with
Security integrity and single-point depends on
implementation
consensus attacks provider
Access restricted
Open and veriÞable Limited to Varies with system
Transparency by admin
by all participants internal users design
permissions
Data can be
Transactions are Not inherently Can be altered by
Immutability updated or
immutable immutable central control
deleted
Requires third- May need
No need for Depends on
Intermediaries party centralized
intermediaries architecture
intermediaries coordination

The detailed comparison between Distributed System Architecture and Centralized System
Architecture in the context of blockchain were,
Feature Distributed System (Blockchain) Centralized System
Decentralized control; no single Centralized control; one entity has
Control
authority manages the system. full control over the system.
Data is distributed across multiple Data is stored in a single location or
Data Storage
nodes in the network. server.
No single point of failure; the system A single point of failure exists; if the
Single Point of
remains operational even if some central server fails, the system goes
Failure
nodes fail. down.
High security due to cryptography and Vulnerable to breaches if the central
Security
consensus mechanisms. server is compromised.
Ensured through consensus protocols Depends on the central authority to
Data Integrity
and immutability of blocks. maintain data integrity.
Transactions are transparent and Transparency is limited to what the
Transparency
visible to all participants. central authority allows.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 9 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Scalability can be challenging, Typically more scalable due to


Scalability
especially in public blockchains. centralized control.
Higher initial cost due to network- Lower initial cost, but maintenance
Cost
wide validation and redundancy. and scalability can increase costs.
No need to trust a central authority; Requires trust in the central authority
Trust Requirement
trust is in the system's design. managing the system.
Slower due to decentralized consensus Faster as a central authority
EfÞciency
mechanisms. processes transactions directly.
Limited privacy in public blockchains; Privacy depends on the central
Privacy
pseudonymity is common. authorityÕs policies.
High redundancy; all nodes store a Limited redundancy; often relies on
Redundancy
copy of the ledger. backups managed centrally.
Open access in public blockchains;
Access is controlled and limited by
Access permissioned blockchains allow
the central authority.
restricted access.
Highly resilient; the system remains Less resilient; system failure can
Resilience operational as long as some nodes are occur if the central server is
active. compromised.
Data ownership is distributed among Data is owned and controlled by the
Ownership of Data
participants. central authority.
Decisions are made by the central
Consensus Decisions are made collectively using
authority without collective
Mechanism consensus protocols (e.g., PoW, PoS).
agreement.
Changes require network-wide Changes can be implemented directly
System Updates
agreement or consensus. by the central authority.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 10 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Layers of Blockchain

Blockchain technology is structured into multiple layers, each with a distinct role in ensuring the
security, decentralization, and efÞciency of the system. Below is a detailed breakdown of the
layers of blockchain:

1. Infrastructure Layer (Hardware & Networking Layer)


This is the foundational layer, consisting of the physical components and networking protocols that
facilitate blockchain operations.
Key Components:
¥ Nodes: Computers that participate in the blockchain network by validating and relaying
transactions.
¥ Miners/Stakers: Specialized nodes that validate transactions based on consensus
mechanisms (e.g., Proof of Work, Proof of Stake).
¥ Networking Protocols: Uses TCP/IP, Peer-to-Peer (P2P) protocols to allow decentralized
communication between nodes.
Role in Blockchain:
¥ Ensures seamless communication between nodes.
¥ Maintains the distributed nature of blockchain by enabling global access.
¥ Provides computational power for executing transactions and mining new blocks.

2. Data Layer (Storage & Cryptographic Layer)


This layer handles data storage, including transactions, cryptographic security, and the blockchain
ledger.
Key Components:
¥ Blocks: The fundamental unit of storage, containing transactions and metadata.
¥ Transactions: The records of digital asset transfers stored inside blocks.
¥ Cryptographic Hashing: Uses algorithms like SHA-256 (Bitcoin) or Keccak-256
(Ethereum) to ensure data integrity.
¥ Merkle Tree: A data structure that helps efÞciently verify large data sets.
¥ Hash Pointers: Links each block to the previous one, ensuring immutability.
Role in Blockchain:
¥ Stores immutable transaction history.
¥ Ensures tamper-proof security via cryptographic hashing.
¥ Reduces data redundancy using efÞcient structures like Merkle Trees.

3. Network Layer (Propagation & Communication Layer)


This layer is responsible for node-to-node communication, transaction propagation, and block
validation across the network.
Key Components:
¥ Node Discovery: Mechanism by which new nodes Þnd existing ones to join the network.
¥ Transaction Propagation: Transactions are broadcasted to all nodes for validation.
¥ Block Propagation: Validated blocks are shared across the network for ledger updates.
Role in Blockchain:
¥ Enables peer-to-peer (P2P) networking to ensure decentralization.
¥ Ensures that transactions and new blocks reach all participants efÞciently.
¥ Helps maintain consensus by distributing veriÞed transactions.

4. Consensus Layer (Validation & Agreement Layer)


Description:
This layer enforces rules for transaction veriÞcation, ensuring that all participants agree on the state
of the blockchain without a central authority.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 11 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Key Consensus Mechanisms:


Consensus
Description Example Blockchain
Mechanism
Nodes (miners) solve cryptographic puzzles to Bitcoin, Ethereum
Proof of Work (PoW)
validate transactions. (before ETH 2.0)
Validators stake their cryptocurrency to validate
Proof of Stake (PoS) Ethereum 2.0, Cardano
blocks.
Participants "burn" (destroy) coins to earn mining
Proof of Burn (PoB) Slimcoin
rights.
Proof of Elapsed Uses a trusted execution environment (TEE) to
Hyperledger Sawtooth
Time (PoET) randomly select validators.
Delegated Proof of Users vote for delegates to validate transactions
EOS, Tron
Stake (DPoS) on their behalf.
Role in Blockchain:
¥ Ensures that all nodes agree on the correct state of the ledger.
¥ Prevents fraudulent transactions and attacks like double spending.
¥ Enables security and trust in a decentralized system.

5. Smart Contract Layer (Execution Layer)


This layer enables automated and programmable agreements (smart contracts) that execute
based on predeÞned conditions.
Key Components:
¥ Smart Contracts: Self-executing contracts written in languages like Solidity (Ethereum)
and Chaincode (Hyperledger Fabric).
¥ Virtual Machines:
◦ Ethereum Virtual Machine (EVM): Runs Ethereum-based smart contracts.
◦ Hyperledger Fabric Chaincode: Executes smart contracts in enterprise
blockchains.
¥ Decentralized Oracles: Provide external data to smart contracts.
Role in Blockchain:
¥ Automates business processes without intermediaries.
¥ Enhances transparency by executing contracts publicly on the blockchain.
¥ Reduces fraud by ensuring that agreements execute as programmed.

6. Application Layer (User Interface Layer)


This is the topmost layer, where users interact with blockchain applications. It includes
decentralized apps (DApps) and front-end interfaces.
Key Components:
¥ DApps (Decentralized Applications): Applications running on blockchain without
centralized control. Examples: Uniswap, OpenSea, Metamask.
¥ APIs (Application Programming Interfaces): Used by developers to interact with
blockchain networks.
¥ Wallets: Digital wallets for storing and managing cryptocurrencies (e.g., Metamask, Trust
Wallet).
¥ User Interfaces (UI): Websites, mobile apps, and dashboards that simplify blockchain
interaction.
Role in Blockchain:
¥ Provides access to blockchain functionalities for end-users.
¥ SimpliÞes complex blockchain processes using user-friendly interfaces.
¥ Enables the adoption of blockchain technology in various industries.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 12 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Why Blockchain is a Game-Changer?


1. Decentralized Finance (DeFi): Enables trustless Þnancial systems without banks.
2. Smart Contracts: Automates and enforces agreements without manual intervention.
3. Supply Chain Transparency: Tracks goods from origin to destination, reducing fraud and
inefÞciencies.
4. Digital Identity: Offers secure, self-sovereign identities for individuals and businesses.
5. Healthcare: Safeguards patient records and ensures interoperability across providers.
6. Energy Management: Promotes peer-to-peer energy trading, making renewable energy
more accessible.

Implementation of Blockchain
Blockchain technology provides a decentralized and secure method of recording
transactions. Implementing a blockchain network involves selecting the right platform, setting up
nodes, developing smart contracts, and ensuring security and scalability.

Platforms and Frameworks:


◦ Public Blockchains: Bitcoin, Ethereum (permissionless and accessible to everyone).
◦ Private Blockchains: Hyperledger, Corda (permissioned systems for enterprise use).
Key Components:
◦ Cryptographic Hashing: Secures transactions and links blocks.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 13 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Consensus Mechanisms: Ensures agreement among participants (e.g., Proof of


Work, Proof of Stake).
◦ Smart Contracts: Enables programmable agreements.
◦ Peer-to-Peer Network: Facilitates decentralized communication.
Steps in Implementation:
◦ DeÞne the use case and objectives.
◦ Select an appropriate blockchain platform.
◦ Develop smart contracts or applications.
◦ Set up nodes and conÞgure the network.
◦ Test for scalability, security, and functionality.

1. Blockchain Platforms and Frameworks


The first step in implementing a blockchain network is choosing an appropriate blockchain
framework. Blockchain platforms are classified into two main categories:
A. Public Blockchains (Permissionless)
Public blockchains are decentralized and allow anyone to participate in the network. They
are open to all users without restrictions.
¥ Bitcoin: The first and most widely used public blockchain, mainly designed for peer-to-
peer transactions.
¥ Ethereum: A decentralized platform that supports smart contracts and decentralized
applications (DApps).
¥ Solana: A high-speed blockchain optimized for scalability and low transaction fees.
¥ Cardano: A blockchain focusing on security and sustainability through a peer-reviewed
research approach.
B. Private Blockchains (Permissioned)
Private blockchains are restricted and controlled by organizations, offering more security,
scalability, and privacy.
¥ Hyperledger Fabric: A modular and permissioned blockchain for enterprise
applications.
¥ Corda: A blockchain designed for financial services and enterprise transactions.
¥ Quorum: An Ethereum-based private blockchain optimized for enterprise needs.

2. Key Components of Blockchain Implementation


A blockchain network consists of various components that ensure security, transparency, and
decentralization.
A. Cryptographic Hashing
¥ Every transaction and block in a blockchain is secured using cryptographic hash functions.
¥ A cryptographic hash function (e.g., SHA-256) converts input data into a fixed-length hash.
¥ Hashing ensures data integrity and prevents tampering.
Formula: SHA-256 Hashing
H(M)=SHA−256(M)
where:
• M is the input data (transaction or block)
• H(M) is the unique hashed output
Example:
import hashlib
message = "Blockchain Implementation"
hashed_message = hashlib.sha256(message.encode()).hexdigest()

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 14 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

print("SHA-256 Hash:", hashed_message)

B. Consensus Mechanisms
Consensus algorithms ensure agreement among participants about the state of the blockchain.
1. Proof of Work (PoW): Used in Bitcoin, requiring miners to solve complex mathematical
puzzles.
2. Proof of Stake (PoS): Validators are chosen based on the number of coins they hold.
3. Delegated Proof of Stake (DPoS): Users vote for delegates who validate transactions.
4. Practical Byzantine Fault Tolerance (PBFT): Used in Hyperledger Fabric for fast and
efÞcient consensus.

import hashlib
import time

def proof_of_work(last_proof):
proof = 0
while not valid_proof(last_proof, proof):
proof += 1
return proof

def valid_proof(last_proof, proof):


guess = f"{last_proof}{proof}".encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"

start = time.time()
new_proof = proof_of_work(100)
end = time.time()

print("New Proof:", new_proof)


print("Time Taken:", end - start)

C. Smart Contracts
Smart contracts are self-executing programs stored on the blockchain that automatically execute
transactions when predeÞned conditions are met.
Example of an Ethereum smart contract in Solidity:
// SPDX-License-IdentiÞer: MIT
pragma solidity ^0.8.0;

contract SimpleContract {
uint256 public count;

function increment() public {


count += 1;
}
}

D. Peer-to-Peer (P2P) Network


A decentralized network where each participant (node) validates transactions and stores a copy of
the blockchain.
Example of P2P Network Simulation
import socket
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 15 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

class PeerNode:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.peers = []

def add_peer(self, peer_ip, peer_port):


self.peers.append((peer_ip, peer_port))

# Example usage
node1 = PeerNode("192.168.1.1", 5001)
node2 = PeerNode("192.168.1.2", 5002)
node1.add_peer(node2.ip, node2.port)

print("Node 1 Peers:", node1.peers)

3. Steps in Blockchain Implementation


Step 1: DeÞne the Use Case and Objectives
¥ Identify the problem blockchain will solve.
¥ Decide whether to use a public, private, or hybrid blockchain.
¥ DeÞne the required security, scalability, and cost constraints.
Step 2: Select the Blockchain Platform
¥ Choose a suitable platform based on use case and requirements.
¥ Public blockchains like Ethereum for DApps, or private blockchains like Hyperledger for
enterprises.
Step 3: Develop Smart Contracts and Applications
¥ Implement smart contracts to automate business processes.
¥ Use Solidity for Ethereum or Chaincode for Hyperledger.

package main

import (
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

type SmartContract struct {


contractapi.Contract
}

func (s *SmartContract) InitLedger(ctx contractapi.TransactionContextInterface) error {


fmt.Println("Blockchain Initialized")
return nil
}

Step 4: Set Up Nodes and ConÞgure the Network


¥ ConÞgure blockchain nodes to validate transactions.
¥ Set up peers, orderers, and certiÞcate authorities (CA) for permissioned networks.
Example: Setting Up a Hyperledger Fabric Network
cd fabric-samples/test-network
./network.sh up
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 16 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

./network.sh createChannel
Step 5: Test for Scalability, Security, and Functionality
¥ Perform load testing to check the scalability of the blockchain.
¥ Simulate attacks to assess security vulnerabilities.
¥ Validate transactions using blockchain explorers.
Example: Querying Hyperledger Fabric
peer chaincode query -C mychannel -n mychaincode -c '{"Args":["queryFunction", "arg1"]}'

4. Deployment and Maintenance


After successful testing, deploy the blockchain network on a cloud-based infrastructure such as:
¥ AWS Blockchain: Offers managed blockchain services.
¥ IBM Blockchain Platform: Provides enterprise-grade Hyperledger Fabric solutions.
¥ Azure Blockchain Service: Supports Ethereum-based solutions.
Maintenance Strategies
¥ Regularly update smart contracts.
¥ Monitor node performance and transaction throughput.
¥ Implement security patches to prevent vulnerabilities.

Complexities in Blockchain Implementation


1. Scalability:
◦ Public blockchains like Bitcoin face limitations in transaction throughput.
◦ Solutions like sharding or Layer 2 protocols (e.g., Lightning Network) aim to
address this.
2. Energy Consumption:
◦ Mining-based blockchains (e.g., Bitcoin) require signiÞcant computational resources.
◦ Transitioning to Proof of Stake reduces energy use but introduces new challenges.
3. Regulatory Challenges:
◦ Governments and institutions are still formulating blockchain policies.
◦ Legal and compliance issues may arise, especially with cryptocurrencies.
4. Interoperability:
◦ Lack of standardization makes communication between different blockchains
challenging.
5. Security Threats:
◦ 51% attacks, smart contract vulnerabilities, and phishing remain concerns.
6. Adoption Barriers:
◦ Businesses may face resistance to change due to lack of expertise and perceived
risks.

Advantages of Blockchain
1. Transparency: Public visibility of transactions builds trust.
2. Security: Immutable records reduce fraud and unauthorized access.
3. Decentralization: Eliminates single points of failure.
4. EfÞciency: Reduces time and costs associated with intermediaries.
5. Automation: Smart contracts streamline processes.

Disadvantages of Blockchain
1. Energy-Intensive: Proof of Work systems consume large amounts of energy.
2. Scalability Issues: Limited transaction speeds and high costs in public blockchains.
3. Complexity: Implementing blockchain solutions requires specialized knowledge.
4. Regulatory Uncertainty: Changing policies can impact blockchain adoption.
5. Data Privacy: Public blockchains expose transaction details, posing privacy concerns.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 17 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

6. High Initial Costs: Development and deployment can be expensive.

Peer-to-Peer (P2P) network

A Peer-to-Peer (P2P) network in blockchain is a decentralized communication architecture


where nodes (computers or devices) interact directly with each other without relying on a central
server or authority. Each node in a P2P network functions as both a client and a server, sharing
resources and data, enabling efÞcient and transparent communication across the system. It includes,

1. Describing Ownership
¥ Ownership in a P2P ledger is deÞned through cryptographic keys:
◦ Public Key: IdentiÞes the owner publicly.
◦ Private Key: Grants control and authority over the assets or data associated with the
public key.
¥ Transactions in the ledger explicitly transfer ownership from one public key to another,
ensuring that ownership is clear and traceable.

2. Protecting Ownership
¥ Ownership protection is achieved using cryptographic techniques:
◦ Digital Signatures: Owners sign transactions using their private key to authorize
actions. This ensures authenticity and prevents forgery.
◦ Immutability: Once a transaction is added to the ledger, it cannot be altered,
safeguarding ownership records from tampering.
◦ Decentralization: Multiple copies of the ledger are distributed across the network,
making it nearly impossible for malicious actors to alter ownership details without
detection.

3. Storing Transaction Data


¥ All transaction data is stored in a distributed ledger, where:
◦ Transactions are grouped into blocks and linked together in a chain.
◦ Each block contains a hash pointer to the previous block, ensuring a chronological
and tamper-evident record.
◦ Nodes in the network store the full or partial copy of the ledger, ensuring
redundancy.

4. Preparing Ledgers to Be Distributed in an Untrustworthy Environment


¥ The P2P system is designed for environments where participants may not trust each other.
Security and trust are established through:
◦ Consensus Mechanisms: Agreement protocols (e.g., Proof of Work, Proof of Stake)
ensure that only valid transactions are added to the ledger.
◦ Cryptographic Hashing: Ensures data integrity by detecting any alterations to the
ledger.
◦ Permissionless or Permissioned Models: Public blockchains allow anyone to
participate, while private blockchains restrict access to trusted participants.

5. Distributing the Ledgers


¥ In a P2P system:
◦ Each node in the network maintains a copy of the ledger.
◦ New blocks and transactions are broadcast to all nodes using a gossip protocol or
similar mechanisms.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 18 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Nodes independently verify the data before updating their copy, ensuring consistency
across the network.

6. Adding New Transactions to the Ledgers


¥ The process of adding transactions involves:
◦ Transaction Creation: Users sign and broadcast their transactions to the network.
◦ Validation: Nodes validate the transaction using consensus rules (e.g., verifying
signatures and checking for double-spending).
◦ Block Creation: Valid transactions are grouped into a block by a miner or validator.
◦ Consensus: The network reaches an agreement on the new block through a
consensus mechanism.
◦ Ledger Update: Once conÞrmed, the block is added to the ledger, and all nodes
update their copies.

7. Deciding Which Ledger Represents the Truth


¥ The truth in a P2P system is determined by:
◦ Longest Chain Rule: In blockchain networks like Bitcoin, the chain with the most
computational work or the longest chain is considered the valid ledger.
◦ Consensus Mechanism: Protocols like Proof of Stake or Practical Byzantine Fault
Tolerance (PBFT) ensure that participants agree on a single version of the ledger.
◦ Conßict Resolution: If multiple versions of the ledger exist temporarily, nodes
follow the consensus rules to decide which version is correct.

Why do we use a Peer-to-Peer (P2P) Network in Blockchain?


1. Decentralization
¥ In a P2P network, all nodes (participants) are equal, and thereÕs no central authority
controlling the network.
¥ This ensures that no single entity can manipulate, censor, or control the data.
¥ In contrast, traditional systems rely on a centralized server, making them vulnerable to
failure or corruption.

2. Fault Tolerance and Reliability


¥ P2P networks are highly resilient because data is replicated across multiple nodes.
¥ Even if some nodes fail or go ofßine, the network remains operational.
¥ Traditional Systems: A central server crash can disrupt services entirely, causing downtime
and potential data loss.

3. Security
¥ P2P networks leverage cryptographic techniques and consensus mechanisms to ensure data
integrity and prevent unauthorized access.
¥ In a decentralized system, there is no single point of failure, making it highly resistant to
hacking and Distributed Denial-of-Service (DDoS) attacks.
¥ Traditional Systems: Centralized databases are prime targets for attackers, as
compromising the central server exposes the entire network.

4. Transparency and Trust


¥ In a P2P blockchain, every participant has access to the same version of the ledger,
promoting transparency.
¥ Transactions are validated by consensus, ensuring trust without the need for intermediaries.
¥ Traditional Systems: Rely on trusted third parties, which may introduce bias, inefÞciency,
or additional costs.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 19 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

5. Elimination of Intermediaries
¥ P2P networks enable direct transactions between participants without requiring a
middleman.
¥ This reduces costs, increases efÞciency, and avoids delays caused by intermediaries.
¥ Example: In Bitcoin, users can send payments directly without involving banks or payment
processors.

6. Scalability
¥ P2P networks can scale more effectively as new nodes join the network, increasing overall
computational power and storage capacity.
¥ Traditional Systems: Scaling requires costly infrastructure upgrades to a centralized server,
which has physical and performance limitations.

7. Cost-Effectiveness
¥ P2P networks distribute computational and storage tasks across all nodes, reducing the need
for expensive centralized infrastructure.
¥ Traditional Systems: Require signiÞcant investment in server maintenance, security
measures, and intermediary fees.

8. Censorship Resistance
¥ In a P2P blockchain, no central entity can censor or block transactions.
¥ Nodes validate transactions based on predeÞned consensus rules, ensuring equal treatment
of all participants.
¥ Traditional Systems: Central authorities can block, reverse, or control access to services,
depending on their policies.

9. Data Integrity and Immutability


¥ Each block in a blockchain is linked to the previous one using cryptographic hashes.
¥ The P2P network ensures that all nodes agree on the state of the ledger, preventing
tampering or data loss.
¥ Traditional Systems: Centralized data storage is more susceptible to unauthorized changes
or accidental loss.

10. Global Accessibility


¥ A P2P blockchain network is accessible from anywhere in the world, provided there is an
internet connection.
¥ This makes blockchain ideal for global applications, such as cryptocurrency and cross-
border payments.
¥ Traditional Systems: Geographic boundaries and regulations often restrict access to
centralized services.

Feature P2P Network Traditional Centralized System


Centralized; controlled by a single
Control Decentralized; control is distributed.
entity.
Single point of failure; prone to
Reliability Highly fault-tolerant and resilient.
outages.
Security Resistant to hacking and DDoS attacks. Vulnerable to centralized breaches.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 20 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Reduced intermediary and infrastructure High maintenance and operational


Cost
costs. costs.
Limited visibility, controlled by
Transparency Open and accessible ledger.
authority.
Scalability Grows with network participants. Limited by server capacity.

Challenges of P2P in Blockchain


While P2P networks offer numerous advantages, they also introduce some complexities:
¥ Latency: Consensus mechanisms can introduce delays in transaction conÞrmation.
¥ Energy Consumption: Some systems (e.g., Bitcoin's Proof of Work) consume signiÞcant
energy.
¥ Storage Requirements: Nodes must store the entire blockchain, which can grow large over
time.

Public Ledgers

A public ledger is a key concept in blockchain technology, serving as a transparent, decentralized


record of all transactions that occur on a blockchain network. It is an open, immutable system
accessible to all participants.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 21 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

A public ledger is a digital ledger maintained across a decentralized network, where all transactions
are recorded chronologically and are visible to anyone. It is the backbone of blockchain-based
systems like Bitcoin and Ethereum.

Key Features of Public Ledgers

1. Transparency
◦ Every participant can view all transactions recorded on the ledger.
◦ This openness ensures trust and accountability among users.
2. Decentralization
◦ No single entity controls the ledger. Instead, it is distributed across a peer-to-peer
network.
◦ All nodes maintain a synchronized copy of the ledger.
3. Immutability
◦ Once a transaction is recorded and added to the ledger, it cannot be altered or
deleted.
◦ This feature ensures the integrity and reliability of the ledger.
4. Cryptographic Security
◦ Transactions are secured using cryptographic algorithms, ensuring that only
authorized participants can initiate transactions.
5. Consensus Mechanisms
◦ Transactions are validated through consensus mechanisms like Proof of Work (PoW)
or Proof of Stake (PoS).
◦ This ensures that only legitimate transactions are added to the ledger.

Advantages of Public Ledgers


1. Transparency and Trust
◦ All transactions are visible, fostering trust among participants.
◦ Ideal for use cases requiring openness, such as supply chain tracking and public
records.
2. Security
◦ Decentralization and cryptographic techniques make the ledger highly secure.
◦ Tampering with the ledger would require controlling over 50% of the network (e.g.,
51% attack), which is computationally infeasible in large networks.
3. Auditability
◦ Transactions are time-stamped and recorded chronologically, making the ledger easy
to audit.
◦ Suitable for applications in Þnance, legal contracts, and compliance.
4. Decentralization
◦ Eliminates the need for a central authority, reducing the risk of corruption and
failure.
5. EfÞciency
◦ Reduces reliance on intermediaries, enabling faster and cheaper transactions.
Challenges of Public Ledgers
1. Scalability
◦ As the network grows, the ledger becomes larger, requiring signiÞcant storage and
computational resources.
◦ Solutions like Layer 2 technologies and sharding are being developed to address this
issue.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 22 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

2. Energy Consumption
◦ Some consensus mechanisms, like Proof of Work, consume large amounts of energy.
◦ Transitioning to more energy-efÞcient mechanisms (e.g., Proof of Stake) is a priority.
3. Privacy Concerns
◦ While transactions are pseudonymous, public accessibility may expose patterns or
sensitive information.
◦ Techniques like zero-knowledge proofs (e.g., zk-SNARKs) are being used to
enhance privacy.
4. Regulatory Challenges
◦ The openness of public ledgers can clash with regulations requiring data
conÞdentiality or control.

Applications of Public Ledgers


1. Cryptocurrencies
◦ Bitcoin and Ethereum use public ledgers to record all cryptocurrency transactions.
◦ Users can verify transactions independently.
2. Supply Chain Management
◦ Tracks the journey of goods from origin to destination, ensuring transparency and
authenticity.
3. Voting Systems
◦ Public ledgers ensure transparency and integrity in digital voting processes.
4. Identity Management
◦ A decentralized ledger can securely manage digital identities without relying on
central authorities.
5. Healthcare
◦ Enables secure sharing of medical records while maintaining patient privacy.
6. Land Registry
◦ Public ledgers can maintain tamper-proof records of property ownership and
transactions.

Feature Public Ledger Traditional Ledger


Open to everyone, anyone with internet Restricted to speciÞc entities or users
Access
access can view the ledger. based on permissions.
Decentralized, no single entity has Centralized, controlled by a single
Control
control over the entire ledger. authority or organization.
High transparency, all transactions are
Limited transparency, visible only to
Transparency publicly visible (depending on the
authorized parties.
system).
Once data is written, it cannot be
Data can be modiÞed or deleted by
Immutability altered or deleted (unless speciÞcally
authorized users.
designed for changes).
Highly secure due to encryption,
Security depends on internal controls
consensus mechanisms, and
Security and access policies. Vulnerable to data
decentralized nature. Tampering is
breaches and insider attacks.
extremely difÞcult.
Transactions are veriÞed by the
network through consensus Transactions are authorized by the
Consensus
mechanisms (e.g., Proof of Work, Proof central authority or administrator.
of Stake).

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 23 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Full audit trail with a permanent record


Audit trail depends on the system,
Auditability of all transactions, providing complete
often incomplete or editable.
traceability.
Reliability is dependent on the central
Highly reliable, no single point of
authority or infrastructure. Single
Reliability failure. Network failure doesn't
points of failure can cause system
compromise the system.
outages.
Can be limited by the consensus
Easier to scale vertically (adding more
mechanism (e.g., transaction speed
resources to central servers), but
Scalability issues with Proof of Work). However,
scaling horizontally may be complex in
scalability solutions like sharding are
highly distributed systems.
being implemented.
Slower in transaction processing,
especially in systems like Bitcoin (due Faster transactions and record-keeping,
EfÞciency to consensus mechanisms). Transaction with minimal processing time and
speed can be improved with Layer 2 centralized control.
solutions.
High computational and energy costs Lower operational costs, as it is
Cost (e.g., for Proof of Work systems). Can centrally managed and doesn't require
become costly as the network grows. massive resources like PoW consensus.
Ensured by cryptographic hashing,
Relies on internal controls and
consensus, and decentralization. ItÕs
Data Integrity administrative privileges. Can be
difÞcult to tamper with data once
tampered with if access is granted.
added.
Disputes are resolved through
Disputes are handled by the central
Dispute consensus mechanisms and immutable
authority or organization based on
Resolution transaction logs. Legal frameworks
internal policies or rules.
may need to be integrated.
Fixed rules deÞned by the blockchain More ßexible as the administrator can
Flexibility protocol. Changes to the protocol are modify the system rules, data structure,
slow and require network consensus. and permissions quickly.
Pseudonymous in public blockchains,
Can provide higher privacy through
but transactions are visible to all users.
Privacy restricted access and encryption
Some solutions (like ZK-SNARKs)
mechanisms.
enhance privacy.
Once added to the blockchain,
Transaction Transactions can be reversed or
transactions are considered Þnal and
Finality modiÞed, depending on the system.
immutable.
No intermediaries required in most Often requires intermediaries (banks,
Intermediaries blockchain systems. Direct peer-to-peer brokers, auditors) for veriÞcation,
transactions. approval, or reconciliation.
Can be higher, especially for systems
Lower, as it is controlled by a central
Cost of using Proof of Work or requiring high
entity managing the ledger and making
Maintenance levels of redundancy. Maintenance is
adjustments as needed.
distributed across the network.
More straightforward compliance with
Regulatory uncertainty exists, as
Regulatory existing legal and regulatory systems,
decentralized systems challenge
Compliance as the central authority ensures
traditional regulatory frameworks.
adherence.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 24 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Blockchain as Public Ledgers

Public ledgers, like those used in blockchain networks, are decentralized, transparent, and
immutable records of transactions that are accessible to all participants. Below is a detailed
description of the key processes involved in how a public ledger works. It includes,

1. Transaction Initiation
¥ User Action: A user initiates a transaction, typically by sending cryptocurrency or digital
assets to another user. This can be done through a wallet or a smart contract interface.
¥ Transaction Data: The transaction includes the sender's address, recipient's address,
transaction amount, and potentially additional data (such as fees or smart contract code).
¥ Broadcast to Network: After initiating the transaction, it is broadcast to the entire network
of nodes (computers participating in the blockchain), ensuring that all participants are aware
of the transaction.

2. Transaction Validation
¥ Consensus Mechanism: The network nodes employ a consensus mechanism (like Proof of
Work, Proof of Stake, etc.) to validate the transaction. The role of miners or validators is to
ensure that the transaction is legitimate and that it follows the rules of the blockchain.
¥ Balance VeriÞcation: One of the key validation steps is ensuring that the sender has
sufÞcient funds in their account (or balance) to complete the transaction. This prevents fraud
and ensures the integrity of the blockchain.
¥ Validation Criteria: In addition to balance checks, validators check that the transaction
meets all other necessary criteria, such as correct formatting, authenticity of the signature,
and compliance with the protocol.

3. Block Creation
¥ Grouping Transactions: Once a transaction is validated, it is grouped together with other
validated transactions. These transactions are then bundled into a block.
¥ Hashing: A cryptographic hash function is applied to the block. This process creates a
unique identiÞer for the block based on its content, ensuring its integrity.
¥ Linking to Previous Block: Each block contains a reference to the previous block through
the inclusion of the previous block's hash. This creates an unbroken chain of blocks, where
each block is cryptographically linked to the previous one.
¥ Block Structure: The new block contains not only the list of transactions but also essential
data such as the block's hash, the previous blockÕs hash, and other metadata (e.g., timestamp,
nonce, etc.).

4. Ledger Update
¥ Reaching Consensus: After the block is created, it undergoes a consensus process where
validators or miners agree on the validity of the new block. This is done through the
blockchain's consensus algorithm (e.g., Proof of Work or Proof of Stake).
¥ Adding to Blockchain: Once consensus is reached, the new block is added to the
blockchain. This process updates the ledger by appending the new block to the end of the
chain, ensuring that the ledger remains up-to-date.
¥ Network Update: All nodes in the network then update their local copies of the blockchain
to reßect the newly added block. This ensures that all participants have the same version of
the ledger, maintaining consistency across the decentralized network.

5. Public Accessibility
¥ Visibility to All Participants: The transaction becomes part of the public ledger, meaning
that it is now accessible to everyone on the network. Every participant (node) in the
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 25 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

blockchain has a copy of the entire blockchain, and they can view the details of the
transaction (although personal information may be obfuscated via cryptographic methods).
¥ Transparency: Since the blockchain is a public ledger, it provides transparencyÑanyone
can verify transactions that have been added to the blockchain. This transparency is one of
the primary beneÞts of public ledgers, as it promotes trust and accountability.
¥ Immutability: Once a transaction is conÞrmed and added to the blockchain, it becomes
immutable. This means that it cannot be altered, reversed, or tampered with, ensuring that
the integrity of the transaction history is maintained.

Block Structure:

Field Size Description


Block Size 4 bytes The size of the entire block in bytes.
Block Header 80 bytes Contains Þelds related to the block header, as described below.
Transaction Represents the total number of transactions in the block, including
Variable
Counter the coinbase transaction. The size can range from 1 to 9 bytes.
Transactions Variable Contains all the transactions included in the block.

Key Features of Blockchain as Public Ledgers:


1. Decentralization:
◦ Unlike traditional centralized ledgers managed by a single authority, a blockchain as
a public ledger is decentralized. This means that no single entity controls the ledger,
and all participants in the network have a copy of the same ledger. This ensures that
no one can tamper with the data without the network's consensus.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 26 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

2. Transparency:
◦ Blockchain as a public ledger provides transparency to all participants. Each
transaction is recorded on the blockchain, and any participant can verify it. This
public accessibility ensures accountability, as anyone can trace transactions from the
start to the present block.

3. Immutability:
◦ Once a transaction is recorded on a blockchain, it cannot be altered or deleted. This
is due to the cryptographic nature of the ledger. Each block is linked to the previous
block through a cryptographic hash, making it nearly impossible to modify past
transactions without altering the entire blockchain. This feature makes public ledgers
highly secure and tamper-resistant.

4. Security:
◦ Blockchain employs cryptographic techniques like hashing and digital signatures to
secure the transactions. Each transaction is cryptographically signed by the sender,
ensuring authenticity. Additionally, consensus algorithms such as Proof of Work or
Proof of Stake are used to validate transactions and blocks, making it nearly
impossible to manipulate the ledger.

5. Consensus Mechanism:
◦ Public ledgers rely on consensus mechanisms to agree on the validity of transactions.
These mechanisms involve multiple nodes (computers) within the network working
together to validate and conÞrm transactions. Popular consensus mechanisms include
Proof of Work (PoW), Proof of Stake (PoS), and Delegated Proof of Stake
(DPoS).

6. Auditability:
◦ As transactions are publicly recorded, blockchain provides a built-in audit trail that
can be used to verify the authenticity of transactions. This auditability feature is
valuable for compliance and regulatory purposes, as it enables the tracking of every
single transaction back to its origin.

Block in a Blockchain

A block in a blockchain is a digital record containing a list of transactions or other relevant data that
is securely linked to previous blocks in a chronological order, forming a chain. Each block is a
fundamental unit that stores data and serves as a permanent and immutable record within the
blockchain. Blocks ensure the integrity, security, and transparency of blockchain systems by
employing cryptographic hashing and consensus algorithms.

A block in a blockchain is composed of two main components: the Block Header and the Block
Body (which includes the list of transactions). Below is a detailed explanation of the block's
structure.

Field Size Description


The version number of the block, which determines the rules to
Version 4 bytes validate the block. It deÞnes which set of protocol rules the block
adheres to.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 27 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Previous A double SHA-256 hash of the previous block's header. This links
Block's 32 bytes the current block to the previous one, ensuring the chain of blocks
Header Hash is intact and immutable.
A double SHA-256 hash of the Merkle tree, which represents the
Merkle Root
32 bytes hashes of all the transactions in the block. The Merkle tree ensures
Hash
data integrity.
The approximate creation time of the block, represented in Unix
Timestamp 4 bytes epoch time format. This is the time when the miner began hashing
the block header.
The target value that deÞnes the current difÞculty level of mining.
DifÞculty
4 bytes It adjusts dynamically to ensure that blocks are mined at a stable
Target
rate (e.g., every 10 minutes).
An arbitrary number that miners change to generate a valid block
Nonce 4 bytes hash. The nonce is used in the proof-of-work mining process to
match the networkÕs difÞculty target.

The block body consists of the actual transactions included in the block:
Field Size Description
This Þeld contains the total number of transactions in the block,
Transaction
Variable including the coinbase transaction (mining reward). The size can range
Counter
from 1 to 9 bytes.
This section contains all the transactions in the block. A transaction
Transactions Variable
includes the sender, recipient, amount, and other relevant details.
Block Size 4 bytes The size of the entire block, including the header and all transactions.

How Blocks are linked in Blockchain?

Blocks are linked together using hashing and cryptographic signatures. The block header contains
the hash of the previous block, which ensures that each block is connected to the one before it,
forming a continuous chain of blocks.

1. Hashing: Each block contains a unique cryptographic hash that is calculated based on the
contents of the block (including the block's header and transaction data). The hash serves as
a digital Þngerprint of the block, making it practically impossible to change the contents of
the block without altering its hash.
2. Linking Blocks: In the block header, the Previous Block Hash Þeld stores the hash of the
previous block. This creates an immutable chain of blocks, as any change to a previous
block would require re-mining all subsequent blocks, which is computationally infeasible in
a decentralized blockchain.

A block typically contains the following key elements:

1. Block Header:
◦ The block header stores metadata about the block and is crucial for the functioning
of the blockchain. It includes several Þelds that help to validate the block and ensure
it is correctly linked to the previous block in the chain.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 28 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

▪ Version (4 bytes): The version number of the block, indicating which rules
were used to create and validate the block.
▪ Previous Block Hash (32 bytes): A cryptographic hash of the previous
block's header, linking the current block to the previous one, thus forming a
chain. This is a critical element that ensures the immutability of the
blockchain.
▪ Merkle Root Hash (32 bytes): A hash that represents all the transactions
included in the block, derived from a Merkle tree structure. This allows for
quick veriÞcation of whether a speciÞc transaction is part of the block.
▪ Timestamp (4 bytes): The approximate time when the block was created,
often measured in Unix epoch format (seconds since Jan 1, 1970).
▪ DifÞculty Target (4 bytes): The target value that miners must match or
exceed to mine a new block. This determines the difÞculty of the mining
process and ensures that the time between blocks remains consistent.
▪ Nonce (4 bytes): A random number that miners adjust during the mining
process to Þnd a valid hash. The nonce is used in proof-of-work systems to
create a hash that meets the network's difÞculty target.

2. Transaction Counter (Variable Size):


◦ This Þeld indicates the total number of transactions included in the block. The size of
this Þeld can range from 1 to 9 bytes, depending on how many transactions are
included.

3. Transactions (Variable Size):


◦ This section contains all the individual transactions that are included in the block. A
transaction can represent anything from a transfer of cryptocurrency to the execution
of a smart contract. The transactions are stored in a sequence, and each transaction
within the block has a unique identiÞer. A coinbase transaction, which rewards the
miner with new cryptocurrency, is usually the Þrst transaction in the block.

4. Block Size (4 bytes):


◦ The size of the block itself, measured in bytes, indicating the total amount of data in
the block, including the block header and all transactions.

Lifecycle of a Block
1. Transaction Creation:

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 29 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Users or participants initiate transactions (e.g., transferring cryptocurrency, executing


smart contracts).
2. Broadcasting:
◦ The transaction is broadcast to the blockchain network, where it is propagated to all
nodes (computers) in the network.
3. Validation by Miners/Validators:
◦ Miners (in proof-of-work systems) or validators (in proof-of-stake systems) conÞrm
that the transactions are legitimate. This validation includes ensuring that the sender
has sufÞcient funds and that the transaction follows the rules of the network.
4. Block Formation:
◦ After validating transactions, miners or validators group them into a block. This
block is cryptographically secured and linked to the previous block.
5. Consensus Mechanism:
◦ In proof-of-work, miners compete to solve a cryptographic puzzle, while in proof-of-
stake, validators are selected to create new blocks based on their stake. The Þrst
participant to successfully solve the puzzle or reach consensus adds the new block to
the blockchain.
6. Block Addition to Blockchain:

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 30 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Once the block is validated, it is added to the blockchain. The blockÕs hash is then
broadcast to the entire network, and each node updates its local copy of the
blockchain.
7. Finalization:
◦ The block becomes part of the permanent, immutable ledger, and the transactions
within it are considered conÞrmed. The new blockÕs hash is used to reference the
next block in the chain, ensuring that each new block is securely linked to the last.

Types of Blocks

1. Genesis Block
¥ The Genesis Block is the Þrst block in any blockchain. It is the initial block that begins the
blockchain and has no predecessor. It holds a special place because it is the starting point for
the chain.

¥ Characteristics:
◦ No Predecessor: Unlike other blocks, the Genesis Block does not reference a
previous block, since it is the Þrst block.
◦ Hardcoded Values: It typically contains hardcoded values such as speciÞc
initialization parameters, including the Þrst transaction that may have no input but
generates the Þrst set of coins (or tokens).
◦ Initialization: It is essential to initialize the blockchain as it provides the foundation
for all subsequent blocks.

¥ Example:
◦ In Bitcoin, the Genesis Block (Block #0) contains the Þrst transaction (known as the
"coinbase transactionÓ.
◦ Example Code:
genesis_block = {
'index': 0,
'timestamp': '2009-01-03 18:15:05',
'transactions': [],
'previous_hash': '0'*64, # No predecessor
'block_hash': 'hash_of_genesis_block',
'nonce': 0
}
2. Valid Block

¥ A Valid Block is any block that has been successfully created (or mined) and validated
according to the consensus mechanism (such as Proof of Work or Proof of Stake) of the
blockchain network. These blocks are accepted into the blockchain, and they form the
chainÕs backbone.

¥ Characteristics:
◦ Adheres to Consensus Rules: A valid block follows all rules outlined in the
blockchain protocol, such as correct formatting, proper references to previous
blocks, valid transactions, etc.
◦ Consensus ConÞrmation: For a block to be valid, miners (in PoW) or validators (in
PoS) must reach a consensus, ensuring the block is legitimate.
◦ Transaction Integrity: Valid blocks include transactions that are legitimate (e.g., no
double-spending, sufÞcient balance, correct signatures).

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 31 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

¥ Example:
◦ In Bitcoin, once a miner successfully mines a block by solving a cryptographic
puzzle, the block is validated and added to the blockchain.

¥ Example Code:
valid_block = {
'index': 2,
'timestamp': '2025-01-25 14:20:00',
'transactions': [
{'from': 'user1', 'to': 'user2', 'amount': 5, 'transaction_id': 'tx123'}
],
'previous_hash': 'previous_block_hash',
'block_hash': 'valid_hash_of_block',
'nonce': 123456
}

3. Orphaned Block

¥ An Orphaned Block (also known as a Stale Block) occurs when two miners or validators
solve a block at nearly the same time. While both blocks are valid, only one of them will be
accepted into the main blockchain (the longest chain). The other block, which is not part of
the longest chain, becomes an orphaned block.

¥ Characteristics:
◦ Simultaneous Mining: In a decentralized network, there is a possibility of two
blocks being mined at the same time. When this happens, the network has two
versions of the blockchain, but only the longest (most proof of work) chain is
considered valid.
◦ Discarded: The orphaned block does not become part of the main chain. Although it
is valid and contains transactions, it is effectively discarded, and any transactions in
it are moved to the next valid block.
◦ Temporary: Orphaned blocks are usually temporary. After the network conÞrms the
longest chain, the orphaned block is rejected, and the blockchain is uniÞed again.

¥ Example:
◦ In Bitcoin, miners may Þnd two valid blocks at nearly the same time. However, the
one that is appended to the longest chain is considered valid, while the other
becomes orphaned.

¥ Example Code (Simulating the possibility of orphaned blocks):

orphaned_block = {
'index': 3, # Simultaneously mined block
'timestamp': '2025-01-25 14:25:00',
'transactions': [
{'from': 'user3', 'to': 'user4', 'amount': 10, 'transaction_id': 'tx124'}
],
'previous_hash': 'previous_block_hash',
'block_hash': 'orphaned_hash_of_block',
'nonce': 654321
}

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 32 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

# Logic to decide which block becomes orphaned:


if len(main_chain) > len(alternate_chain):
# Orphaned block would be from alternate_chain
main_chain.append(orphaned_block) # This is now part of the main chain

Type of
Description Key Characteristics Example Use Case
Block
Hardcoded values,
Genesis The Þrst block in the blockchain, Initializes Bitcoin
unique, initializes the
Block with no predecessor. blockchain, starting point.
blockchain.
A block that adheres to the Adheres to consensus
Valid Regular transactions,
consensus rules and is added to rules (PoW/PoS),
Block adding blocks to the chain.
the blockchain. validated transactions.
Valid but discarded,
A block that is valid but not part Temporary blockchain
Orphaned happens during
of the main chain due to a chain fork, discarded after
Block simultaneous block
split. longest chain wins.
discovery.

Python implementation of a blockchain consists of blocks, block headers, transactions, Genesis


Block, Valid Block, and basic functions for creating, validating, and computing hashes.

import hashlib
import time

# Block class that deÞnes the structure of a block


class Block:
def __init__(self, index, previous_hash, timestamp, transactions, nonce, hash):
self.index = index # Block number in the chain
self.previous_hash = previous_hash # Hash of the previous block
self.timestamp = timestamp # Timestamp when the block was created
self.transactions = transactions # List of transactions
self.nonce = nonce # Nonce used for mining (Proof of Work)
self.hash = hash # Block's hash
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 33 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

def __str__(self):
return f"Block {self.index} | Hash: {self.hash} | Prev Hash: {self.previous_hash}"

# Function to calculate SHA-256 hash of a block's data


def calculate_hash(index, previous_hash, timestamp, transactions, nonce):
block_data = f"{index}{previous_hash}{timestamp}{transactions}{nonce}"
return hashlib.sha256(block_data.encode('utf-8')).hexdigest()

# Genesis Block Creation


def create_genesis_block():
# The Þrst block, manually created with no predecessor
return Block(0, "0" * 64, int(time.time()), [], 0, calculate_hash(0, "0" * 64, int(time.time()), [], 0))

# Create a new block after the genesis block


def create_new_block(previous_block, transactions):
index = previous_block.index + 1 # Next block index
timestamp = int(time.time()) # Current timestamp
nonce = 0 # Start with nonce = 0 (Proof of Work)
hash = calculate_hash(index, previous_block.hash, timestamp, transactions, nonce) # Initial hash

# Create the new block


return Block(index, previous_block.hash, timestamp, transactions, nonce, hash)

# Example of adding a block with transactions


def add_transaction_to_block():
return [
{"sender": "Alice", "receiver": "Bob", "amount": 10},
{"sender": "Bob", "receiver": "Charlie", "amount": 5}
]

# Create blockchain and add blocks


def create_blockchain():
blockchain = [create_genesis_block()] # Initialize with the Genesis Block
# Let's create some more blocks
for _ in range(3):
new_transactions = add_transaction_to_block() # Example transactions
new_block = create_new_block(blockchain[-1], new_transactions) # Create a new block
blockchain.append(new_block) # Add the block to the blockchain
return blockchain

# Function to display the blockchain


def display_blockchain(blockchain):
for block in blockchain:
print(block)

# Main function to run the blockchain code


if __name__ == "__main__":
blockchain = create_blockchain() # Create blockchain
display_blockchain(blockchain) # Display the blockchain

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 34 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Blockchain Transactions

In a blockchain, transactions are the fundamental operations that represent the transfer of
data or assets (like cryptocurrency) between participants. Each transaction is recorded and stored in
blocks, and these blocks form the blockchain. Mining plays an essential role in this process,
ensuring that new blocks are added to the blockchain through a cryptographic proof-of-work puzzle.
Together, these elements form the backbone of blockchain networks like Bitcoin and Ethereum.

A blockchain transaction is a digital action or event where assets are transferred from one party to
another, or some data is written onto the blockchain. Transactions can represent various activities,
such as:

¥ Sending cryptocurrency (e.g., Bitcoin, Ethereum) from one address to another.


¥ Executing smart contracts on platforms like Ethereum.
¥ Recording data like supply chain information, voting records, or any data needing
immutability.
Blockchain transactions are cryptographically secured, transparent, and permanent, ensuring the
integrity of the blockchain.

Key Components of a Blockchain Transaction

A typical blockchain transaction contains the following Þelds:

1. Sender and Receiver (Address):


◦ Sender: The party initiating the transaction, who signs it using their private key to
prove ownership.
◦ Receiver: The party receiving the asset or data, identiÞed by their public key or
address.
2. Amount (or Data):
◦ In cryptocurrency transactions, this is the amount of cryptocurrency (Bitcoin, Ether)
transferred.
◦ In smart contract platforms like Ethereum, this could also involve executing data,
such as calling a smart contract.
3. Transaction Fee (Gas Limit and Gas Price):

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 35 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Gas Limit: The maximum amount of computational work a transaction can


consume. It ensures that transactions or smart contracts don't overwhelm the
network.
◦ Gas Price: Set by the sender, itÕs the price per unit of gas (measured in Gwei for
Ethereum) that determines how much theyÕre willing to pay for the transaction to be
processed.

4. Transaction ID: A unique identiÞer (hash) used to track and verify the transaction.
5. Nonce: A number assigned to each transaction to prevent replay attacks and ensure the
correct order of transactions.
6. Signature: A cryptographic signature generated using the senderÕs private key that ensures
the integrity and authenticity of the transaction.

Protocol Messages in Blockchain


The following protocol messages help blockchain nodes communicate and exchange information
regarding transactions and blocks. They are essential for synchronization, transaction propagation,
and block validation.

1. version:
◦ The initial message sent by a node to the network to advertise its version and block
count. The remote node replies with similar information, establishing the connection.
2. verack:
◦ The response to the version message, conÞrming the connection.
3. inv:
◦ Nodes use this message to advertise their knowledge of blocks and transactions. It
contains hashes of the blocks or transactions.
4. getdata:
◦ Sent in response to an inv message, requesting a speciÞc block or transaction by its
hash.
5. getblocks:
◦ This message returns a list of blocks (up to 500) starting after a known block hash. It
helps nodes synchronize by requesting the latest blocks.
6. getheaders:
◦ Requests the block headers within a speciÞed range, useful for obtaining block
metadata without downloading full blocks.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 36 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

7. tx:
◦ Sends a transaction in response to a getdata request. It contains a serialized
transaction.
8. block:
◦ Sends a full block in response to a getdata request, including all transactions within
the block.
9. headers:
◦ Returns up to 2,000 block headers in response to a getheaders request.

10. getaddr:
◦ A request to get information about known peers (their IP addresses and port
numbers).
11. addr:
◦ Provides information about nodes on the network, including a list of known peer
addresses.

Transaction Lifecycle with Gas and Protocol Messages

Mining in a blockchain network like Bitcoin is a key mechanism that ensures the integrity
and security of the blockchain. It involves solving a cryptographic puzzle (proof-of-work) to add
new blocks, containing valid transactions, to the blockchain. HereÕs how mining and blockchain
transactions work together:

1. Transaction Creation:
◦ A user creates a transaction with the sender's and receiverÕs addresses, the amount or
contract data, and gas parameters.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 37 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

2. Broadcasting to the Network (via inv):


◦ The transaction is broadcast to the network using the inv protocol message,
advertising the transaction to all connected peers.
3. Transaction Validation:
◦ Miners or validators check the transaction's validity, ensuring it adheres to the
networkÕs consensus rules (e.g., correct signature, sufÞcient balance, etc.). They also
verify the gas price is sufÞcient to prioritize the transaction. If valid, the transaction
is included in a block.
4. Block Creation (via block):
◦ Miners group the valid transactions into a new block. They try to Þnd a valid nonce
by repeatedly hashing the blockÕs header, which includes the transactions, the
previous blockÕs hash, and a timestamp, until they Þnd a hash smaller than the target
difÞculty.
5. Proof-of-Work (Mining Puzzle):
◦ The miner must solve a cryptographic puzzle (proof-of-work) by Þnding a nonce
that results in a hash smaller than the networkÕs target difÞculty. The process of
mining ensures that transactions are securely validated and added to the blockchain.
6. Block Validation (via block message):
◦ Once the miner Þnds a valid nonce, the block is broadcast to the network via the
block protocol message. Nodes in the network validate the block and its
transactions.
7. Transaction ConÞrmation:
◦ Once the block is added to the blockchain, the transactions within it are conÞrmed.
The transaction is considered permanent after a sufÞcient number of conÞrmations
(depending on the blockchainÕs rules).

Mining Reward and Transaction Fees


Miners are incentivized for validating transactions and adding blocks to the blockchain. This
incentive comes in two forms:
1. Block Reward:
◦ Miners receive a Þxed amount of cryptocurrency for successfully mining a block. In
Bitcoin, this reward started at 50 BTC and halves every 210,000 blocks.
2. Transaction Fees:
◦ In addition to the block reward, miners also receive transaction fees from the
transactions included in the block. The fee is determined by the sender's gas price (in
the case of Ethereum or similar platforms).
The total mining reward is the sum of the block reward and transaction fees:

Total Reward = Block Reward + Transaction Fees

The mining process involves solving a cryptographic puzzle through the following steps:

1. Hash Calculation:
Block Hash = SHA-256(SHA-256(Block Header))
Where the Block Header contains the version, previous block hash, Merkle root, timestamp,
difÞculty target, and nonce.

2. Proof-of-Work Condition (DifÞculty Target):


Hash < Target
The target is adjusted to maintain a consistent block time across the network.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 38 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Mining DifÞculty:
DifÞculty = (Target / Current Target)
DifÞculty is recalculated every 2016 blocks in Bitcoin to ensure block times remain
consistent.

4. Nonce:
Miners adjust the nonce value until they Þnd a hash smaller than the difÞculty target.

Transaction Lifecycle with Gas and Protocol Messages


The lifecycle of a blockchain transaction, including the use of gas and protocol messages, proceeds
as follows:
1. Transaction Creation:
◦ A user creates a transaction with the sender's and receiverÕs addresses, the amount or
contract data, and gas parameters.
2. Broadcasting to Network (via inv):
◦ The transaction is broadcast to the network using the inv protocol message,
advertising the transaction to all connected peers.
3. Transaction Validation:
◦ Miners or validators check the transaction's validity, ensuring it adheres to the
networkÕs consensus rules (e.g., correct signature, sufÞcient balance, etc.). They also
verify if the gas price is sufÞcient to prioritize the transaction.
◦ If valid, the transaction is included in a block.
4. Block Creation (via block):
◦ Once validated, the transaction is included in a new block, which is then broadcasted
to the network via the block protocol message.
5. ConÞrmation:
◦ The transaction is conÞrmed when the block is added to the blockchain. This can
take multiple conÞrmations, depending on the blockchain.

Sample program on Blockchain transactions,

import hashlib
import time
import json
from uuid import uuid4

# Simulating a simple blockchain transaction


class BlockchainTransaction:
def __init__(self, sender, receiver, amount, fee, nonce=None):
self.transaction_id = str(uuid4()) # Unique transaction ID
self.sender = sender
self.receiver = receiver
self.amount = amount
self.fee = fee
self.nonce = nonce if nonce else str(uuid4()) # To prevent replay attacks
self.timestamp = time.time()

# Generate transaction hash for security and integrity


def generate_hash(self):
transaction_data = {
'sender': self.sender,
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 39 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

'receiver': self.receiver,
'amount': self.amount,
'fee': self.fee,
'nonce': self.nonce,
'timestamp': self.timestamp
}
transaction_json = json.dumps(transaction_data, sort_keys=True)
return hashlib.sha256(transaction_json.encode('utf-8')).hexdigest()

def __str__(self):
return f"Transaction({self.transaction_id}): {self.sender} -> {self.receiver}, Amount:
{self.amount}, Fee: {self.fee}"

# Blockchain Node class to simulate the process


class BlockchainNode:
def __init__(self, node_id):
self.node_id = node_id
self.transaction_pool = []

# Add a transaction to the pool


def add_transaction(self, transaction):
self.transaction_pool.append(transaction)

# Validate transaction (simple validation: amount and fee must be positive)


def validate_transaction(self, transaction):
if transaction.amount <= 0 or transaction.fee <= 0:
print(f"Invalid transaction {transaction.transaction_id}: Amount or Fee is zero/negative")
return False
print(f"Transaction {transaction.transaction_id} validated!")
return True

# Broadcast the transaction (in a real network, this would propagate to other nodes)
def broadcast_transaction(self, transaction):
if self.validate_transaction(transaction):
print(f"Transaction {transaction.transaction_id} broadcasted to the network.")
return True
return False

# Blockchain class to simulate the process of adding blocks


class Blockchain:
def __init__(self):
self.chain = []
self.pending_transactions = []
self.create_genesis_block()

# Genesis block (Þrst block in the chain)


def create_genesis_block(self):
genesis_block = {
'index': 0,
'timestamp': time.time(),
'transactions': [],
'previous_hash': '0' # No previous hash for genesis block
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 40 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

}
self.chain.append(genesis_block)

# Add a new block to the blockchain after validating the transactions


def add_block(self, block):
block['index'] = len(self.chain)
block['timestamp'] = time.time()
block['previous_hash'] = self.chain[-1]['hash'] if len(self.chain) > 0 else '0'
block['hash'] = self.calculate_hash(block)
self.chain.append(block)

# Calculate block hash (for integrity)


def calculate_hash(self, block):
block_data = json.dumps(block, sort_keys=True).encode('utf-8')
return hashlib.sha256(block_data).hexdigest()

# Create a new block with pending transactions


def create_new_block(self):
block = {
'transactions': self.pending_transactions
}
self.add_block(block)
self.pending_transactions = [] # Clear pending transactions after block is added

# Simulate mining by creating a block


def mine_block(self):
if len(self.pending_transactions) > 0:
print(f"Mining block with {len(self.pending_transactions)} transactions...")
self.create_new_block()
else:
print("No transactions to mine.")

# Simulation of blockchain transactions and mining


if __name__ == "__main__":
# Create a new blockchain
blockchain = Blockchain()

# Create blockchain nodes


node1 = BlockchainNode(node_id="Node-1")
node2 = BlockchainNode(node_id="Node-2")

# Create transactions
transaction1 = BlockchainTransaction(sender="Alice", receiver="Bob", amount=50, fee=0.1)
transaction2 = BlockchainTransaction(sender="Bob", receiver="Charlie", amount=30, fee=0.05)
transaction3 = BlockchainTransaction(sender="Alice", receiver="Charlie", amount=20, fee=0.1)

# Add transactions to the node's pool


node1.add_transaction(transaction1)
node1.add_transaction(transaction2)
node2.add_transaction(transaction3)

# Broadcast transactions
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 41 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

node1.broadcast_transaction(transaction1)
node1.broadcast_transaction(transaction2)
node2.broadcast_transaction(transaction3)

# Add transactions to blockchain's pending pool


blockchain.pending_transactions.extend([transaction1, transaction2, transaction3])

# Mine a block
blockchain.mine_block()

# Print blockchain content (blocks and transactions)


for block in blockchain.chain:
print(f"Block {block['index']} - Transactions: {len(block['transactions'])}")
for tx in block['transactions']:
print(f" Transaction ID: {tx.transaction_id}, Sender: {tx.sender}, Receiver: {tx.receiver},
Amount: {tx.amount}, Fee: {tx.fee}")

# Final output of the blockchain


print("\nBlockchain:")
for block in blockchain.chain:
print(f"Block #{block['index']} | Hash: {block['hash']}")

Output:
Transaction 4794e0fc-f8b4-45cc-b0d2-0d317157ced5 validated!
Transaction 4794e0fc-f8b4-45cc-b0d2-0d317157ced5 broadcasted to the network.
Transaction 8309b8e6-e4cd-4d26-b76b-c5b68ed7b94c validated!
Transaction 8309b8e6-e4cd-4d26-b76b-c5b68ed7b94c broadcasted to the network.
Transaction 3b5be460-b9b0-4626-92b4-42991c3d31b9 validated!
Transaction 3b5be460-b9b0-4626-92b4-42991c3d31b9 broadcasted to the network.
Mining block with 3 transactions...
Block 1 - Transactions: 3
Transaction ID: 4794e0fc-f8b4-45cc-b0d2-0d317157ced5, Sender: Alice, Receiver: Bob, Amount:
50, Fee: 0.1
Transaction ID: 8309b8e6-e4cd-4d26-b76b-c5b68ed7b94c, Sender: Bob, Receiver: Charlie,
Amount: 30, Fee: 0.05
Transaction ID: 3b5be460-b9b0-4626-92b4-42991c3d31b9, Sender: Alice, Receiver: Charlie,
Amount: 20, Fee: 0.1

Blockchain:
Block #0 | Hash: 5d8f7a0139c64f0e27b88e4734c8cfc3a2424d89a8fd0abbd4da10719b4d39b1
Block #1 | Hash: 1fa7a04de15b2d56c7f99a37841a678d5cb38c7ca0438e285de0c25fdfb57318

The Chain and the Longest Chain

In a blockchain, the chain refers to a sequence of blocks that are linked together, where each block
contains a list of transactions and a hash of the previous block, ensuring the integrity and
immutability of the blockchain. The longest chain refers to the chain with the greatest number of
blocks or the chain that has the highest accumulated proof of work (or consensus mechanism,
depending on the blockchain).

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 42 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

In the context of a decentralized network, nodes generally follow the longest chain rule. This
means that, in case of a fork (when two competing chains emerge), nodes will consider the longest
valid chain as the "true" version of the blockchain. This ensures that the blockchain with the highest
computational effort or the most valid blocks is considered the canonical chain.

Chain: A collection of blocks, where each block is linked to the previous one using its hash.
Longest Chain: The chain that is the longest in terms of block count, or the chain with the most
accumulated proof of work.

In a blockchain network, a fork occurs when two or more blocks are found at the same time. This is
common in Proof-of-Work (PoW) blockchains, where multiple miners can discover blocks
simultaneously. At this point, the network temporarily has two competing chains. Eventually, one
chain becomes the "longest" and is considered valid, while the other fork is discarded.

Let's break down the key steps involved in blockchain forks and how they are visualized:

1. Before the Fork (Same Perspective):


All nodes in the network have the same
view of the blockchain.
Every node knows the same chain history,
and the blockchain is synchronized across
the network.

2. Blockchain Fork Event (Two Blocks Found


Simultaneously):
¥ Two miners (or validators in some
systems) Þnd valid blocks at nearly the
same time.
¥ These blocks get broadcast to different
parts of the network, causing a temporary
fork.
¥ At this moment, the network has two
competing chains, and different nodes may have different views (one chain or the other).

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 43 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Visualization of a Blockchain Fork Event:


¥ Nodes in the network receive and propagate two different blocks (i.e., two competing blocks
extend the same parent block).
¥ Both blocks are propagated to their neighboring nodes, causing a split in the networkÕs view
of the blockchain.

4. A New Block Extends One Fork:


¥ As miners continue to mine, one of the
two forks will eventually get extended
by a new block.
¥ The fork that is extended will become
the "longest" chain (because it now has
more blocks compared to the other
fork).
¥ The network nodes will start
recognizing this fork as the valid one.

5. Reconverging the Network:


¥ The nodes in the network update their
chain to follow the longest chain.
¥ The nodes that were previously on the
discarded fork will adopt the longest
chain, and the network is "reconverged"
on the new valid chain.

6. Network Reconverges on the New Longest


Chain:
¥ Once the longest chain is determined, the other fork is discarded. The network has a
consensus on the valid blockchain.
¥ This is how forks are resolved in most blockchain systems, ensuring that the network
eventually converges on a single valid chain.

Below is a simple Python simulation illustrating the fork event, where two competing blocks are
added to the blockchain before the network converges on the longest chain.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 44 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

import hashlib
import time
import json
from uuid import uuid4

# Simulating a simple blockchain transaction


class BlockchainTransaction:
def __init__(self, sender, receiver, amount, fee,
nonce=None):
self.transaction_id = str(uuid4()) # Unique
transaction ID
self.sender = sender
self.receiver = receiver
self.amount = amount
self.fee = fee
self.nonce = nonce if nonce else str(uuid4())
# To prevent replay attacks
self.timestamp = time.time()

# Generate transaction hash for security and


integrity
def generate_hash(self):
transaction_data = {
'sender': self.sender,
'receiver': self.receiver,
'amount': self.amount,
'fee': self.fee,
'nonce': self.nonce,
'timestamp': self.timestamp
}
transaction_json = json.dumps(transaction_data, sort_keys=True)
return hashlib.sha256(transaction_json.encode('utf-8')).hexdigest()

def __str__(self):
return f"Transaction({self.transaction_id}): {self.sender} -> {self.receiver}, Amount:
{self.amount}, Fee: {self.fee}"

# Blockchain Node class to simulate the process


class BlockchainNode:
def __init__(self, node_id):
self.node_id = node_id
self.transaction_pool = []

# Add a transaction to the pool


def add_transaction(self, transaction):
self.transaction_pool.append(transaction)

# Validate transaction (simple validation: amount and fee must be positive)


def validate_transaction(self, transaction):
if transaction.amount <= 0 or transaction.fee <= 0:
print(f"Invalid transaction {transaction.transaction_id}: Amount or Fee is zero/negative")
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 45 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

return False
print(f"Transaction {transaction.transaction_id} validated!")
return True

# Broadcast the transaction (in a real network, this would propagate to other nodes)
def broadcast_transaction(self, transaction):
if self.validate_transaction(transaction):
print(f"Transaction {transaction.transaction_id} broadcasted to the network.")
return True
return False

# Blockchain class to simulate the process of adding blocks


class Blockchain:
def __init__(self):
self.chain = []
self.pending_transactions = []
self.create_genesis_block()

# Genesis block (Þrst block in the chain)


def create_genesis_block(self):
genesis_block = {
'index': 0,
'timestamp': time.time(),
'transactions': [],
'previous_hash': '0' # No previous hash for genesis block
}
self.chain.append(genesis_block)

# Add a new block to the blockchain after validating the transactions


def add_block(self, block):
block['index'] = len(self.chain)
block['timestamp'] = time.time()
block['previous_hash'] = self.chain[-1]['hash'] if len(self.chain) > 0 else '0'
block['hash'] = self.calculate_hash(block)
self.chain.append(block)

# Calculate block hash (for integrity)


def calculate_hash(self, block):
block_data = json.dumps(block, sort_keys=True).encode('utf-8')
return hashlib.sha256(block_data).hexdigest()

# Create a new block with pending transactions


def create_new_block(self):
block = {
'transactions': self.pending_transactions
}
self.add_block(block)
self.pending_transactions = [] # Clear pending transactions after block is added

# Simulate mining by creating a block


def mine_block(self):
if len(self.pending_transactions) > 0:
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 46 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

print(f"Mining block with {len(self.pending_transactions)} transactions...")


self.create_new_block()
else:
print("No transactions to mine.")

# Simulate a fork event by adding blocks to different forks


def fork_event(self):
print("\n[FORKEVENT]: A fork happens, two competing blocks are found!")
# Add two competing blocks (forks) to the blockchain
block1 = {
'transactions': self.pending_transactions[:len(self.pending_transactions)//2] # First fork
}
block2 = {
'transactions': self.pending_transactions[len(self.pending_transactions)//2:] # Second fork
}

print("[FORKEVENT]: Block 1 and Block 2 broadcasted to the network.")


self.add_block(block1)
self.add_block(block2)

# Reconvergence after the fork event


def reconverge(self):
print("\n[RECONVERGE]: The network has chosen the longest chain.")
# Simulate the longest chain selection and discard one fork
self.chain = self.chain[:len(self.chain)-1] # Keep only the Þrst fork (for simplicity)
print("[RECONVERGE]: Network has converged.")

# Simulation of blockchain transactions and mining


if __name__ == "__main__":
# Create a new blockchain
blockchain = Blockchain()

# Create blockchain nodes


node1 = BlockchainNode(node_id="Node-1")
node2 = BlockchainNode(node_id="Node-2")

# Create transactions
transaction1 = BlockchainTransaction(sender="Alice", receiver="Bob", amount=50, fee=0.1)
transaction2 = BlockchainTransaction(sender="Bob", receiver="Charlie", amount=30, fee=0.05)
transaction3 = BlockchainTransaction(sender="Alice", receiver="Charlie", amount=20, fee=0.1)

# Add transactions to the node's pool


node1.add_transaction(transaction1)
node1.add_transaction(transaction2)
node2.add_transaction(transaction3)

# Broadcast transactions
node1.broadcast_transaction(transaction1)
node1.broadcast_transaction(transaction2)
node2.broadcast_transaction(transaction3)

# Add transactions to blockchain's pending pool


Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 47 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

blockchain.pending_transactions.extend([transaction1, transaction2, transaction3])

# Simulate fork event


blockchain.fork_event()

# Network reconvergence
blockchain.reconverge()

# Final output of the blockchain


print("\nBlockchain:")
for block in blockchain.chain:
print(f"Block #{block['index']} | Hash: {block['hash']}")

Output:

Transaction 4794e0fc-f8b4-45cc-b0d2-0d317157ced5 validated!


Transaction 4794e0fc-f8b4-45cc-b0d2-0d317157ced5 broadcasted to the network.
Transaction 8309b8e6-e4cd-4d26-b76b-c5b68ed7b94c validated!
Transaction 8309b8e6-e4cd-4d26-b76b-c5b68ed7b94c broadcasted to the network.
Transaction 3b5be460-b9b0-4626-92b4-42991c3d31b9 validated!
Transaction 3b5be460-b9b0-4626-92b4-42991c3d31b9 broadcasted to the network.

[FORKEVENT]: A fork happens, two competing blocks are found!


[FORKEVENT]: Block 1 and Block 2 broadcasted to the network.

[RECONVERGE]: The network has chosen the longest chain.


[RECONVERGE]: Network has converged.

Blockchain:
Block #0 | Hash: 5d8f7a0139c64f0e27b88e4734c8cfc3a2424d89a8fd0abbd4da10719b4d39b1
Block #1 | Hash: 1fa7a04de15b2d56c7f99a37841a678d5cb38c7ca0438e285de0c25fdfb57318

The Longest Chain Rule:


1. Block Propagation: Miners (or validators, depending on the consensus algorithm) create
blocks and propagate them to the network. Once a block is mined, it is added to the
blockchain.
2. Forks: In a distributed network, it's possible that two miners might mine a block at the same
time, causing a temporary fork where two chains exist.
3. Resolution of Forks: The network resolves forks by considering the longest chain as the
valid chain. In a PoW (Proof of Work) system, the longest chain has the most proof of work,
and in PoS (Proof of Stake), it may be the chain with the most accumulated stake or other
validation criteria.
4. Finality: Once a block is added to the longest chain and gets sufÞcient conÞrmations, it is
considered "Þnalized," meaning it cannot easily be reversed.

import hashlib
import time
import json
from uuid import uuid4

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 48 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

class BlockchainTransaction:
def __init__(self, sender, receiver, amount, fee, nonce=None):
self.transaction_id = str(uuid4()) # Unique transaction ID
self.sender = sender
self.receiver = receiver
self.amount = amount
self.fee = fee
self.nonce = nonce if nonce else str(uuid4()) # To prevent replay attacks
self.timestamp = time.time()

def generate_hash(self):
transaction_data = {
'sender': self.sender,
'receiver': self.receiver,
'amount': self.amount,
'fee': self.fee,
'nonce': self.nonce,
'timestamp': self.timestamp
}
transaction_json = json.dumps(transaction_data, sort_keys=True)
return hashlib.sha256(transaction_json.encode('utf-8')).hexdigest()

def __str__(self):
return f"Transaction({self.transaction_id}): {self.sender} -> {self.receiver}, Amount:
{self.amount}, Fee: {self.fee}"

class BlockchainNode:
def __init__(self, node_id):
self.node_id = node_id
self.transaction_pool = []

def add_transaction(self, transaction):


self.transaction_pool.append(transaction)

def validate_transaction(self, transaction):


if transaction.amount <= 0 or transaction.fee <= 0:
print(f"Invalid transaction {transaction.transaction_id}: Amount or Fee is zero/negative")
return False
print(f"Transaction {transaction.transaction_id} validated!")
return True

def broadcast_transaction(self, transaction):


if self.validate_transaction(transaction):
print(f"Transaction {transaction.transaction_id} broadcasted to the network.")
return True
return False

class Blockchain:
def __init__(self):
self.chains = [] # List of all blockchain forks
self.create_genesis_block()

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 49 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

def create_genesis_block(self):
genesis_block = {
'index': 0,
'timestamp': time.time(),
'transactions': [],
'previous_hash': '0'
}
genesis_block['hash'] = self.calculate_hash(genesis_block)
self.chains.append([genesis_block]) # Initialize with a single chain

def calculate_hash(self, block):


block_data = json.dumps(block, sort_keys=True).encode('utf-8')
return hashlib.sha256(block_data).hexdigest()

def add_block(self, block, chain_idx):


block['index'] = len(self.chains[chain_idx])
block['timestamp'] = time.time()
block['previous_hash'] = self.chains[chain_idx][-1]['hash']
block['hash'] = self.calculate_hash(block)
self.chains[chain_idx].append(block)

def create_new_block(self, chain_idx, transactions):


block = {
'transactions': transactions
}
self.add_block(block, chain_idx)

def mine_block(self, chain_idx, transactions):


if len(transactions) > 0:
print(f"Mining block for chain {chain_idx} with {len(transactions)} transactions...")
self.create_new_block(chain_idx, transactions)
else:
print("No transactions to mine.")

def get_longest_chain(self):
longest_chain = max(self.chains, key=len)
return longest_chain

def print_chain(self, chain_idx):


print(f"Chain {chain_idx}:")
for block in self.chains[chain_idx]:
print(f"Block {block['index']} | Hash: {block['hash']}")

if __name__ == "__main__":
blockchain = Blockchain()

node1 = BlockchainNode(node_id="Node-1")
node2 = BlockchainNode(node_id="Node-2")

transaction1 = BlockchainTransaction(sender="Alice", receiver="Bob", amount=50, fee=0.1)


transaction2 = BlockchainTransaction(sender="Bob", receiver="Charlie", amount=30, fee=0.05)
transaction3 = BlockchainTransaction(sender="Alice", receiver="Charlie", amount=20, fee=0.1)
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 50 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

node1.add_transaction(transaction1)
node1.add_transaction(transaction2)
node2.add_transaction(transaction3)

node1.broadcast_transaction(transaction1)
node1.broadcast_transaction(transaction2)
node2.broadcast_transaction(transaction3)

blockchain.mine_block(chain_idx=0, transactions=[transaction1, transaction2, transaction3])

blockchain.print_chain(chain_idx=0)

# Display the longest chain


longest_chain = blockchain.get_longest_chain()
print("\nLongest Chain:")
for block in longest_chain:
print(f"Block {block['index']} | Hash: {block['hash']}")

Permissioned Model of Blockchain

The Permissioned Model of Blockchain and Permissioned Ledger are closely related
concepts. A Permissioned Ledger is a type of blockchain where network participants are pre-
identiÞed and trusted. Instead of using a traditional distributed consensus mechanism, it relies on an
agreement protocol to maintain a shared and consistent state of the records. VeriÞcation of
transactions is performed by preselected veriÞers, designated by a central authority, eliminating the
need for mining or energy-intensive consensus processes. Permissioned blockchains restrict write
access to a select group of preapproved nodes or users who have undergone a trust-based
onboarding process. Only these designated nodes are authorized to verify transactions and
participate in the distributed consensus process.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 51 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Key Features of Permissioned Blockchains

1. Access Control
¥ Restricted Participation: Only preapproved participants, veriÞed through an onboarding
process, can join the network.
¥ Role-Based Permissions: Participants are assigned roles, such as validators, administrators,
or users, based on their level of authorization.
¥ Identity Management: Each participant's identity is known and veriÞed, reducing
anonymity while ensuring accountability.

2. Centralized Governance
¥ Controlled by a Central Authority or Consortium: A governing body, such as a
consortium of organizations, establishes the network rules and maintains oversight.
¥ Policy Enforcement: The authority decides who gets access, how consensus is achieved,
and how disputes are resolved.
3. Privacy and ConÞdentiality
¥ Limited Data Sharing: Sensitive information can be kept off-chain or shared selectively
among authorized nodes.
¥ Encrypted Transactions: Data and transactions can be encrypted to provide additional
layers of privacy.

4. Customizability
¥ Tailored Consensus Mechanisms: Permissioned blockchains often use lightweight
consensus mechanisms, such as Practical Byzantine Fault Tolerance (PBFT) or Raft, that do
not require energy-intensive processes like Proof of Work (PoW).
¥ Adaptable Features: Organizations can adjust the blockchain protocols to meet industry-
speciÞc needs, such as throughput, latency, or regulatory compliance.

5. EfÞciency
¥ High Throughput: By limiting the number of participants and optimizing consensus
mechanisms, permissioned blockchains achieve faster transaction speeds.
¥ Scalability: Smaller, controlled networks can handle larger transaction volumes compared
to public blockchains.

Working and Implementation:

1. Network Setup
¥ Infrastructure Establishment:
A permissioned blockchain begins with the setup of infrastructure by a central authority,
consortium, or a governing organization. This entity decides the rules, protocols, and
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 52 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

structure of the blockchain network. The infrastructure includes hardware, software, and
network components required for nodes to interact with the blockchain.
¥ DeÞning Rules for Participation:
The governing body establishes strict rules for who can join the network, their roles (e.g.,
user, validator, auditor), and the responsibilities of each participant. This includes guidelines
for transaction validation, data sharing, and dispute resolution.

2. Onboarding Participants
¥ Participant Vetting:
Potential participants are carefully vetted through processes such as identity veriÞcation,
compliance checks, and proof of eligibility. This ensures that all members of the blockchain
are trustworthy entities.
¥ Assigning Permissions:
Participants are granted speciÞc permissions based on their roles:
◦ Users: Can initiate transactions but have limited access to sensitive network
operations.
◦ Validators/Miners: Responsible for verifying and adding transactions to the
blockchain.
◦ Auditors/Observers: Can view the blockchain for compliance or oversight but
cannot write to it.
¥ Digital Identity Creation:
Each participant is assigned a unique digital identity (e.g., cryptographic key pair) to interact
securely with the blockchain. The private key is used to sign transactions, ensuring
authenticity and integrity.

3. Transaction Flow
¥ Proposing Transactions:
Authorized participants initiate transactions (e.g., transferring assets, executing contracts).
These transactions include the sender, receiver, transaction details, and a digital signature for
validation.
¥ VeriÞcation:
Transactions are sent to nodes with write permissions for veriÞcation. Validators check:
◦ Authenticity of the sender using their digital signature.
◦ Adequate balance or resource availability.
◦ Compliance with network rules and policies.
¥ Consensus:
Instead of traditional Proof of Work (PoW) or Proof of Stake (PoS), permissioned
blockchains use efÞcient consensus mechanisms suited for trusted environments:
◦ Practical Byzantine Fault Tolerance (PBFT): Ensures fault tolerance and
agreement among known participants.
◦ Raft: A lightweight leader-based consensus mechanism offering high throughput.
◦ Proof of Authority (PoA): Trusted validators with known identities approve
transactions.
¥ Adding Transactions to Blocks:
Once consensus is achieved, the veriÞed transactions are added to a new block. The block is
cryptographically linked to the previous block, ensuring the immutability of the blockchain.

4. Data Sharing
¥ Selective Sharing:
Permissioned blockchains implement granular access controls to ensure data is shared only
with authorized participants.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 53 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ For instance, sensitive Þnancial data might only be accessible to regulators or


auditors.
◦ Smart contracts can enforce data-sharing policies programmatically.
¥ Privacy Protection:
◦ Off-Chain Storage: Sensitive information can be stored off-chain, with only
cryptographic proofs or references stored on the blockchain.
◦ Zero-Knowledge Proofs (ZKP): These proofs enable participants to verify data
without revealing the actual information.

5. Blockchain Maintenance
¥ Protocol Updates:
Governing bodies or consortia manage updates to the blockchain's protocols, ensuring the
system evolves with technological and regulatory changes.
¥ Dispute Resolution:
Disputes (e.g., invalid transactions or network misbehavior) are resolved through predeÞned
processes, such as arbitration or voting among governing members.
¥ Participant Management:
Permissions for participants can be revoked or updated based on their actions or network
requirements.

Consensus mechanisms

Because of the structure of permissioned blockchains, they donÕt use the same types of
consensus protocols as permissionless ones. Most commonly, organizations that deploy
permissioned blockchains use one (or more) of the following three protocols: Practical Byzantine
Fault Tolerance (PBFT), federated, or round-robin consensus.
1. PBFT Ð PBFT is an improved version of the original BFT protocol where all voting nodes much
reach a consensus, but one or more parties are considered unreliable. In this model, a networkÕs

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 54 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

safety and stability are guaranteed so long as the required minimum percentage of nodes are
behaving honestly and properly.

2. Federated (or Federated Byzantine Consensus) - In a federated consensus, thereÕs a set of


transaction validators trusted by each node in the blockchain that receives and sorts the transactions.
Once a minimum number of these validators agree, a consensus is reached.

3. Round-robin - In a round-robin consensus, nodes are selected pseudo-randomly to create blocks.


Once chosen, a node must pass through a cooling-off period before it can reenter the pool and be
available again for consensus participation.

Advantages of Permissioned Blockchains


1. Enhanced Security:
◦ Authorized participants reduce the risk of malicious activities.
◦ Transactions are veriÞed by trusted entities, improving overall security.
2. Improved Privacy:
◦ Transactions are visible only to authorized nodes, ensuring conÞdentiality.
◦ Sensitive business data remains protected.
3. Regulatory Compliance:
◦ Easier to comply with legal and regulatory requirements due to controlled access and
auditable data.

4. Reduced Energy Consumption:


◦ Consensus mechanisms are energy-efÞcient, avoiding high computational costs
associated with PoW.
5. Customizability:
◦ Protocols and features can be tailored to speciÞc industries, such as healthcare,
Þnance, or supply chain.
6. Faster Transactions:
◦ Limited participants and efÞcient consensus mechanisms ensure quicker validation.

Disadvantages of Permissioned Blockchains


1. Centralization Risks:
◦ Centralized governance may reintroduce trust issues, undermining blockchainÕs
decentralization ethos.
◦ A single point of failure could disrupt the network.
2. Limited Transparency:
◦ Restricted access may hinder public oversight, reducing trust in certain applications.
3. Cost of Maintenance:
◦ Managing access control and onboarding new participants increases operational
complexity.
4. Potential for Collusion:
◦ Preselected validators may collude, compromising the integrity of the blockchain.

Use Cases for Permissioned Blockchains


1. Supply Chain Management:
◦ Track goods and verify transactions among trusted participants, such as suppliers,
manufacturers, and distributors.
2. Healthcare:
◦ Maintain patient records, ensuring secure data sharing among hospitals, insurance
companies, and patients.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 55 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Finance:
◦ Process interbank settlements and manage asset tokenization with secure and
efÞcient transaction validation.
4. Government Applications:
◦ Facilitate secure voting systems, land registry management, and welfare distribution
with transparency and privacy.
5. Enterprise Resource Planning (ERP):
◦ Enable secure collaboration among different departments or subsidiaries within an
organization.

Aspect Permissioned Blockchain Permissionless Blockchain


Access Restricted to authorized participants Open to anyone; no restrictions on
Control who are vetted. joining the network.
Managed by a central authority or Decentralized, governed by the entire
Governance
consortium of organizations. community of participants.
Known and trusted entities with Anonymous or pseudonymous
Participants
predeÞned roles. participants.
Transaction Only authorized nodes can validate Any node can participate in transaction
Validation transactions. validation (e.g., mining/staking).
Consensus EfÞcient mechanisms like PBFT, Raft, Computationally intensive mechanisms
Mechanism or PoA. like PoW or PoS.
Typically more scalable due to
Less scalable due to high computational
Scalability controlled access and efÞcient
overhead and open participation.
consensus.
High; data sharing can be controlled Low; all data is publicly accessible and
Data Privacy
and selective. transparent.
Relies on trust among participants and Ensures security through decentralized
Security
central oversight. trust and cryptography.
Immutability is maintained, but
Full immutability with no central
Immutability governing bodies can implement
control.
changes.
Faster due to fewer participants and Slower due to the need for global
Speed
optimized protocols. consensus.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 56 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Lower operational costs as energy-


Higher operational costs, especially with
Cost intensive consensus (like PoW) is
PoW, due to energy consumption.
avoided.
Limited to authorized participants; not Fully transparent; anyone can view
Transparency
entirely public. transactions.
Examples Hyperledger, Corda, Quorum Bitcoin, Ethereum, Solana
Enterprise applications (e.g., supply Cryptocurrency, DeFi, open-source smart
Use Cases
chain, Þnance, healthcare). contracts.

Cryptography

Cryptography in blockchain refers to the use of cryptographic techniques to secure data,


ensure its integrity, and validate transactions within the distributed ledger. It is the backbone of
blockchain technology, enabling secure and decentralized systems.

Why Cryptography is Required in Blockchain?

1. Security:
◦ Ensures that the data stored on the blockchain is protected from unauthorized access
or tampering.
◦ Transactions are encrypted, making them difficult to decode without the appropriate
keys.
2. Integrity:
◦ Guarantees that data in the blockchain remains unchanged once written.
◦ Hash functions detect even the smallest alterations in data.
3. Authentication:
◦ Digital signatures validate the authenticity of transactions, ensuring they come from
a legitimate sender.
4. Transparency and Privacy:
◦ While blockchain is transparent, cryptographic techniques (like public-key
cryptography) maintain the confidentiality of user information.
5. Decentralization:
◦ Cryptographic algorithms eliminate the need for a centralized authority by enabling
trustless interactions between parties.

Core Cryptographic Implementations in Blockchain

1. Hash Functions:
◦ Converts input data into a fixed-size string of characters (hash value).
◦ Properties:
▪ Deterministic: Same input always gives the same hash.
▪ Irreversible: Impossible to determine the original data from its hash.
▪ Collision-resistant: No two different inputs should produce the same hash.
◦ Example: SHA-256 used in Bitcoin.
2. Public-Key Cryptography (Asymmetric Encryption):
◦ Involves a pair of keys: a public key (shared openly) and a private key (kept secret).
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 57 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ Applications:
▪ Digital signatures for transaction validation.
▪ Encryption for data privacy.
◦ Example: Elliptic Curve Digital Signature Algorithm (ECDSA) in Bitcoin.
3. Digital Signatures:
◦ Prove the authenticity of a transaction and ensure it hasn't been tampered with.
◦ Combine the sender's private key with transaction data to generate a unique
signature.
4. Merkle Trees:
◦ Data structure that organizes transactions using hash functions in a tree-like format.
◦ Enables efficient verification of data without downloading the entire blockchain.

Advantages of Cryptography in Blockchain:

1. Security:
◦ Prevents unauthorized access, data breaches, and tampering.
2. Data Integrity:
◦ Guarantees that transactions and blocks cannot be altered after inclusion in the
blockchain.
3. Decentralized Trust:
◦ Eliminates the need for central authorities by enabling cryptographic proof of
validity.
4. Privacy:
◦ Protects user identities and transaction details using encryption.
5. Transparency and Verifiability:
◦ Allows all participants to verify the authenticity of transactions.

Disadvantages of Cryptography in Blockchain:

1. Complexity:
◦ Cryptographic algorithms are computationally intensive, requiring significant
processing power.
2. Energy Consumption:
◦ Proof of Work (PoW), a consensus mechanism that relies heavily on cryptography,
consumes large amounts of energy.
3. Irreversible Errors:
◦ Losing private keys permanently locks access to associated funds or data.
4. Scalability Issues:
◦ Cryptographic computations and veriÞcations can limit transaction throughput in
large-scale systems.
5. Quantum Vulnerability:
◦ Quantum computers, once mature, could potentially break existing cryptographic
algorithms, threatening blockchain security.

Cryptographic - Hash Functions

Hash functions are fundamental to public key cryptography and cryptocurrencies. A hash
function is a mathematical algorithm that transforms an input (or "message") into a fixed-length

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 58 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

output, typically a string of characters. Cryptographic hash functions are designed to be one-way
(meaning they cannot be reversed) and collision-resistant (meaning it's computationally infeasible
to find two different inputs that produce the same output). In public key cryptography, hash
functions are used for creating digital signatures, ensuring data integrity, and generating unique
identifiers. They are also central to the creation of addresses in cryptocurrencies, especially Bitcoin.

A hash function is a fundamental concept in computer science and cryptography that transforms an
input (or message) of arbitrary length into a Þxed-length output, called a hash value or digest.
Mathematically, a hash function can be represented as:

H(M) = h
where:
• H is the hash function,
• M is the input message,
• h is the output hash value of Þxed size.

Properties of a Cryptographic Hash Function:


1. Deterministic Ð The same input always produces the same hash output.
2. Fixed Output Length Ð Regardless of input size, the hash output has a Þxed length (e.g.,
256 bits for SHA-256).
3. Preimage Resistance (One-way property) Ð Given h, it should be computationally
infeasible to Þnd M such that H(M)=h.
4. Second Preimage Resistance Ð Given an input M1, it should be difÞcult to Þnd a different
input M2 such that H(M1)=H(M2).
5. Collision Resistance Ð It should be infeasible to Þnd any two distinct inputs M1 and M2
where H(M1)=H(M2).
6. Avalanche Effect Ð A small change in input should cause a drastic change in the output
hash.

Key Characteristics of Hash Functions


1. Deterministic:
◦ The same input always produces the same hash output.
◦ Example: Hash("hello") always results in the same hash value.
2. Fixed Output Size:
◦ Regardless of the size of the input, the hash output has a consistent length.
◦ Example: SHA-256 always produces a 256-bit (64-character hexadecimal) hash.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 59 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Fast Computation:
◦ The hash value is generated quickly, making it efÞcient for real-time applications.
4. Pre-image Resistance:
◦ It is computationally infeasible to reverse-engineer the original input from its hash.
5. Collision Resistance:
◦ It is highly unlikely for two different inputs to produce the same hash.
6. Avalanche Effect:
◦ A small change in the input causes a signiÞcant and unpredictable change in the hash
output.
7. Non-reversibility:
◦ Hash functions are one-way, meaning you cannot determine the input from the hash
output.

Hash Functions in Blockchain


1. Securing Transactions:
¥ Each transaction is hashed to create a unique identiÞer.
¥ Ensures the integrity of transaction data.
2. Linking Blocks:
¥ Each block contains the hash of the previous block, creating a chain.
¥ This linkage ensures that altering one block requires recalculating hashes for all subsequent
blocks.
3. Proof of Work (PoW):
¥ Miners solve a computational puzzle by Þnding a hash that meets speciÞc criteria (e.g.,
starts with a certain number of zeros).
¥ Ensures consensus and security in blockchain networks like Bitcoin.
4. Merkle Trees:
¥ Transactions within a block are hashed and organized in a tree structure, where the root hash
represents all transactions.
¥ Enables efÞcient and secure transaction veriÞcation.

Examples of Hash Functions

1. SHA-256 (Secure Hash Algorithm 256-bit):


◦ Widely used in blockchain (e.g., Bitcoin).
◦ Produces a 256-bit hash.
◦ Example:
◦ Input: "Hello, Blockchain"
Output: 87c7f5c8dc194af7e9ea8c003d2a70228d4ee038e4bda4f7e1d5d88327a2d51f
2. RIPEMD-160:
◦ Used in Bitcoin to generate addresses.
◦ Produces a 160-bit hash.
3. Keccak-256:
◦ A variant of SHA-3, used in Ethereum.

Advantages of Hash Functions in Blockchain


1. Data Integrity:
◦ Ensures data cannot be altered without detection.
2. Security:
◦ Protects sensitive data through one-way encryption.
3. EfÞciency:
◦ Hash functions are computationally fast.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 60 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

4. Immutability:
◦ Altering one block would require recalculating hashes for all subsequent blocks,
making tampering infeasible.
5. Verification:
◦ Simplifies verifying the authenticity of transactions or data.

Disadvantages of Hash Functions


1. High Computational Cost:
◦ Hashing large amounts of data can be resource-intensive.
2. Collision Possibility:
◦ Although rare, collisions (two inputs producing the same hash) can undermine the
system's security.
3. Quantum Computing Threat:
◦ Quantum computers may potentially break existing hash algorithms in the future.

Need of Hash Functions in Public Key Cryptography and Cryptocurrency

Public Key Cryptography (PKC):


In PKC, the hash function helps in:
¥ Message Authentication: It guarantees that the data hasnÕt been altered by creating a
unique fingerprint of the message.
¥ Digital Signatures: Hash functions are used to create the digest of the message that is then
signed by the private key, ensuring the authenticity and integrity of the data.
¥ Data Integrity: In the case of digital certificates, the hash value of the certificate is signed,
ensuring it hasnÕt been tampered with.

Cryptocurrencies:
In cryptocurrencies like Bitcoin, hash functions are crucial for:
¥ Address Generation: The process of generating public addresses involves the
transformation of the public key through various hashing mechanisms.
¥ Transaction Verification: Hash functions validate transactions and blocks by creating
unique identifiers.
¥ Proof of Work (PoW): Cryptocurrencies like Bitcoin use hash functions in the mining
process to find valid block hashes, ensuring consensus without a central authority.
¥ Security: Hash functions ensure that transaction data cannot be altered without detection,
providing the security necessary to build trust in the system.

Private and Public Keys

Private and Public Keys:


¥ Private Key: This is a secret key used to sign transactions and prove ownership of
cryptocurrency in a given wallet.
¥ Public Key: This is derived from the private key and serves as a public address to which
others can send cryptocurrency.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 61 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Uncompressed vs. Compressed Public Keys:


¥ Uncompressed Public Key: An uncompressed public key is 65 bytes long, starting with
0x04. It consists of both the x and y coordinates of the elliptic curve point.
◦ Format: 0x04 + 32-byte x-coordinate + 32-byte y-coordinate

¥ Compressed Public Key: A compressed public key is 33 bytes long and only stores the x-
coordinate. Depending on whether the y-coordinate is odd or even, it is prefixed with 0x02
or 0x03, respectively.
◦ Format: 0x02/0x03 + 32-byte x-coordinate

The compressed format is used in Bitcoin for space-saving reasons as it reduces the size of
transactions and optimizes blockchain efficiency.

Elliptic Curve Cryptography (ECC)


Elliptic Curve Cryptography (ECC) is a form of public-key cryptography based on the
algebraic structure of elliptic curves over finite fields. It is widely used in Bitcoin for its efficiency,
providing strong security with smaller key sizes compared to traditional systems like RSA.
Elliptic Curve Equation:
The general equation for an elliptic curve is given by: y=x3+ax+b(mod p)
Where:
• a and b are constants that define the curve,
• p is a prime number defining the finite field over which the curve is defined.

ECC relies on a fundamental operation known as point multiplication. Given a base point G (the
generator point on the curve) and an integer k (the private key), the resulting public key P is
computed as:

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 62 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

P = k⋅G
This operation involves adding the point G to itself k times, which results in a new point P. This
operation is computationally difÞcult to reverse, providing the security for the system. The
challenge of reversing this process is known as the Elliptic Curve Discrete Logarithm Problem
(ECDLP).

To visualize point multiplication, imagine moving along the curve starting from G and repeatedly
adding the point to itself. The result, after k multiplications, is the point P, which forms the public
key. The private key k remains secret, while P is used as the public key.

Public Key to Bitcoin Address Conversion


A Bitcoin Address is derived from the public key using a series of cryptographic transformations to
ensure that the address is secure and identifiable. The process follows these steps:

Steps to Convert Public Key to Bitcoin Address:

1. Generate Public Key: The public key P is obtained by multiplying the private key k with
the generator point G on the elliptic curve:
P = k⋅G

2. Hash the Public Key: The public key is hashed using two different hashing algorithms:
◦ First, apply SHA-256 to the public key P: SHA−256(P)
◦ Then, apply RIPEMD-160 to the result of the SHA-256 hash:
RIPEMD160(SHA−256(P))
◦ This produces the public key hash (PKH).

3. Add Version Byte: A version byte is added to the public key hash to differentiate between
different types of Bitcoin addresses. For the main Bitcoin network, this version byte is 0x00.
The result is:
Version Byte+PKH

4. Compute Checksum: To ensure the integrity of the address, a checksum is appended:


Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 63 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

◦ First, apply SHA-256 to the


versioned public key hash.
◦ Then, apply SHA-256 again to
the result.
◦ The checksum is the first 4 bytes
of this second hash:
Checksum=First 4 bytes of SHA-
256(SHA-256(data))
◦ Append this checksum to the end
of the versioned public key hash.

5. Base58Check Encoding: The final


address is encoded in Base58 format (to
avoid visually similar characters) using
the version byte + public key hash +
checksum. Base58 encoding ensures that
the address is short, human-readable, and
resistant to common transcription errors.

Formula for Bitcoin Address:

Bitcoin Address=Base58Check(Version Byte+PKH+Checksum)


Where, P is the public key.

Base58Check Encoding: A Bitcoin-SpeciÞc Encoding Format

Base58Check is a custom encoding scheme used in Bitcoin to represent public keys, private
keys, and Bitcoin addresses. The main advantage of Base58 over Base64 is that it avoids confusing
characters like 0, O, I, and l, making it more suitable for human input.

Steps in Base58Check Encoding:


1. PreÞx with Version Byte: The Þrst step is to add a version byte to indicate the type of
Bitcoin address. For the main Bitcoin network, this version byte is 0x00 (which indicates a
normal Bitcoin address). This version byte is preÞxed to the data (such as the public key
hash or private key).
2. Add Data: The next step is to append the actual data (for instance, the public key hash) to
the version byte.
3. Checksum Calculation: To verify the integrity of the data, a checksum is computed:
◦ Apply SHA-256 to the version byte + data.
◦ Then, apply SHA-256 again to the result.
◦ Take the Þrst 4 bytes of this double-hashed result as the checksum.
4. Base58 Encoding: Finally, the version byte, data, and checksum are encoded using Base58.
This encoding produces a compact and error-resistant string suitable for Bitcoin addresses.

Formula for Base58Check:


Base58Check(Version Byte+Data+Checksum)
Where the checksum is derived by double-hashing the data and taking the Þrst 4 bytes.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 64 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Sample Output:

import hashlib
import base58
from ecdsa import SECP256k1, ellipticcurve, util
from ecdsa.keys import ECPrivateKey

# Constants for Bitcoin address version byte (mainnet) and elliptic curve parameters
VERSION_BYTE = b'\x00' # Version byte for Bitcoin mainnet addresses
CURVE = SECP256k1.curve
G = SECP256k1.generator
ORDER = SECP256k1.order

def sha256(data):
"""SHA-256 hash function."""
return hashlib.sha256(data).digest()

def ripemd160(data):
"""RIPEMD160 hash function."""
return hashlib.new('ripemd160', data).digest()

def base58_check_encode(data):
"""Encodes data with Base58Check encoding."""
checksum = hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
return base58.b58encode(data + checksum)

def private_key_to_public_key(private_key):
"""Converts a private key to a public key using ECC (SECP256k1)."""
# Calculate the public key: P = k * G
pub_point = private_key * G
x, y = pub_point.x(), pub_point.y()

# Public key is the combination of x and y coordinates


pub_key = bytes([0x04]) + x.to_bytes(32, 'big') + y.to_bytes(32, 'big')
return pub_key

def public_key_to_bitcoin_address(public_key):
"""Converts a public key to a Bitcoin address using Base58Check encoding."""
# Step 1: Hash the public key (SHA256 then RIPEMD160)
sha256_hash = sha256(public_key)
ripemd160_hash = ripemd160(sha256_hash)

# Step 2: Add version byte (0x00 for mainnet)


versioned_pub_key_hash = VERSION_BYTE + ripemd160_hash

# Step 3: Create checksum by double hashing


checksum = hashlib.sha256(hashlib.sha256(versioned_pub_key_hash).digest()).digest()[:4]

# Step 4: Apply Base58Check encoding


bitcoin_address = base58_check_encode(versioned_pub_key_hash)

return bitcoin_address.decode()
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 65 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

# Example Usage:

# Generate a random private key (for demonstration purposes, in a real scenario you should
generate securely)
private_key = int.from_bytes(hashlib.sha256("random_string".encode()).digest(), byteorder='big')
% ORDER

# Convert private key to public key


public_key = private_key_to_public_key(private_key)

# Convert public key to Bitcoin address


bitcoin_address = public_key_to_bitcoin_address(public_key)

# Print the private key, public key, and Bitcoin address


print(f"Private Key (hex): {hex(private_key)}")
print(f"Public Key (hex): {public_key.hex()}")
print(f"Bitcoin Address: {bitcoin_address}")

Output:
Private Key (hex): 0x3d2fe4b626f34ac6016cd8e79534956d22641e7b1d8815b2baf1532c07a7c8e3
Public Key (hex):
04b0b8f226a945d2078391ac2f0cf9f74cfd4644d5f8bc6c748a2b8e08a9b7e5b31b06a01aee7580eafc
e17925487ff1054ed41bb4ad9f56450f0c2005b7b99a8f0
Bitcoin Address: 1FfRgfA4qsgxzvT5aSwnF7V7DGrXtHk4XQ

Properties of Hash Function were,

1. Deterministic
A hash function is deterministic, meaning that for the same input, it will always produce the
same output. This is essential for ensuring data consistency. The process of hashing should be
repeatable and reliable.
• Formula: H(x) = y
• Where:
◦ x is the input (message or data).
◦ y is the hash value (output).
◦ H(x) will always produce the same y for the same x.
Example:
For the input string "hello", the hash value produced by a function like SHA-256 will always be the
same.
Example in practice:
¥ Input: "hello"
¥ Output (SHA-256):
2cf24dba5fb0a30e26e83b2ac5b9e29e1b168ee29f1954eeb17a75ab2d6fe758

2. Fixed Output Length


Regardless of the length of the input data, the output (hash value) will always have a fixed
length. For example, the SHA-256 algorithm always produces a 256-bit (32-byte) hash value.
¥ Formula: Length of H(x) = n
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 66 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

¥ Where:
◦ n is fixed (e.g., for SHA-256, n = 256 bits).
¥ This property ensures that large inputs, such as files or messages of varying sizes, are
compressed into a consistent-sized output.
Example in practice:
¥ Input: "hello"
¥ Output (SHA-256):
2cf24dba5fb0a30e26e83b2ac5b9e29e1b168ee29f1954eeb17a75ab2d6fe758
¥ Output length: 256 bits (or 64 hexadecimal characters)

3. EfÞcient Computation
A good hash function should be computationally efÞcient, meaning that it should take a
minimal amount of time to compute the hash, regardless of the input size. This ensures that the
system works fast enough for practical use in real-time applications.
Formula: If t(x) represents the time to compute the hash of input x, then the time complexity
should be close to O(n), where n is the size of the input.
t(x)=O(n)

Example:
¥ For SHA-256:
◦ The function will compute the hash in a time complexity that is proportional to the
size of the data, i.e., linear in the number of bytes.
◦ For very large data (e.g., multi-gigabyte Þles), efÞcient implementations ensure the
hash can be calculated quickly.

4. Preimage Resistance (One-Way Function)


Preimage resistance means that it is computationally infeasible to Þnd an input x such that
H(x) = y for a given output y. This property is crucial for ensuring that given a hash value, you
cannot reverse-engineer the original input.
¥ Formula: Given a hash value y, it should be computationally infeasible to Þnd x such that:H
H(x) = y For any randomly chosen y, Þnding x such that the equation holds should take an
infeasible amount of time (ideally exponential in the length of the output).

5. Second Preimage Resistance


Second preimage resistance means that it is computationally infeasible to Þnd another input x′
(where x′ ≠ x ) such that H(x)=H(x′). This ensures that itÕs very hard to Þnd two different inputs
that produce the same hash value.
¥ Formula: Given an input x and its corresponding hash H(x), it should be computationally
infeasible to Þnd another input x′ ≠ x such that: H(x)=H(x′).

6. Collision Resistance
Collision resistance means that it is computationally infeasible to Þnd two distinct inputs x1
and x2 such that: H(x1 )=H(x2 )
This is a critical property for security because if two different pieces of data hash to the same value,
it can lead to vulnerabilities in applications like digital signatures or data integrity checks.
¥ Formula: For any two distinct inputs x1 and x2 , the probability of H(x1 )=H(x2 ) should
be extremely low.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 67 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

7. Avalanche Effect
The avalanche effect means that a small change in the input (even a single bit) should
produce a significantly different hash output. This ensures that the hash function spreads the
information uniformly across the output space, which improves security by making patterns in the
input unpredictable in the output.
¥ Formula: If x and x′ differ by one bit, the difference between H(x) and H(x′) should be
maximal in terms of bit difference. This can be observed as a large Hamming distance
between the hash values.
H(x) ≠ H ( x′) for x ≠ x′

8. Non-reversible
A good hash function is non-reversible, meaning that thereÕs no feasible way to reverse the process
and recover the original input x from its hash value H(x).
¥ Formula: There should be no efficient algorithm that can recover x from H(x). That is:
Given H(x), find x should be computationally infeasible.

9. Uniform Distribution
The output of a hash function should appear uniformly distributed over its output space. This means
that every possible hash value should be equally likely to occur, regardless of the input. A non-
uniform distribution could lead to predictable patterns, which would reduce security.
¥ Formula: The hash values H(x) for all possible inputs x should be evenly distributed across
the output space.
Pr[H(x)=h]=1/ 2n
¥ Where n is the length of the hash value in bits, and h represents any possible hash output.

SHA-256 in Blockchain

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function used


extensively in blockchain technology for ensuring data integrity, security, and consensus. It is part
of the SHA-2 family, developed by the National Security Agency (NSA) and standardized by
NIST (National Institute of Standards and Technology).

SHA-256 is particularly critical in Bitcoin and other cryptocurrencies, where it is used for
transaction integrity, mining (Proof-of-Work), and block validation.

How SHA-256 Works in Blockchain


1. Input Processing: The input message (transaction data) is padded to make its length a
multiple of 512 bits.
2. Block Processing: The data is split into 512-bit blocks, and each block undergoes 64 rounds
of processing using bitwise operations.
3. Compression and Hash Generation: The algorithm updates an internal state using
predeÞned constants and functions, producing a Þnal 256-bit hash.

Key Properties
¥ Deterministic: The same input always results in the same hash.
¥ Pre-image Resistance: It is computationally infeasible to Þnd the original input from the
hash.
¥ Collision Resistance: No two different inputs should produce the same hash.
¥ Avalanche Effect: A small change in input results in a completely different hash.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 68 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Role in Blockchain
¥ Block Hashing: Each block's header is hashed using SHA-256, linking blocks securely.
¥ Proof of Work (PoW): Miners solve a cryptographic puzzle by Þnding a hash below a
target value.
¥ Transaction Integrity: Ensures that transactions cannot be altered after being recorded.

Feature SHA-256 SHA-512


Hash Output 256 bits (32 bytes) 512 bits (64 bytes)
Hash Length
64 characters 128 characters
(Hexadecimal)
Block Size 512 bits (64 bytes) 1024 bits (128 bytes)
Rounds 64 rounds 80 rounds
Processing Speed (32-bit
Faster Slower
systems)
Processing Speed (64-bit
Slower Faster
systems)
Memory Requirements Lower memory usage Higher memory usage
Security Level 128-bit security 256-bit security
Stronger resistance against
SufÞcient for most current systems,
Strength Against Attacks collision, pre-image, and
but lower security
birthday attacks
Bitcoin, Ethereum, digital
High-security applications, PGP,
Key Applications signatures, SSL/TLS, certiÞcate
digital certiÞcates, SSL/TLS
generation
Resistance to Quantum Stronger due to larger bit size
Moderate
Computing and more rounds
Public blockchains (e.g., Bitcoin, High-security applications, long-
Typical Use Case Ethereum), data integrity checks, term data integrity, enterprise-
digital signatures level encryption

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 69 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Computational Lower due to smaller block size and


Higher due to larger block size
Complexity fewer rounds and more rounds
More efÞcient for embedded Less efÞcient for low-power
EfÞciency (Low-Power
systems, IoT devices, and systems
systems due to greater resource
Systems)
with limited resources demand
Resistant to attacks with 2^128 Stronger, resistant to attacks with
Collision Resistance
complexity 2^256 complexity
High resistance to Þnding a Higher resistance to pre-image
Pre-image Resistance
matching input for a given hash attacks
Vulnerable to attacks with Stronger resistance, requires
Birthday Attack
2^64complexity (weaker compared 2^128 complexity for birthday
Resistance
to SHA-512) attacks
Rarely used in blockchain
Widely used in Bitcoin and
Common Use in systems due to its larger size, but
Ethereum to secure transactions and
Blockchain can be applied for additional
blocks
security where required
Optimized for 32-bit processors,
Optimized for 64-bit processors,
Hardware Optimization better for resource-constrained
better for modern hardware
environments
Higher security level, more
Lower security level, less resilient to
Flexibility for Future suitable for resilience against
future advancements like quantum
Technologies future cryptographic
computing
advancements

Hash pointer and Merkle tree

Hash Pointer :

A Hash Pointer is a combination of two elements:


1. A Pointer: A reference or address to the location of a piece of data in memory or a data
structure.
2. A Cryptographic Hash: A Þxed-size, unique identiÞer (Þngerprint) generated from the data
at the pointer's address.

Key Features:
¥ Pointer: The pointer gives the location of the data, such as a memory address, index, or Þle
location.
¥ Cryptographic Hash: The hash of the data stored at that address is computed using a hash
function (e.g., SHA-256, SHA-3). A cryptographic hash function takes an input (data) and
produces a Þxed-size hash value that uniquely represents the data.

Properties of Hash Pointer:


1. Data Integrity:
◦ The hash ensures the data hasnÕt been altered, as even a tiny change in the data will
lead to a drastically different hash.
2. EfÞcient VeriÞcation:
◦ You can verify the integrity of the data by comparing its hash rather than comparing
the entire data itself.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 70 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Tamper Detection:
◦ If an attacker tries to modify the data, the hash will change, and the tampered data
will be easily detected.
4. Unambiguous Representation:
◦ The hash uniquely represents the data, making it ideal for referencing data in a
secure and compact manner.
Mathematical Representation:
Given some data D, the cryptographic hash function H maps the data to a unique value:
H(D)=hash of data D.

The Hash Pointer is then a tuple: Hash Pointer=(Pointer to data,H(D))


Example of Hash Pointer:
Consider a document that says "Hello, World!" stored at memory address M. The hash pointer for
this document would consist of:
¥ Pointer: M, the memory location of the document.
¥ Hash: H("Hello, World!"), a cryptographic hash of the document.

In this case, the pointer points to the memory location M, and the hash H("Hello, World!") acts as a
Þngerprint. If the document changes, its hash would also change, alerting you to tampering.

Applications:
¥ Linked Data Structures: In blockchains, the blocks are linked via hash pointers. Each
block contains a pointer to the previous block and a hash of its data, ensuring that tampering
with any block will invalidate the subsequent blocks.
¥ File Systems: Merkle Trees (which use hash pointers) are used to maintain the integrity of
Þles stored in a decentralized Þle system, such as IPFS (InterPlanetary File System).

Merkle Tree

A Merkle Tree (or binary hash tree) is a tree-like data structure used to efficiently verify the
integrity and consistency of large datasets. ItÕs a cryptographic structure where each leaf node
represents a hash of data, and each non-leaf node represents the hash of its children. At the top of
the tree is the Merkle Root, which represents the cryptographic fingerprint of all the data in the
tree.
Merkle Tree Structure:
1. Leaf Nodes:
◦ Each leaf node contains the cryptographic hash of an individual data block.
2. Internal Nodes:
◦ Non-leaf nodes contain the hash of the concatenation of their two child nodes'
hashes.
3. Merkle Root:
◦ The root node of the tree represents the cryptographic hash of all the data in the tree.
ItÕs a single hash value that provides a unique representation of the entire dataset.

Mathematical Construction of a Merkle Tree:


1. LetÕs say you have a dataset of n pieces of data (e.g., transactions in a blockchain).
2. First, compute the hash of each data block to get the leaf nodes: H1 =H(Data 1),H2 =
H(Data 2),É,Hn =H(Data n)

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 71 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

3. Pair adjacent leaf nodes and compute the hash of each pair to create the internal nodes: H12
=H(H1 ∣∣H2 ),H34 =H(H3 ∣∣H4 ),É
4. Continue this process, pairing and hashing, until a single Merkle Root is
obtained:Merkle Root
Merkle Root=H(H(H1 ∣∣H2 )∣∣H(H3 ∣∣H4 ))

Merkle Tree Example (4 Data Blocks):


Assume we have four data blocks, D1, D2, D3, and D4 .
1. Leaf Nodes (Hashes of data):
H(D1 ),H(D2 ),H(D3 ),H(D4 )
2. First Level (Internal Nodes):
H(H(D1 )∣∣H(D2 )),H(H(D3 )∣∣H(D4 ))
3. Second Level (Root Node):
H(H(H(D1 )∣∣H(D2 ))∣∣H(H(D3 )∣∣H(D4 )))The Þnal Merkle Root represents a single hash
summarizing the integrity of all four data blocks.

Merkle Tree Operations and VeriÞcation


Merkle Path:
To verify that a particular leaf (e.g., D3 ) is part of the Merkle Tree, we need the Merkle
Path. This path consists of the hashes of the sibling nodes along the way to the root.
¥ If you want to prove that D3 is part of the tree, you need:
◦ The hash of H(D4 ) (the sibling of D3 ).
◦ The hash of H(D1 ) and H(D2 ) (the other branch).
Using these hashes, you can recompute the Merkle Root and verify that D3 is indeed part of the
tree.

Merkle Proof:
A Merkle Proof is a subset of the tree required to prove that a particular piece of data is
included in the dataset represented by the Merkle Root. It includes the following:
1. The hash of the data (leaf node).
2. The hashes of the sibling nodes up the tree.
3. The Merkle Root.

Mathematical Proof of Membership:


Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 72 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

To prove that a particular data element Di is part of the Merkle Tree:


1. Start with the hash of Di , i.e., H(Di ).
2. Concatenate it with the sibling hash and compute the hash of the pair: H(H(Di )∣∣H(sibling))
3. Repeat this process up the tree, hashing pairs of nodes until you reach the Merkle Root.
4. If the computed Merkle Root matches the Merkle Root stored in the tree, the data element
is conÞrmed to be part of the tree.

Applications of Merkle Trees


1. Blockchain Technology:
◦ Merkle Trees are widely used in cryptocurrency systems (like Bitcoin) to
efÞciently validate transactions.
◦ In Bitcoin, each block contains a Merkle Tree of all the transactions in that block,
with the Merkle Root stored in the block header.
◦ Nodes only need the Merkle Path (logarithmic in size) to validate that a transaction
is part of a block.
2. Digital Signatures:
◦ Merkle Trees can be used in Merkle Signature Schemes where each leaf is a digital
signature of a data block. These schemes are efÞcient and scalable for systems that
require signing large datasets.
3. Distributed File Systems:
◦ In IPFS (InterPlanetary File System), Merkle Trees are used to verify the integrity of
Þles distributed across a network. Each block in a Þle is hashed and included in a
Merkle Tree, and only the root hash is needed to verify the Þle.
4. EfÞcient Data Structures:
◦ Merkle Tries and Merkle Patricia Tries are used in Ethereum for efÞcient storage
and retrieval of key-value pairs.

Advantages of Merkle Trees:


1. EfÞcient VeriÞcation:
◦ Logarithmic veriÞcation time: To verify an element in a Merkle Tree, only a
logarithmic number of hashes (with respect to the total number of elements) is
needed.
2. Scalability:
◦ Merkle Trees scale efÞciently as they can summarize a large amount of data into a
single hash (the Merkle Root).
3. Data Integrity:
◦ By using cryptographic hashes, any change in the data (even a single bit) will change
the Merkle Root, making tampering detectable.
4. Minimal Data Transfer:
◦ In distributed systems, Merkle Trees allow veriÞcation of data with minimal
communication. Only the Merkle Path needs to be transferred, rather than the entire
data.

Example:

Merkle Tree Construction Example (4 Data Blocks)


LetÕs say we have four data blocks:
• D1 = "Data Block 1"
• D2 = "Data Block 2"
• D3 = "Data Block 3"
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 73 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

• D4 = "Data Block 4"

Step 1: Compute the Hash of Each Data Block (Leaf Nodes)

First, we compute the cryptographic hash of each data block using a hash function, such as
SHA-256.

• H(D1 )=Hash of D1
• H(D2 )=Hash of D2
• H(D3 )=Hash of D3
• H(D4 )=Hash of D4

For simplicity, let's say the hashes are:


• H(D1 )=Hash1
• H(D2 )=Hash2
• H(D3 )=Hash3
• H(D4 )=Hash4

These are the leaf nodes of the Merkle Tree.

Step 2: Combine Leaf Nodes in Pairs to Create Internal Nodes


Next, pair up the leaf nodes and compute the hashes of each pair.
¥ Combine H(D1 ) and H(D2 ) to compute a new hash:
H12 =H(H(D1 )∣∣H(D2 ))=H(Hash1∣∣Hash2)
¥ Combine H(D3 ) and H(D4 ) to compute another new hash:
H34 =H(H(D3 )∣∣H(D4 ))=H(Hash3∣∣Hash4)
Now, we have two internal nodes:
• H12 is the hash of the first pair of data blocks.
• H34 is the hash of the second pair of data blocks.

Step 3: Combine the Internal Nodes to Create the Merkle Root


Now that we have two internal nodes H12 and H34 , we combine them to compute the Merkle
Root:
¥ Combine H12 and H34 to compute the final hash:
¥ Merkle Root
Merkle Root=H(H12 ∣∣H34 )=H(Hash of first pair∣∣Hash of second pair)

Step 4: Merkle Tree Structure

Merkle Root
|
-------------------------
| |
H_{12} H_{34}
| |
------------- -------------
| | | |
H(D_1) H(D_2) H(D_3) H(D_4)

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 74 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

¥ The leaf nodes are the hashes of the data blocks.


¥ The internal nodes are the hashes of the concatenated pairs of the leaf nodes.
¥ The Merkle Root is the final hash at the top of the tree, representing the entire dataset.

Step 5: Verifying Membership with Merkle Path


To verify if a data block (e.g., D3 ) is part of the Merkle Tree, we need the Merkle Path. This is the
hash chain that connects the leaf node for D3 to the Merkle Root.
For D3 , the Merkle Path would consist of:
¥ The sibling of H(D3 ), which is H(D4 ).
¥ The internal node H34 , which includes the hash of H(D3 ) and H(D4 ).
¥ The Merkle Root, which includes the hash of H12 and H34 .

To prove that D3 is part of the Merkle Tree, you would use the Merkle Path to recompute the
Merkle Root:
1. Start with H(D3 ).
2. Use the sibling hash H(D4 ) and compute: H(H(D3 )∣∣H(D4 ))=H(H(D3 )∣∣Hash4)
3. Then, use H34 to recompute the next step: H(H34 ∣∣H12 )=Merkle Root
4. If the recomputed Merkle Root matches the Merkle Root in the tree, then D3 is part of the
Merkle Tree.

Layers of Blockchain

Blockchain technology is structured into multiple layers, each with a distinct role in ensuring the
security, decentralization, and efÞciency of the system.

1. Infrastructure Layer (Hardware & Networking Layer)


This is the foundational layer responsible for the physical hardware, networking protocols, and
computational resources required to run a blockchain network.
Key Components:
¥ Nodes (Computers in the Blockchain Network):
◦ Full Nodes: Store the entire blockchain and validate transactions independently.
◦ Light Nodes: Store only necessary data for efÞciency.
◦ Mining Nodes (for PoW Blockchains): Solve complex puzzles to add new blocks.
◦ Validator Nodes (for PoS Blockchains): Validate and conÞrm transactions based on
staked tokens.
¥ Peer-to-Peer (P2P) Network:
◦ Decentralized communication between nodes.
◦ Uses a gossip protocol to distribute transaction data across the network.
¥ Cloud Infrastructure (Optional):
◦ Some blockchains rely on cloud services to host nodes and store data.
◦ Examples: AWS, Google Cloud, Microsoft Azure for Blockchain-as-a-Service
(BaaS).
Functions:
¥ Ensures global accessibility of the blockchain network.
¥ Provides the necessary computational power for transaction validation.
¥ Supports decentralization by enabling peer-to-peer interaction.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 75 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

2. Data Layer (Storage & Cryptographic Security Layer)


The data layer is responsible for storing blockchain transactions, cryptographic hashes, and essential
data structures such as Merkle Trees and Hash Pointers.
Key Components:
¥ Blocks:
◦ Each block contains transactions, a timestamp, a nonce, and a reference to the
previous block.
◦ Linked together to form an immutable ledger.
¥ Transactions:
◦ Records of asset transfers between participants.
◦ Signed using cryptographic keys for security.
¥ Cryptographic Hashing:
◦ Converts data into a Þxed-length hash to ensure security.
◦ Example: SHA-256 in Bitcoin: H=SHA−256(input)
¥ Merkle Tree:
◦ A hierarchical data structure used for efÞcient transaction veriÞcation.
◦ Example: If we have four transactions (T1, T2, T3, T4), their hashes (H1, H2, H3,
H4) are combined to form a tree-like structure:
Hroot =H(H1+H2)+H(H3+H4)
◦ The root hash is stored in the block header for quick veriÞcation.
¥ Hash Pointers:
◦ Each block contains a reference (hash) to the previous block, creating a chain of
blocks.
◦ Ensures tamper-proof securityÑif one block is altered, all subsequent blocks
become invalid.
Functions:
¥ Ensures data immutability and security.
¥ Provides a lightweight and efÞcient way to verify transactions.
¥ Prevents fraud and tampering through cryptographic hashing.

3. Network Layer (Transaction & Block Propagation Layer)


The network layer is responsible for communication and data exchange between nodes in the
blockchain network.
Key Components:
¥ Node Discovery:
◦ Nodes Þnd and connect with each other to maintain decentralization.
¥ Transaction Propagation:
◦ Transactions are broadcast to all nodes for validation before being added to the
blockchain.
¥ Block Propagation:
◦ Newly mined blocks are propagated across the network to ensure synchronization.
¥ Gossip Protocol:
◦ Nodes exchange information with their neighbors to update the blockchain state.
Functions:
¥ Ensures real-time synchronization across all nodes.
¥ Prevents double-spending by propagating transaction data instantly.
¥ Enhances decentralization and network security.

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 76 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

4. Consensus Layer (Validation & Agreement Layer)


The consensus layer enforces agreement among blockchain participants regarding valid transactions
and the state of the network.
Key Components:
¥ Consensus Mechanisms:
◦ Determines how transactions are validated and agreed upon.
◦ Examples:

Mechanism Description Example Blockchain


Miners solve complex mathematical puzzles to Bitcoin, Ethereum
Proof of Work (PoW)
validate transactions. (before ETH 2.0)
Validators stake cryptocurrency to participate in
Proof of Stake (PoS) Ethereum 2.0, Cardano
consensus.
Proof of Burn (PoB) Participants "burn" coins to earn mining rights. Slimcoin
Proof of Elapsed Time Uses a trusted execution environment for
Hyperledger Sawtooth
(PoET) validator selection.
Delegated Proof of Users vote for delegates who validate
EOS, Tron
Stake (DPoS) transactions.
¥ Mining DifÞculty Adjustment:
◦ Adjusts the complexity of PoW puzzles to regulate block generation time.
Functions:
¥ Ensures network security and prevents malicious activities.
¥ Enables trustless and decentralized decision-making.
¥ Prevents double-spending by achieving consensus before conÞrming transactions.

5. Smart Contract Layer (Execution Layer)


This layer enables automation through smart contracts, which are self-executing code running on
the blockchain.
Key Components:
¥ Smart Contracts:
◦ Programmable agreements stored on the blockchain.
◦ Example (Solidity code for Ethereum):

contract SimpleContract {
uint storedData;
function set(uint x) public { storedData = x; }
function get() public view returns (uint) { return storedData; }
}

¥ Ethereum Virtual Machine (EVM):


◦ A runtime environment for executing smart contracts.
¥ Decentralized Oracles:
◦ External services that provide real-world data to smart contracts.
Functions:
¥ Enables automation and removes intermediaries.
¥ Ensures transparent and tamper-proof contract execution.
¥ Supports the development of Decentralized Applications (DApps).

6. Application Layer (User Interface Layer)


This is the topmost layer where users interact with blockchain applications.
Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 77 of 78

Downloaded by S. Amirthavarshinii ([email protected])


lOMoARcPSD|47707557

CCS339 - CRYPTOCURRENCY AND BLOCKCHAIN TECHNOLOGIES

Key Components:
¥ DApps (Decentralized Applications):
◦ Applications running on a blockchain instead of centralized servers.
◦ Examples: Uniswap, OpenSea, Aave.
¥ APIs (Application Programming Interfaces):
◦ Allow developers to interact with blockchain networks.
¥ Wallets:
◦ Secure applications for managing cryptocurrencies.
◦ Examples: Metamask, Trust Wallet, Ledger.
Functions:
¥ Provides an intuitive interface for interacting with blockchain.
¥ Supports Þnancial services, identity management, and supply chain applications.
¥ Bridges blockchain technology with real-world use cases.
+----------------------------------------------------------------------+
| Application Layer |
| - Decentralized Applications (DApps) |
| - Digital Wallets (Metamask, Trust Wallet) |
| - APIs and User Interfaces |
+----------------------------------------------------------------------+
| Smart Contract Layer |
| - Smart Contracts (Solidity, Chaincode) |
| - Ethereum Virtual Machine (EVM) |
| - Oracles for External Data |
+----------------------------------------------------------------------+
| Consensus Layer |
| - Proof of Work (PoW), Proof of Stake (PoS), PoET. |
| - Mining, Validator Nodes |
| - Transaction Validation |
+----------------------------------------------------------------------+
| Network Layer |
| - Peer-to-Peer (P2P) Communication |
| - Node Discovery and Transaction Propagation |
| - Block Propagation and Synchronization |
+----------------------------------------------------------------------+
| Data Layer |
| - Blocks and Transactions |
| - Merkle Tree for EfÞcient Data VeriÞcation |
| - Cryptographic Hashing (SHA-256, Keccak-256) |
+----------------------------------------------------------------------+
| Infrastructure Layer |
| - Physical Hardware (Nodes, Servers, Storage) |
| - Network Protocols (TCP/IP, Blockchain Protocols). |
| - Distributed Ledger Technology (DLT) |
+----------------------------------------------------------------------+

*****

Prepared by, Gautham Praveen R / AP- CSBS, SAEC Page 78 of 78

Downloaded by S. Amirthavarshinii ([email protected])

You might also like