0% found this document useful (0 votes)
20 views86 pages

BlockChain Notes

The document provides an overview of blockchain technology, focusing on public ledgers, Bitcoin, smart contracts, and the differences between public and private blockchains. It explains key concepts such as decentralization, immutability, and various consensus mechanisms like Proof of Work and Proof of Stake. Additionally, it discusses the advantages and disadvantages of cryptocurrencies and permissioned blockchains, along with their applications in various sectors.

Uploaded by

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

BlockChain Notes

The document provides an overview of blockchain technology, focusing on public ledgers, Bitcoin, smart contracts, and the differences between public and private blockchains. It explains key concepts such as decentralization, immutability, and various consensus mechanisms like Proof of Work and Proof of Stake. Additionally, it discusses the advantages and disadvantages of cryptocurrencies and permissioned blockchains, along with their applications in various sectors.

Uploaded by

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

Unit 1

Public Ledgers in Blockchain


Definition
A public ledger is a decentralized and openly accessible record-keeping system where all
transactions are recorded in a transparent and immutable manner.

Characteristics of Public Ledgers


1. Decentralized – No central authority controls the ledger; it is distributed across multiple
nodes.
2. Transparency – Anyone can view the transactions, ensuring trust and security.
3. Immutability – Once recorded, transactions cannot be altered or deleted.
4. Security – Uses cryptographic techniques like hashing and digital signatures to protect data.
5. Consensus Mechanisms – Transactions are validated through mechanisms like Proof of
Work (PoW) or Proof of Stake (PoS).

How Public Ledgers Work?


1. Transactions are initiated by users and broadcast to the network.
2. Miners/validators verify transactions using cryptographic rules.
3. Verified transactions are added to a block.
4. The block is linked to the previous block using cryptographic hashes, forming a blockchain.
5. The updated ledger is shared with all nodes, ensuring consistency.

Examples of Public Ledgers


• Bitcoin Blockchain – Maintains a public record of Bitcoin transactions.
• Ethereum – Records transactions related to smart contracts and decentralized applications
(DApps).

Bitcoin and its Role in Blockchain


Introduction to Bitcoin
• Bitcoin (BTC) is the first decentralized cryptocurrency, introduced by Satoshi Nakamoto
in 2008.
• Uses blockchain as a public ledger to record transactions securely.

Key Features of Bitcoin


1. Decentralization – No central bank or government controls Bitcoin.
2. Cryptographic Security – Transactions use SHA-256 hashing for security.
3. Limited Supply – Only 21 million BTC will ever exist.
4. Peer-to-Peer Transactions – Direct transactions without intermediaries.
5. Mining Process – New bitcoins are created through Proof of Work (PoW) mining.
6. Pseudonymity – Users can transact without revealing personal identities.

How Bitcoin Transactions Work?


1. A user initiates a transaction, signing it with a private key.
2. The transaction is broadcasted to the Bitcoin network.
3. Miners validate the transaction by solving cryptographic puzzles (PoW).
4. The validated transaction is added to a new block in the blockchain.
5. Once confirmed, the transaction becomes irreversible and immutable.

Advantages of Bitcoin
✔ Low transaction costs compared to banks.
✔ Borderless payments without currency exchange limitations.
✔ Resistant to fraud due to cryptographic security.
✔ Open-source and transparent for all users.

Disadvantages of Bitcoin
✖ Scalability issues – Limited transactions per second.
✖ Energy-intensive mining due to PoW.
✖ Price volatility – Bitcoin's value fluctuates significantly.
✖ Regulatory concerns – Some governments restrict or ban Bitcoin usage.

Smart Contracts
Definition
A smart contract is a self-executing program stored on a blockchain that runs automatically when
predefined conditions are met.

Characteristics of Smart Contracts


1. Automation – Executes automatically without intermediaries.
2. Immutability – Once deployed, it cannot be altered.
3. Transparency – Code and execution results are visible on the blockchain.
4. Security – Uses cryptographic mechanisms to prevent tampering.
5. Trustless Execution – No need for third-party validation (banks, notaries, etc.).
How Smart Contracts Work?
1. A user deploys the smart contract on the blockchain.
2. It waits for a specific condition (e.g., payment received).
3. Once the condition is met, the contract executes its predefined action (e.g., transfer of
ownership, token issuance).
4. The transaction is recorded on the blockchain, ensuring immutability.

Use Cases of Smart Contracts


✔ Financial Services – Automated payments, insurance claims.
✔ Supply Chain – Tracking goods in real-time.
✔ Voting Systems – Transparent and fraud-proof elections.
✔ Real Estate – Automatic property transfers.

Limitations of Smart Contracts


✖ Code Vulnerabilities – Bugs in the code can lead to exploits.
✖ Legal Recognition – Not fully recognized by all legal systems.
✖ Complexity – Requires expertise to develop and audit.

Block in a Blockchain
Definition
A block is a data structure in a blockchain that stores a set of transactions, a timestamp, and a
reference to the previous block.

Structure of a Block
1. Block Header
• Previous Block Hash – Hash of the previous block to maintain chain integrity.
• Merkle Root – Hash of all transactions in the block.
• Timestamp – Records the time the block was created.
• Nonce – A number used in Proof of Work (PoW) mining.
• Difficulty Target – Determines mining difficulty.
2. Block Body
• Transactions – List of verified transactions.

How Blocks are Added to the Blockchain?


1. New transactions are collected and verified.
2. Miners compete to solve a cryptographic puzzle (in PoW).
3. The first miner to solve the puzzle gets to add the block.
4. The new block is linked to the previous block, forming a chain.
5. The updated ledger is distributed across all nodes.

Importance of Blocks in Blockchain


✔ Ensures immutability – Transactions cannot be altered.
✔ Prevents double spending – Each transaction is recorded only once.
✔ Provides security – Cryptographic hashing protects data.

Transactions in Blockchain
Definition
A transaction is a record of value exchange between two parties stored in a blockchain.

Components of a Blockchain Transaction


1. Sender's Address – Public key of the sender.
2. Recipient's Address – Public key of the receiver.
3. Amount – Value being transferred.
4. Digital Signature – Sender signs the transaction using a private key.
5. Transaction Hash – A unique identifier generated using cryptographic hashing.

Types of Transactions
1. Cryptocurrency Transactions – Transfer of digital currency (e.g., Bitcoin, Ethereum).
2. Smart Contract Execution – Running a smart contract on the blockchain.
3. Token Transactions – Transfer of tokens issued on a blockchain (e.g., ERC-20 tokens).

Transaction Validation Process


1. A user initiates a transaction.
2. The transaction is broadcasted to the network.
3. Miners/validators verify its authenticity.
4. Once validated, it is added to a block.
5. The block is added to the blockchain, confirming the transaction.

Key Features of Blockchain Transactions


✔ Irreversible – Cannot be undone once confirmed.
✔ Secure – Uses cryptographic techniques for protection.
✔ Decentralized – No central authority controls transactions.
Cryptocurrency
Definition
A cryptocurrency is a decentralized digital currency that uses cryptographic techniques to secure
transactions and control the creation of new units.

Characteristics of Cryptocurrency
1. Decentralized – No central authority (government or bank) controls it.
2. Blockchain-Based – Transactions are recorded on a public ledger.
3. Peer-to-Peer (P2P) – Direct transactions without intermediaries.
4. Immutable and Secure – Uses cryptography to prevent fraud.
5. Limited Supply – Most cryptocurrencies have a fixed maximum supply (e.g., Bitcoin: 21
million coins).
6. Anonymity and Transparency – Users can transact without revealing their real identities,
but all transactions are publicly visible.

How Cryptocurrency Transactions Work?


1. A sender initiates a transaction.
2. The transaction is broadcasted to a decentralized network.
3. Miners/validators verify and validate the transaction.
4. Once verified, the transaction is added to a block.
5. The block is added to the blockchain, making the transaction permanent.

Examples of Cryptocurrencies
• Bitcoin (BTC) – The first and most popular cryptocurrency.
• Ethereum (ETH) – Enables smart contracts and DApps.
• Ripple (XRP) – Focuses on fast and low-cost transactions.
• Litecoin (LTC) – Faster transactions compared to Bitcoin.

Advantages of Cryptocurrency
✔ Decentralization – No single entity controls it.
✔ Low Transaction Fees – Compared to traditional banking systems.
✔ Fast Transactions – Can be processed in minutes globally.
✔ Security and Privacy – Uses cryptography for protection.
Disadvantages of Cryptocurrency
✖ Price Volatility – Cryptocurrency values fluctuate widely.
✖ Regulatory Issues – Some governments ban or restrict usage.
✖ Irreversible Transactions – Once sent, transactions cannot be reversed.

Blockchain
Definition
A blockchain is a decentralized, distributed ledger that records transactions securely and immutably
in blocks linked together using cryptography.

Key Features of Blockchain


1. Decentralization – No single authority controls the data.
2. Immutability – Once recorded, data cannot be changed.
3. Security – Uses cryptographic techniques like hashing and digital signatures.
4. Transparency – Transactions are publicly visible.
5. Consensus Mechanisms – Ensures agreement among network participants (e.g., Proof of
Work, Proof of Stake).

Structure of Blockchain
• Blocks – Store transaction data.
• Hash – A unique identifier for each block.
• Previous Block Hash – Ensures connection with the previous block.
• Merkle Root – A tree structure summarizing all transactions in a block.

Types of Blockchain
1. Public Blockchain – Open to everyone (e.g., Bitcoin, Ethereum).
2. Private Blockchain – Restricted access, controlled by an organization.
3. Consortium Blockchain – Controlled by a group of organizations.

Applications of Blockchain
✔ Cryptocurrency Transactions – Secure and decentralized digital payments.
✔ Smart Contracts – Automated contract execution.
✔ Supply Chain Management – Transparency in tracking goods.
✔ Voting Systems – Secure and tamper-proof elections.
Distributed Consensus
Definition
Distributed consensus is a mechanism used in blockchain networks to ensure that all participants
(nodes) agree on the validity of transactions without a central authority.

Why is Consensus Needed?


• To prevent fraud (e.g., double spending).
• To maintain the integrity of the blockchain.
• To ensure all nodes have a consistent and accurate ledger.

Types of Consensus Mechanisms


1. Proof of Work (PoW)
• Used in Bitcoin and Ethereum (before Ethereum 2.0).
• Miners solve complex mathematical puzzles to validate transactions.
• The first miner to solve the puzzle gets rewarded.
• Pros: High security.
• Cons: Energy-intensive and slow.
2. Proof of Stake (PoS)
• Used in Ethereum 2.0, Cardano, and Solana.
• Validators are chosen based on the number of coins they hold and are willing to
"stake" as collateral.
• Pros: Energy-efficient, faster than PoW.
• Cons: Wealthy participants have more power.
3. Delegated Proof of Stake (DPoS)
• Used in EOS, Tron.
• Coin holders vote for delegates who validate transactions.
• Pros: Faster and more efficient than PoS.
• Cons: Centralization risk due to limited validators.
4. Proof of Authority (PoA)
• Used in private blockchains.
• Transactions are validated by selected, trusted nodes.
• Pros: Efficient and fast.
• Cons: Less decentralized.
5. Byzantine Fault Tolerance (BFT) Mechanisms
• Used in Hyperledger Fabric, Ripple, and Stellar.
• Nodes communicate to reach a consensus even if some nodes fail or act maliciously.

Importance of Consensus Mechanisms


✔ Ensures Trust – No central authority is needed.
✔ Prevents Fraud – Stops malicious actors from altering data.
✔ Maintains Network Integrity – Ensures consistency across all nodes.

Public vs Private Blockchain


Blockchain networks can be classified into two main types: Public Blockchain and Private
Blockchain. Below is a detailed comparison between the two:

1. Public Blockchain
Definition:
A public blockchain is an open and permissionless network where anyone can participate, read,
and validate transactions without restrictions.

Characteristics:
✔ Decentralized – No single entity controls the network.
✔ Permissionless – Anyone can join as a node and participate in consensus.
✔ Transparent – All transactions are publicly visible.
✔ Secure – Uses cryptographic techniques to prevent tampering.
✔ Consensus Mechanisms – Uses Proof of Work (PoW) or Proof of Stake (PoS).

Examples of Public Blockchains:


• Bitcoin – The first and most popular cryptocurrency.
• Ethereum – Supports smart contracts and DApps.
• Solana, Cardano, Polkadot – Blockchain platforms for various applications.

Advantages:
✔ Fully Decentralized – No central control.
✔ Highly Secure – Tamper-proof due to consensus mechanisms.
✔ Trustless – No need for intermediaries.
✔ Immutable – Transactions cannot be altered once recorded.
Disadvantages:
✖ Slow Transactions – Due to high network participation and mining time.
✖ High Energy Consumption – Proof of Work (PoW) requires intensive computation.
✖ Scalability Issues – Limited transactions per second (TPS).

2. Private Blockchain
Definition:
A private blockchain is a closed, permissioned network where only authorized participants can
access, validate, and manage transactions.

Characteristics:
✔ Controlled Access – Only selected participants can join the network.
✔ Permissioned – Requires approval to read/write data.
✔ Faster Transactions – Fewer nodes result in quicker validation.
✔ Privacy – Transactions are not publicly visible.
✔ Consensus Mechanisms – Uses Proof of Authority (PoA) or other customized mechanisms.

Examples of Private Blockchains:


• Hyperledger Fabric – Used in enterprise applications.
• Corda (R3) – Designed for financial institutions.
• Quorum (by JPMorgan) – A private blockchain for banking applications.

Advantages:
✔ Faster Transactions – Less congestion due to fewer participants.
✔ Efficient – Uses less energy than public blockchains.
✔ More Control – Suitable for businesses and organizations.
✔ Better Privacy – Sensitive data remains confidential.

Disadvantages:
✖ Centralization Risk – Controlled by an organization, reducing decentralization.
✖ Less Secure – Smaller number of participants makes it vulnerable to attacks.
✖ Lack of Transparency – Not open for public verification.

3. Key Differences: Public vs Private Blockchain


Feature Public Blockchain Private Blockchain
Access Open to everyone Restricted to selected users
Permission Permissionless Permissioned
Decentralization Fully decentralized Partially centralized
Feature Public Blockchain Private Blockchain
Security Highly secure (PoW/PoS) Moderately secure
Transaction Speed Slower due to large network Faster due to fewer participants
Transparency Fully transparent Limited transparency
Consensus Mechanism PoW, PoS PoA, BFT, Custom Mechanisms
Examples Bitcoin, Ethereum Hyperledger, Corda

4. Which One to Choose?


✔ Public Blockchain is Best for:
• Cryptocurrencies (e.g., Bitcoin, Ethereum)
• Decentralized Applications (DApps)
• Open financial systems and transparency-driven use cases
✔ Private Blockchain is Best for:
• Enterprise solutions (e.g., Supply Chain, Banking, Healthcare)
• Confidential business transactions
• Internal record-keeping with restricted access

Permissioned Model of Blockchain


1. Introduction
A permissioned blockchain is a type of blockchain where access to the network is restricted to
authorized participants. Unlike public blockchains, which allow anyone to join, permissioned
blockchains require identity verification and predefined roles.

2. Characteristics of a Permissioned Blockchain


✔ Restricted Access – Only authorized users can participate.
✔ Identity Management – Users must verify their identity to join the network.
✔ Customizable Rules – Organizations can define transaction policies.
✔ Efficient Consensus – Uses consensus mechanisms like Proof of Authority (PoA) or Byzantine
Fault Tolerance (BFT) for faster transactions.
✔ Better Scalability – Due to fewer participants compared to public blockchains.
✔ Enhanced Privacy – Transactions and data are visible only to approved participants.
3. How the Permissioned Model Works?
1. Access Control – New users must obtain permission from network administrators.
2. Role-Based Transactions – Different participants (e.g., admin, validator, user) have
different rights.
3. Consensus Mechanisms – Instead of mining (PoW), permissioned blockchains use PoA,
BFT, or Raft-based consensus for transaction validation.
4. Data Privacy – Only authorized nodes can view or modify the ledger.

4. Examples of Permissioned Blockchains


🔹
🔹 Hyperledger Fabric – Used in enterprises for supply chain, banking, and healthcare.

🔹 Corda (R3) – Designed for financial institutions and cross-border transactions.


Quorum (by JPMorgan) – Focused on private banking and financial services.

5. Advantages of Permissioned Blockchain


✔ High Efficiency – Faster transactions due to fewer nodes.
✔ Stronger Governance – Controlled by a trusted entity.
✔ Lower Energy Consumption – No need for mining like in PoW-based public blockchains.
✔ Better Security and Privacy – Only authorized participants can access sensitive data.

6. Disadvantages of Permissioned Blockchain


✖ Less Decentralized – Control is in the hands of a few participants.
✖ Limited Transparency – Not open to public scrutiny like Bitcoin or Ethereum.
✖ Risk of Centralization – Trust is placed in a governing entity, which could be manipulated.

7. Use Cases of Permissioned Blockchains


🔹
🔹 Banking and Finance – Secure financial transactions between institutions.

🔹
🔹
Supply Chain Management – Track goods and ensure authenticity.
Healthcare – Store and share medical records securely.
Government Services – Identity management and land registry.
Security Aspects of Blockchain
Blockchain technology provides a highly secure and tamper-resistant way of storing and
transferring data. However, like any technology, it has security challenges and risks. Below is an
overview of the key security aspects of blockchain.

1. Core Security Features of Blockchain


a) Cryptographic Security
Blockchain uses cryptography to ensure data integrity, confidentiality, and authenticity.
✔ Hashing (SHA-256, Keccak-256, etc.) – Ensures data immutability and tamper resistance.
✔ Digital Signatures (ECDSA, RSA) – Verifies the authenticity of transactions.
✔ Public and Private Key Encryption – Ensures secure access control.

b) Immutability
Once data is added to the blockchain, it cannot be altered or deleted. This prevents fraud and
unauthorized modifications.

c) Consensus Mechanisms
Blockchain achieves trust without central control through consensus algorithms like:
✔ Proof of Work (PoW) – Prevents Sybil attacks using computational puzzles.
✔ Proof of Stake (PoS) – Reduces risks of 51% attacks by requiring stake commitments.
✔ Byzantine Fault Tolerance (BFT) – Protects against malicious nodes.

d) Decentralization
Since blockchain is distributed across multiple nodes, a single point of failure is avoided.
Hacking one node does not compromise the entire network.

2. Security Threats and Risks in Blockchain


a) 51% Attack
✔ If a single entity controls more than 50% of the network’s mining power, they can manipulate
transactions (double spending, blocking transactions).
✔ More common in smaller blockchains with low computing power.

b) Sybil Attack
✔ A malicious actor creates multiple fake identities to gain control over a network.
✔ Prevented using Proof of Work (PoW), Proof of Stake (PoS), and identity verification
mechanisms.
c) Smart Contract Vulnerabilities
✔ Poorly written smart contracts can be exploited by hackers (e.g., Ethereum’s DAO Hack,
2016).
✔ Solutions: Formal verification, security audits, and best coding practices.

d) Private Key Theft


✔ If a private key is stolen, the attacker gains full control over the wallet.
✔ Prevented using hardware wallets, multi-signature authentication, and secure key storage.

e) Routing Attacks
✔ Attackers intercept blockchain network traffic and alter transactions before they reach miners.
✔ Solutions: Encryption, VPNs, and decentralized relay networks.

f) Eclipse Attack
✔ A node is isolated by an attacker, making it accept false transactions.
✔ Mitigation: Peer diversity and IP randomization.

3. Best Practices for Blockchain Security


✔ Strong Cryptographic Standards – Regularly update hashing and encryption algorithms.
✔ Smart Contract Audits – Conduct security testing and bug bounties.
✔ Cold Storage for Keys – Use offline wallets to store private keys safely.
✔ Multi-Factor Authentication (MFA) – Adds extra security layers for blockchain accounts.
✔ Decentralized Consensus – Avoid centralization risks that could compromise security.

Basic Crypto Primitives in Blockchain


Crypto primitives are fundamental cryptographic techniques used to ensure the security, integrity,
and confidentiality of data in blockchain systems. These primitives provide the foundation for
authentication, encryption, and verification in blockchain transactions.

1. Key Cryptographic Primitives Used in Blockchain


a) Hash Functions
A hash function converts input data into a fixed-length string (hash) that uniquely represents the
input. It is widely used for data integrity in blockchain.
✔ Properties of a Good Hash Function:
• Deterministic – Same input always produces the same output.
• Collision-resistant – No two different inputs should produce the same hash.
• Preimage resistance – Cannot reverse-engineer the original data from the hash.
• Avalanche Effect – A small change in input results in a completely different hash.
✔ Common Hashing Algorithms in Blockchain:
• SHA-256 (Secure Hash Algorithm 256-bit) – Used in Bitcoin.
• Keccak-256 – Used in Ethereum.
• RIPEMD-160 – Used for Bitcoin addresses.
✔ Example of SHA-256 Hashing:
Input: "Blockchain"
Output: 6b1cd349c12296f7b99a4dd79a28a7da9780ea9026f4d2467e9361643a7c4265

Use in Blockchain:
• Securing block data (block hashes).
• Generating digital signatures.
• Creating unique transaction IDs.

b) Symmetric and Asymmetric Cryptography


Cryptography helps secure transactions and communications in blockchain.

i) Symmetric Cryptography (Secret-Key Encryption)


• Same key is used for encryption and decryption.
• Fast but less secure because if the key is compromised, the data is exposed.
• Used in off-chain communication, private blockchains, and data encryption.
✔ Example: AES (Advanced Encryption Standard) – Used in many blockchain applications.

ii) Asymmetric Cryptography (Public-Key Encryption)


• Uses a pair of keys (Public + Private Key).
• The public key is shared, while the private key remains secret.
• More secure and used for authentication and digital signatures.
✔ Example Algorithms:
• RSA (Rivest-Shamir-Adleman)
• ECDSA (Elliptic Curve Digital Signature Algorithm) – Used in Bitcoin and Ethereum.

Use in Blockchain:
• Generating wallet addresses (Public Key).
• Signing transactions (Private Key).
• Verifying digital signatures.

c) Digital Signatures
A digital signature ensures the authenticity and integrity of transactions. It is used to verify that a
message or transaction was created by the rightful owner.
✔ How Digital Signatures Work?
1. A sender signs a message with their private key.
2. The receiver verifies the signature using the sender’s public key.
3. If the verification is successful, the message is confirmed as authentic.
✔ Common Digital Signature Algorithms:
• ECDSA (Elliptic Curve Digital Signature Algorithm) – Used in Bitcoin and Ethereum.
• EdDSA (Edwards-Curve Digital Signature Algorithm) – Used in newer blockchains.
✔ Use in Blockchain:
• Signing blockchain transactions.
• Verifying transaction authenticity without revealing private keys.

d) Merkle Trees
A Merkle Tree is a binary tree structure that organizes transaction hashes to improve efficient
verification in blockchain networks.
✔ How it Works?
1. Transactions are hashed.
2. Pairs of hashes are combined and re-hashed.
3. The process continues until a single root hash (Merkle Root) is created.
✔ Use in Blockchain:
• Efficiently verifying transactions in large datasets.
• Reducing storage and processing power required for verification.
• Ensuring data integrity in blocks.

e) Zero-Knowledge Proofs (ZKP)


A Zero-Knowledge Proof allows one party to prove to another that they know a value without
revealing the actual value.
✔ Common Zero-Knowledge Proof Algorithms:
• ZK-SNARKs (Zero-Knowledge Succinct Non-Interactive Argument of Knowledge) –
Used in Zcash for anonymous transactions.
• ZK-STARKs – A more scalable alternative to SNARKs.
✔ Use in Blockchain:
• Enabling privacy-focused transactions (e.g., Zcash, Tornado Cash).
• Allowing identity verification without exposing personal information.

2. Summary Table of Crypto Primitives in Blockchain


Example
Primitive Purpose Use in Blockchain
Algorithms
SHA-256, Block hashing,
Hash Functions Secure data, ensure integrity
Keccak-256 transaction IDs
Symmetric Encrypt/decrypt data with Off-chain data
AES, DES
Cryptography the same key encryption
Asymmetric Secure communication with Wallet security,
RSA, ECDSA
Cryptography public/private keys authentication
Verify transaction Signing blockchain
Digital Signatures ECDSA, EdDSA
authenticity transactions
Efficient verification of large Organizing transactions
Merkle Trees Merkle Hashing
datasets in blocks
Zero-Knowledge Prove knowledge without ZK-SNARKs, ZK- Private transactions,
Proofs revealing data STARKs identity verification

Cryptographic Hash Functions, Hash Pointers


& Merkle Trees, Digital Signatures, and Public
Key Cryptography
Blockchain technology relies heavily on cryptographic techniques to ensure security, integrity, and
authenticity of transactions. Below is a breakdown of key cryptographic concepts used in
blockchain.

1. Cryptographic Hash Functions


A cryptographic hash function is an algorithm that takes an input (data) and produces a fixed-size
output (hash). It ensures data integrity, authentication, and security in blockchain.
✔ Key Features:
• Deterministic – Same input always produces the same output.
• Collision-resistant – No two different inputs should have the same hash.
• Preimage resistance – Cannot reverse-engineer the original input from the hash.
• Avalanche effect – Small changes in input result in a drastically different hash.
✔ Common Hashing Algorithms in Blockchain:
• SHA-256 (Secure Hash Algorithm 256-bit) – Used in Bitcoin.
• Keccak-256 – Used in Ethereum.
• RIPEMD-160 – Used for Bitcoin addresses.
✔ Example of SHA-256 Hashing:
vbnet
CopyEdit
Input: "Blockchain"
Output: 6b1cd349c12296f7b99a4dd79a28a7da9780ea9026f4d2467e9361643a7c4265

✔ Uses in Blockchain:
• Ensuring data integrity.
• Creating block hashes.
• Generating transaction IDs.

2. Properties of a Cryptographic Hash Function


Property Description
Deterministic Same input always produces the same hash.
Collision-resistant No two different inputs should generate the same hash.
Preimage resistance Cannot derive the original input from its hash.
Second preimage resistance If H(x) = H(y), it must be hard to find another y ≠ x.
Avalanche Effect Small changes in input cause large changes in hash output.
Fast Computation Hashing must be quick and efficient for practical use.

3. Hash Pointer & Merkle Tree


a) Hash Pointer
A hash pointer is a data structure used in blockchains where a pointer to data is stored along with
the hash of that data. This ensures tamper resistance because if the data changes, the hash will
also change.
✔ Use in Blockchain:
• Linking blocks in a blockchain.
• Preventing tampering (if block data is modified, the hash chain breaks).

b) Merkle Tree
A Merkle Tree is a binary tree where:
• Leaves contain transaction hashes.
• Parent nodes contain hashes of their child nodes.
• The root hash (Merkle Root) represents the entire dataset.
✔ How it Works?
1. Each transaction is hashed.
2. Pairs of hashes are combined and hashed again.
3. The process repeats until a single Merkle Root is created.
✔ Use in Blockchain:
• Efficient transaction verification.
• Saves storage space.
• Enables SPV (Simplified Payment Verification) in Bitcoin.

4. Digital Signature
A digital signature is a cryptographic technique used to authenticate transactions and ensure
data integrity in blockchain.
✔ How Digital Signatures Work?
1. Signing: Sender hashes the transaction and encrypts it with their private key.
2. Verification: Receiver decrypts it using the sender’s public key.
3. If valid, the transaction is authentic and untampered.
✔ Algorithms Used:
• ECDSA (Elliptic Curve Digital Signature Algorithm) – Used in Bitcoin & Ethereum.
• EdDSA (Edwards-Curve Digital Signature Algorithm) – Used in newer blockchains.
✔ Uses in Blockchain:
• Signing and verifying transactions.
• Ensuring authenticity without revealing private keys.
5. Public Key Cryptography (Asymmetric Cryptography)
Public Key Cryptography (PKC) uses a pair of keys:
✔ Public Key – Shared with others (like an address).
✔ Private Key – Kept secret and used to sign transactions.
✔ How it Works?
1. A sender encrypts a message with the recipient’s public key.
2. The recipient decrypts it using their private key.
3. The process ensures confidentiality and authentication.
✔ Algorithms Used in Blockchain:
• RSA (Rivest-Shamir-Adleman)
• ECDSA (Elliptic Curve Digital Signature Algorithm)
✔ Uses in Blockchain:
• Securely storing cryptocurrencies in wallets.
• Signing transactions for validation.
• Preventing unauthorized access.

6. Summary Table
Concept Definition Uses in Blockchain
Ensures data integrity, block
Hash Functions Converts data into a fixed-length hash
hashing
Hash Pointer A pointer to data + hash of that data Links blocks in blockchain
A tree of hashes leading to a Merkle
Merkle Tree Efficient transaction verification
Root
Cryptographic method for
Digital Signature Secures blockchain transactions
authentication
Public Key Encryption using a public-private key
Wallet security, authentication
Cryptography pair
Unit 2
Bitcoin and Blockchain
Bitcoin and blockchain are closely related but are not the same. Bitcoin is a cryptocurrency, while
blockchain is the technology that powers it. Let’s break down both concepts.

1. What is Blockchain?
Blockchain is a decentralized, distributed ledger technology (DLT) that securely records
transactions across multiple computers (nodes) in a tamper-resistant manner.
✔ Key Features of Blockchain:
• Decentralized – No central authority controls the data.
• Immutable – Data cannot be changed or deleted once recorded.
• Transparent – Transactions are publicly visible (in public blockchains).
• Secure – Uses cryptography to protect transactions.
• Consensus Mechanisms – Ensures agreement on transaction validity (e.g., Proof of Work).
✔ How Blockchain Works?
1. A user initiates a transaction.
2. The transaction is broadcasted to a network of nodes.
3. Nodes validate the transaction using consensus mechanisms.
4. Valid transactions are grouped into a block.
5. The new block is added to the blockchain cryptographically linked to the previous block.
6. The blockchain is updated across all nodes in the network.
✔ Types of Blockchains:
• Public Blockchain – Open to everyone (e.g., Bitcoin, Ethereum).
• Private Blockchain – Restricted access (used by businesses).
• Consortium Blockchain – Controlled by multiple organizations.

2. What is Bitcoin?
Bitcoin (BTC) is the first decentralized cryptocurrency, introduced in 2009 by an anonymous
entity known as Satoshi Nakamoto. It enables peer-to-peer (P2P) transactions without
intermediaries like banks.
✔ Key Features of Bitcoin:
• Digital Currency – No physical form, purely digital.
• Decentralized – No government or institution controls it.
• Limited Supply – Only 21 million bitcoins will ever exist.
• Uses Blockchain – Transactions are recorded on a public blockchain.
✔ How Bitcoin Transactions Work?
1. A user creates a transaction and signs it using their private key.
2. The transaction is broadcasted to the Bitcoin network.
3. Miners validate the transaction using Proof of Work (PoW).
4. Once validated, the transaction is added to a new block.
5. The new block is added to the Bitcoin blockchain.
✔ Bitcoin’s Proof of Work (PoW) Consensus:
• Miners compete to solve complex mathematical puzzles.
• The first miner to solve it adds the new block to the blockchain.
• The miner is rewarded with newly minted Bitcoin + transaction fees.

3. Difference Between Bitcoin and Blockchain


Feature Bitcoin Blockchain
Definition A digital cryptocurrency A decentralized ledger technology
Purpose Facilitates payments & transactions Stores any type of data securely
Ownership Public (anyone can participate) Can be public, private, or consortium
Use Cases Digital payments, remittances Supply chain, healthcare, finance
Security Uses cryptography & PoW Uses cryptography & consensus algorithms

4. Summary
✔ Blockchain is the underlying technology, and Bitcoin is an application of blockchain.
✔ Bitcoin revolutionized digital payments, eliminating the need for banks.
✔ Blockchain is not limited to cryptocurrencies – it is used in finance, supply chain, healthcare,
and more.

Creation of Coins, Payments, and Double


Spending in Bitcoin
Bitcoin operates on a decentralized network where new coins are created, payments are made,
and the system prevents double spending using cryptographic techniques and consensus
mechanisms.
1. Creation of Coins (Bitcoin Mining)
Bitcoin follows a process called mining to create new coins. Mining is a computational process
that secures transactions and adds them to the blockchain while generating new bitcoins as a reward
for miners.

✔ How New Bitcoins Are Created?


1. Miners validate transactions and package them into a block.
2. They compete to solve a complex mathematical puzzle using Proof of Work (PoW).
3. The first miner to solve the puzzle broadcasts the block to the network.
4. If the block is valid, it is added to the blockchain, and the miner receives a block reward
(newly minted bitcoins + transaction fees).

✔ Bitcoin Halving (Controlled Supply)


• Bitcoin has a fixed supply of 21 million coins.
• The block reward halves every 4 years (~ every 210,000 blocks) to control inflation.
• Initially, the reward was 50 BTC per block; after multiple halvings, it is now 6.25 BTC (as
of 2024).

✔ Current Bitcoin Supply Distribution


• Total supply: 21 million BTC (fixed).
• Already mined: ~19.6 million BTC.
• Remaining supply: ~1.4 million BTC to be mined by 2140.

✔ Who Can Mine Bitcoin?


• Any individual or group with powerful hardware (ASIC miners) can mine.
• Mining pools combine computing power to increase their chances of winning rewards.

2. Bitcoin Payments
Bitcoin payments allow users to send and receive BTC without intermediaries. Transactions occur
on the blockchain and are secured using cryptography.

✔ How Bitcoin Payments Work?


1. Sender creates a transaction using their Bitcoin wallet.
2. The transaction contains:
• Sender’s Bitcoin address (public key).
• Recipient’s Bitcoin address.
• Amount of BTC to send.
• Digital signature (signed with sender’s private key for authenticity).
3. The transaction is broadcasted to the Bitcoin network.
4. Miners validate the transaction and include it in a block.
5. Once confirmed, the recipient receives the BTC.

✔ Transaction Fees in Bitcoin Payments


• Users pay a small fee for transactions.
• Fees depend on network congestion and transaction size.
• Higher fees = Faster confirmation, as miners prioritize high-fee transactions.

✔ Bitcoin Payment Speed


• A new block is mined every ~10 minutes.
• A transaction is considered fully confirmed after 6 blocks (~60 minutes).
• Lightning Network improves speed by enabling instant BTC transactions off-chain.

3. Double Spending Problem in Bitcoin


Double spending occurs when someone tries to spend the same Bitcoin twice. Since Bitcoin is
digital, unlike physical cash, a malicious user could attempt to send the same BTC to multiple
people.

✔ How Bitcoin Prevents Double Spending?


1. Public Ledger (Blockchain): Every transaction is recorded in a decentralized, transparent
ledger. Once a transaction is confirmed, it cannot be reversed.
2. Consensus Mechanism (Proof of Work): Transactions are validated by miners, ensuring
that only one version of the transaction is accepted.
3. Confirmation Requirement: Transactions are only considered valid after multiple block
confirmations (recommended: 6 confirmations).
4. Unspent Transaction Output (UTXO) Model: Each BTC comes from previous
transactions, preventing reuse of the same coins.

✔ Types of Double-Spending Attacks


• Race Attack: Attacker sends two transactions with the same BTC to different recipients
before confirmation.
• Finney Attack: Miner pre-mines a transaction and spends the same BTC elsewhere before
broadcasting the block.
• 51% Attack: If a single entity controls more than 50% of mining power, they can rewrite
transactions and double spend.

✔ Why Bitcoin is Secure from Double Spending?


• Decentralization: Thousands of nodes verify transactions, making manipulation difficult.
• Mining Difficulty: Requires immense computing power to alter blockchain history.
• Confirmation Time: The more confirmations a transaction has, the harder it is to reverse.

4. Summary Table
Concept Description
Creation of Coins New BTC is mined using Proof of Work (PoW)
Bitcoin Payments BTC transactions occur via wallets and blockchain
Transaction Fees Small fees paid to miners for faster processing
Double Spending Attempt to spend the same BTC twice
Prevention of Double Spending Blockchain, PoW, confirmations, UTXO model

Bitcoin Scripts and Bitcoin P2P Network


Bitcoin uses a script-based system for transaction verification and a peer-to-peer (P2P) network
for decentralized transaction broadcasting. Let's break them down in detail.

1. Bitcoin Scripts
✔ What is Bitcoin Script?
Bitcoin uses a stack-based scripting language called Bitcoin Script to define transaction rules. It
is a simple, non-Turing complete language, meaning it cannot perform complex loops (preventing
infinite execution).
✔ Purpose of Bitcoin Script:
• Enables custom conditions for spending BTC.
• Ensures security by defining rules for valid transactions.
• Used in multi-signature transactions, time locks, and smart contracts.

✔ Bitcoin Script Execution (Stack-Based Processing)


1. Bitcoin Script runs on a stack-based model (Last-In, First-Out).
2. Operations (opcodes) are executed in sequence.
3. If the final stack evaluates to "True", the transaction is valid.

✔ Basic Bitcoin Script Example (Pay-to-Public-Key-Hash - P2PKH)


A common transaction type in Bitcoin is Pay-to-Public-Key-Hash (P2PKH), where BTC is sent to
a specific address.

Locking Script (ScriptPubKey) - Set by Sender


mathematica
CopyEdit
OP_DUP OP_HASH160 <Recipient's Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

• OP_DUP → Duplicates the top item in the stack.


• OP_HASH160 → Hashes the public key using SHA-256 + RIPEMD-160.
• OP_EQUALVERIFY → Ensures hashes match (verifies ownership).
• OP_CHECKSIG → Checks the digital signature for validity.

Unlocking Script (ScriptSig) - Provided by Receiver


php-template
CopyEdit
<Signature> <Public Key>

• The receiver provides their signature and public key to unlock BTC.
• The script executes, and if it evaluates to True, BTC is spent.

✔ Advanced Bitcoin Scripts


Script Type Purpose
P2PKH (Pay-to-Public-Key-Hash) Sends BTC to a public key hash (most common)
P2SH (Pay-to-Script-Hash) Allows complex scripts, like multi-signature
Multi-Sig Transactions Requires multiple signatures to spend BTC
Time-Locked Transactions Restricts spending BTC until a future time

2. Bitcoin Peer-to-Peer (P2P) Network


Bitcoin operates on a peer-to-peer (P2P) network, meaning all nodes are equal, and there is no
central authority.

✔ How the Bitcoin P2P Network Works?


1. Nodes (computers) communicate using the Bitcoin protocol over the Internet.
2. When a user broadcasts a transaction, it spreads across the network.
3. Miners verify transactions, add them to blocks, and broadcast new blocks.
4. Other nodes receive the block, validate it, and add it to their local blockchain.

✔ Types of Nodes in the Bitcoin Network


Node Type Function
Stores the entire Bitcoin blockchain and validates transactions
Full Node
independently.
Mining Node Competes to solve Proof of Work (PoW) and add new blocks.
Lightweight Node (SPV
Does not store full blockchain, relies on full nodes for verification.
Node)
Listening Node (Public
Always online, helps relay transactions and blocks.
Node)

✔ Bitcoin Message Types in P2P Network


Bitcoin nodes communicate using messages in the P2P network.

Message Type Purpose


tx Broadcasts a new transaction
block Broadcasts a newly mined block
inv Announces known transactions or blocks
getdata Requests specific data from peers
verack Acknowledges version compatibility

3. Summary Table
Concept Description
Bitcoin Script Stack-based language for transaction validation
P2PKH Standard Bitcoin payment script
P2SH Allows more complex spending conditions
Bitcoin P2P Network Decentralized network for transaction and block propagation
Full Nodes Validate and store the entire blockchain
Miners Solve PoW puzzles and add new blocks
Lightweight nodes that verify transactions without storing the full
SPV Nodes
blockchain

Transaction in Bitcoin Network, Block Mining,


Block Propagation, and Block Relay
Bitcoin transactions are processed in a decentralized manner using a peer-to-peer (P2P)
network. These transactions are grouped into blocks by miners, who validate them and propagate
new blocks across the network. Let’s explore these concepts in detail.
1. Transactions in the Bitcoin Network
A Bitcoin transaction is a transfer of value (BTC) between addresses, recorded on the blockchain.

✔ Structure of a Bitcoin Transaction


A Bitcoin transaction consists of:
1. Transaction Inputs – Source of BTC (previous transactions’ outputs).
2. Transaction Outputs – Destination addresses receiving BTC.
3. Transaction Fees – Reward for miners to include the transaction in a block.
4. Signature (Digital Signature) – Verifies ownership and prevents tampering.

✔ How a Bitcoin Transaction Works?


1. Sender creates a transaction in their wallet and signs it using their private key.
2. The transaction is broadcasted to the Bitcoin network.
3. Full nodes validate the transaction by checking:
• The sender has sufficient BTC (checking Unspent Transaction Outputs - UTXO).
• The signature is correct.
4. If valid, the transaction enters the mempool (waiting area for unconfirmed transactions).
5. Miners pick transactions from the mempool, include them in a block, and attempt to mine
it.
6. Once mined, the transaction is confirmed and added to the blockchain.
7. The receiver sees the BTC in their wallet after confirmations.

2. Block Mining in Bitcoin


Bitcoin mining is the process of validating transactions, creating new blocks, and adding them
to the blockchain using Proof of Work (PoW).

✔ How Block Mining Works?


1. Miners collect transactions from the mempool.
2. They assemble transactions into a new block.
3. The block header contains:
• Previous block hash (linking blocks in the chain).
• Merkle root (hash of all transactions).
• Nonce (random number miners adjust to find a valid block).
• Timestamp.
4. Miners perform Proof of Work (PoW) by repeatedly hashing the block header until they
find a hash below the target difficulty.
5. Once a miner finds a valid hash, they broadcast the new block to the network.
6. Other nodes verify the block and add it to their blockchain.

✔ Bitcoin Block Structure


Field Description
Block Header Metadata about the block
Previous Block Hash Links the block to the previous one
Merkle Root Hash of all transactions in the block
Nonce Number adjusted for PoW
Timestamp Time when block was created
Transactions List of included transactions

3. Block Propagation in Bitcoin


Once a miner successfully mines a block, it must be propagated across the network so that all
nodes agree on the updated blockchain.

✔ Steps in Block Propagation


1. Miner finds a valid block and broadcasts it to neighboring nodes.
2. The receiving nodes:
• Validate the block (checking Proof of Work, transactions, and previous block hash).
• If valid, they store the block and propagate it further.
3. The process continues until the entire Bitcoin network receives the new block.
4. If multiple miners find blocks simultaneously, a temporary fork occurs.
5. The network resolves the fork by following the longest valid chain rule (chain with the
most accumulated PoW).

4. Block Relay in Bitcoin


Block relay is the efficient transmission of new blocks across the Bitcoin network.

✔ Challenges in Block Relay


• Large block size can slow down propagation.
• Network latency may delay block distribution.
• Duplicate data transmission increases bandwidth usage.

✔ Methods to Improve Block Relay


Method Description
Standard Block Propagation Nodes relay full blocks to their peers.
Only transaction hashes are sent; missing transactions are
Compact Blocks
requested separately.
Fast Relay Networks (e.g.,
Optimized relay networks reduce latency.
FIBRE)
Graphene Protocol Uses advanced compression to reduce data transmission size.

5. Summary Table
Concept Description
Bitcoin Transaction Transfer of BTC from sender to receiver, recorded on the blockchain
Mempool Temporary storage for unconfirmed transactions
Mining Process of validating transactions and creating new blocks using PoW
Block Propagation Process of distributing new blocks across the Bitcoin network
Block Relay Optimized methods for faster and more efficient block distribution

Working with Consensus in Bitcoin:


Distributed Consensus in Open Environments
& Consensus in Bitcoin Network
1. What is Consensus in Bitcoin?
Bitcoin operates in a decentralized network, meaning there is no central authority to validate
transactions. Instead, all nodes must agree on a single version of the blockchain. This agreement
process is called distributed consensus.
Bitcoin achieves consensus through Proof of Work (PoW), ensuring that all participants follow the
same rules and preventing fraud like double spending.

2. Distributed Consensus in Open Environments


✔ What is Distributed Consensus?
Distributed consensus is the process by which nodes in a decentralized network agree on a shared
state (e.g., the current valid blockchain). This is challenging in open environments (like Bitcoin),
where:
• Nodes are anonymous.
• Some participants may act maliciously.
• Network delays can cause temporary inconsistencies.

✔ Challenges in Open-Environment Consensus


Challenge Description
Byzantine Fault Tolerance Some nodes may be faulty or malicious but the system must still
(BFT) work.
Sybil Attacks Attackers may create multiple fake identities to manipulate voting.
Transactions and blocks take time to propagate, leading to
Network Latency
temporary forks.
Scalability More nodes make consensus harder to achieve quickly.
Bitcoin overcomes these issues using Proof of Work (PoW).

3. Consensus in the Bitcoin Network


✔ How Bitcoin Achieves Consensus?
Bitcoin follows Nakamoto Consensus, which is based on:
1. Proof of Work (PoW) – Miners solve a cryptographic puzzle to add blocks.
2. Longest Chain Rule – The chain with the most PoW is considered valid.
3. Block Validation – Nodes verify transactions and blocks before accepting them.

✔ Step-by-Step Bitcoin Consensus Process


1. New transactions are broadcast to all nodes.
2. Transactions enter the mempool (waiting area).
3. Miners pick transactions and compete to solve a PoW puzzle.
4. The first miner to find a valid block broadcasts it to the network.
5. Other nodes verify the block and add it to their blockchain.
6. If multiple miners find blocks at the same time, a temporary fork occurs.
7. The network eventually resolves the fork by following the longest chain.

✔ Proof of Work (PoW) Explained


• Miners must find a hash (SHA-256) below a target difficulty.
• This process is computationally expensive but easy to verify.
• The difficulty adjusts every 2016 blocks (~2 weeks) to maintain a 10-minute block time.
✔ Security Benefits of PoW:
• Prevents Sybil attacks (since mining requires real computational work).
• Makes tampering nearly impossible, as altering a block would require re-mining all
subsequent blocks.
• Provides economic security, as attacking Bitcoin would require enormous energy and cost.

✔ Forks in Bitcoin: Handling Temporary Disagreements


A fork happens when two miners produce valid blocks at the same time.

Types of Forks:
Fork Type Description
Temporary Happens naturally when two blocks are found simultaneously. The network
Fork eventually resolves it by following the longest chain.
A backwards-compatible update (e.g., SegWit). Older nodes can still validate
Soft Fork
transactions.
A non-backward-compatible upgrade that creates a separate chain (e.g., Bitcoin
Hard Fork
Cash).

✔ Summary Table
Concept Description
Distributed Consensus Agreement among decentralized nodes on a single valid blockchain.
Challenges Byzantine faults, Sybil attacks, network latency, scalability.
Nakamoto Consensus Bitcoin's consensus mechanism using Proof of Work (PoW).
Proof of Work (PoW) Miners solve cryptographic puzzles to validate blocks.
Longest Chain Rule The chain with the most PoW is considered the valid blockchain.
Temporary forks resolve naturally; soft and hard forks change the
Forks
protocol.

Proof of Work (PoW) – Overview, Hashcash


PoW, Bitcoin PoW, Attacks on PoW &
Monopoly Problem
Proof of Work (PoW) is the foundational consensus mechanism of Bitcoin. It ensures network
security, prevents spam, and maintains decentralization by requiring participants (miners) to solve
computational puzzles before adding new blocks to the blockchain.
1. Introduction to Proof of Work (PoW)
✔ What is Proof of Work?
PoW is a cryptographic mechanism where nodes (miners) solve a computationally difficult
problem to propose new blocks. The first miner to solve the problem gets to add the block and
receives a reward.

✔ Key Properties of PoW:


1. Hard to Compute – Requires significant computing power.
2. Easy to Verify – Other nodes can quickly validate the solution.
3. Prevents Spam & Attacks – Making changes requires enormous energy.

✔ How PoW Works in Blockchain?


1. Miners collect transactions and form a block.
2. They must find a valid hash by adjusting a number called nonce.
3. The hash must be below a target difficulty (defined by the network).
4. The first miner to find a valid hash broadcasts the block.
5. Other nodes verify the block and add it to their chain.
6. The miner receives a block reward + transaction fees.

2. Hashcash PoW – The Basis of Bitcoin PoW


Bitcoin’s PoW is inspired by Hashcash, a system developed by Adam Back in 1997 to prevent
email spam and denial-of-service (DoS) attacks.

✔ How Hashcash PoW Works?


• Senders must compute a special hash before sending an email.
• The recipient’s server verifies the hash to ensure the sender expended effort.
• This prevents spam, as mass-sending emails becomes computationally expensive.

✔ Hashcash PoW Algorithm:


1. Choose a message M (e.g., an email header).
2. Add a random nonce to M.
3. Compute SHA-256 hash of (M + nonce).
4. If the hash has a certain number of leading zeros, it is valid.
5. If not, increment the nonce and try again.
Bitcoin adopted this hash-based PoW to secure its blockchain.
3. Bitcoin PoW – Nakamoto Consensus
Bitcoin uses SHA-256-based Proof of Work, ensuring decentralization and security.

✔ Bitcoin PoW Steps:


1. Miners collect transactions and form a block header.
2. They modify the nonce and hash the block header using SHA-256.
3. If the hash is below the target difficulty, the block is valid.
4. The block is broadcasted and verified by other nodes.
5. The miner receives a reward (BTC) and transaction fees.

✔ Difficulty Adjustment
• The network adjusts the difficulty every 2016 blocks (~2 weeks).
• If blocks are mined too fast, difficulty increases.
• If blocks take too long, difficulty decreases.


✔ Bitcoin PoW Advantages:



Decentralization – No single entity controls mining.
Security – Changing the blockchain requires enormous energy.
Prevents Double Spending – Attackers need to redo all PoW.

4. Attacks on Proof of Work (PoW)


Despite its security, PoW has vulnerabilities.

✔ Common Attacks on PoW:


Attack Description Impact
If a miner controls >50% of hash power, Can double-spend BTC & censor
51% Attack
they can rewrite transactions. transactions.
Selfish Miners hide blocks to gain an unfair Slows down honest miners, causing
Mining advantage. inefficiencies.
Sybil An attacker creates multiple fake nodes to Increases network congestion, but PoW
Attack manipulate the network. makes Sybil attacks costly.
Eclipse An attacker isolates a node by controlling Delays block updates and causes financial
Attack all its peer connections. losses.
Bribery A malicious entity pays miners to work
Weakens blockchain security.
Attack against the network.

✔ Why 51% Attacks Are Rare?


• Expensive – Controlling 51% of Bitcoin’s hash power requires billions of dollars.
• No Incentive – Attacking Bitcoin would crash its value, making it unprofitable.

5. Monopoly Problem in PoW


✔ What is the Monopoly Problem?
• Over time, big mining pools dominate PoW, leading to centralization.
• Wealthy miners buy better hardware (ASICs), making solo mining impossible.
• High electricity costs prevent small miners from competing.

🚨
✔ Consequences of Mining Centralization:

🚨
🚨
Less Decentralization – A few mining pools control most of the hash rate.
Security Risk – If one pool gains 51% hash power, it can manipulate transactions.
Higher Entry Barrier – Requires expensive hardware (ASICs), shutting out small miners.

✔ Solutions to the Monopoly Problem:


Solution Description
Mining Pools
Encouraging more independent mining pools.
Decentralization
Stronger Governance Implementing network rules to prevent mining dominance.
Using memory-hard PoW (e.g., Ethereum’s Ethash) to reduce ASIC
Alternative PoW Algorithms
dominance.
Moving to PoS (Proof of
Some blockchains switch to PoS to avoid mining centralization.
Stake)

6. Summary Table
Concept Description
Proof of Work
Miners solve cryptographic puzzles to add blocks.
(PoW)
Hashcash PoW Precursor to Bitcoin PoW, used to prevent email spam.
Bitcoin PoW Uses SHA-256 hashing to secure the network.
51% Attack Occurs if one miner controls most of the hash power.
Selfish Mining Miners hide blocks to gain more rewards.
Monopoly Problem Large mining pools centralize Bitcoin mining.
Decentralized mining pools, alternative PoW algorithms, and governance
Solutions
mechanisms.
Consensus Mechanisms: Proof of Stake (PoS),
Proof of Burn (PoB), and Proof of Elapsed
Time (PoET)
In blockchain networks, consensus mechanisms ensure agreement among participants. Apart from
Proof of Work (PoW), alternative mechanisms like Proof of Stake (PoS), Proof of Burn (PoB),
and Proof of Elapsed Time (PoET) aim to provide efficiency, security, and decentralization.

1. Proof of Stake (PoS)


✔ What is Proof of Stake (PoS)?
PoS replaces computational work with financial commitment. Instead of solving complex
puzzles (like in PoW), validators are chosen based on the number of coins they "stake" in the
network.

✔ How PoS Works?


1. Validators stake their coins to participate in block validation.
2. The network randomly selects a validator based on the amount staked.
3. The chosen validator proposes the next block.
4. Other validators confirm the block’s validity.
5. The validator receives transaction fees as a reward (instead of mining rewards).


✔ Advantages of PoS:



Energy Efficient – No need for expensive mining hardware.
Faster Transactions – Blocks are validated quicker than PoW.
Less Centralization – Does not rely on mining pools.

🚨
✔ Disadvantages of PoS:

🚨 Wealth Concentration – Rich participants control more stakes and earn more rewards.
Nothing-at-Stake Problem – Validators might support multiple chains during forks without
penalty.

✔ Example Blockchains Using PoS:


• Ethereum 2.0
• Cardano (ADA)
• Polkadot (DOT)
2. Proof of Burn (PoB)
✔ What is Proof of Burn (PoB)?
PoB allows participants to “burn” (destroy) coins in exchange for mining rights. The more
coins a user burns, the higher their chances of being chosen to validate the next block.

✔ How PoB Works?


1. Participants send coins to a verifiable unspendable address (black hole wallet).
2. The more coins a user burns, the higher their probability of mining a block.
3. Over time, burned coins act as a long-term investment, increasing mining power.
4. The network selects the next validator based on the amount of burned coins.


✔ Advantages of PoB:



Fair Mining Process – Anyone can participate by burning coins.
Energy Efficient – No need for mining hardware like in PoW.
Prevents Hoarding – Burning coins removes them from circulation, reducing supply.

🚨
✔ Disadvantages of PoB:

🚨 Waste of Resources – Burning valuable coins reduces liquidity in the market.


Wealth-Based System – Users with more money can burn more coins, gaining control.

✔ Example Blockchains Using PoB:


• Slimcoin (SLM) – Uses PoB for fair mining distribution.
• Some experimental altcoins use PoB for token distribution.

3. Proof of Elapsed Time (PoET)


✔ What is Proof of Elapsed Time (PoET)?
PoET is a leader-election algorithm designed by Intel, primarily used in permissioned
blockchains. Instead of miners competing through PoW or staking tokens like in PoS, PoET
randomly assigns block validation rights based on a waiting period.

✔ How PoET Works?


1. Each participant requests a random wait time from a trusted execution environment
(TEE) (like Intel SGX).
2. The node with the shortest wait time wins the right to validate the next block.
3. The winner broadcasts the block to the network.
4. Other nodes verify the block and continue the process.

✔ Advantages of PoET:



Highly Energy Efficient – No expensive mining hardware is needed.
Equal Opportunity – Randomized selection prevents wealth-based monopoly.
Fast Block Validation – Ideal for enterprise blockchains (e.g., Hyperledger).

🚨
✔ Disadvantages of PoET:

🚨 Trusted Hardware Dependency – Relies on Intel SGX, reducing decentralization.


Less Secure for Open Networks – Best suited for private blockchains, not permissionless
ones.

✔ Example Blockchains Using PoET:


• Hyperledger Sawtooth (Enterprise blockchain).

4. Summary Table: Comparison of PoS, PoB, and PoET


Consensus Energy
Selection Method Security Risks Used in
Mechanism Efficiency
Proof of Stake
(PoS)
Based on staked
coins
✅ High
Wealth concentration,
Nothing-at-Stake
problem
Ethereum 2.0,
Cardano

Proof of Burn
(PoB)
Based on burned
coins
✅ High
Coin wastage, Wealth-
based mining
Slimcoin,
Experimental
Blockchains
Proof of Elapsed
Time (PoET)
Randomized wait
time (via Intel
SGX)
✅ High
Requires trusted
hardware
Hyperledger
Sawtooth

Bitcoin Mining: Life of a Miner, Mining


Difficulty, and Mining Pools
Bitcoin mining is a crucial process in the Bitcoin network, ensuring security, decentralization, and
new BTC issuance. Miners compete to solve complex puzzles using computational power, validate
transactions, and earn rewards.

1. The Life of a Bitcoin Miner


A Bitcoin miner is a participant in the network who uses specialized hardware to validate
transactions and add new blocks to the blockchain.

🔹
✔ Steps in a Miner’s Daily Life:
Step 1: Setting Up Mining Equipment
• Miners use ASIC (Application-Specific Integrated Circuit) machines designed for
Bitcoin mining.

🔹
• They install mining software (e.g., CGMiner, BFGMiner) and connect to the network.
Step 2: Selecting a Mining Pool or Solo Mining
• Miners can mine solo or join a mining pool for consistent rewards.
• In solo mining, rewards are high but infrequent.

🔹
• In a pool, rewards are split among miners based on their contribution.
Step 3: Verifying Transactions & Creating a Block
• Miners collect pending transactions from the mempool.
• They verify the validity of transactions (checking signatures, preventing double-spending).

🔹
• Transactions are assembled into a candidate block.
Step 4: Solving the Proof of Work (PoW) Puzzle
• The miner must find a valid hash (SHA-256) by modifying a nonce.
• The hash must be below a target difficulty value.

🔹
• If successful, the miner broadcasts the block to the network.
Step 5: Earning Bitcoin Rewards

✅✅
• If the block is accepted, the miner receives:
Block reward (currently 6.25 BTC, halves every 4 years).

🔹
Transaction fees from all transactions in the block.
Step 6: Continuous Mining
• If unsuccessful, the miner keeps modifying the nonce and tries again.
• Miners constantly optimize hardware, manage electricity costs, and upgrade equipment.

2. Mining Difficulty
Bitcoin adjusts its mining difficulty to ensure a new block is mined approximately every 10
minutes.

🔹
✔ What is Mining Difficulty?

🔹
🔹
Mining difficulty is a parameter that determines how hard it is to find a valid hash.
The difficulty level adjusts every 2016 blocks (~2 weeks).

🔹 If blocks are mined too quickly, the difficulty increases.


If blocks take too long, the difficulty decreases.

✔ Why is Difficulty Adjustment Important?



Ensures Network Stability – Blocks are mined at a consistent rate.
Prevents Sudden Changes – If more miners join, difficulty rises to maintain balance.
Defends Against Attacks – High difficulty makes it expensive to launch attacks.

✔ Formula for Difficulty Adjustment


New Difficulty=Old Difficulty×Actual Time for 2016 BlocksExpected Time (20160 min)\text{New
Difficulty} = \text{Old Difficulty} \times \frac{\text{Actual Time for 2016 Blocks}}
{\text{Expected Time (20160 min)}}
New Difficulty=Old Difficulty×Expected Time (20160 min)Actual Time for 2016 Blocks
• If mining is too fast, difficulty increases.
• If mining is too slow, difficulty decreases.

✔ Example Difficulty Adjustments:


Date Difficulty Level Change (%) Reason
2021-05-01 25T +15% More miners joined
2021-07-01 19T -24% China banned mining (less miners)
2022-01-01 22T +10% Network stabilized

3. Mining Pools
✔ What is a Mining Pool?
A mining pool is a group of miners who combine their computational power to increase the chances
of mining a block. Rewards are distributed based on contribution.

🚀
✔ Why Use a Mining Pool?
Consistent Earnings – Instead of waiting months for a block reward, miners earn steady

🚀
payouts.

🚀 Lower Variance – Even with low hash power, miners can earn small portions of BTC.
Better Resource Utilization – Pooling resources increases mining efficiency.

✔ How Mining Pools Work?


1. Miners connect their machines to a mining pool.
2. The pool assigns work units (small parts of the PoW problem).
3. Each miner solves their work unit and submits results to the pool.
4. If a miner in the pool finds a valid block, the pool receives the reward.
5. The reward is shared among miners based on their contributed work (hashrate).
✔ Reward Distribution Models in Mining Pools
Method Description
Pay-per-Share (PPS) Miners receive a fixed payout per valid share submitted.
Miners are paid based on the proportion of shares they submit in a
Proportional (PROP)
round.
Pay-per-Last N Shares Rewards are distributed only to miners who worked on the latest
(PPLNS) N shares.

✔ Example Mining Pools:


• F2Pool – One of the largest Bitcoin mining pools.
• AntPool – Operated by Bitmain, a leading mining hardware company.
• Slush Pool – The first-ever Bitcoin mining pool.

4. Summary Table
Concept Description
Uses specialized hardware (ASICs) to validate transactions and mine
Bitcoin Miner
blocks.
Mining Difficulty Adjusts every 2016 blocks to maintain 10-minute block times.
Mining Pool A group of miners who combine computing power to share rewards.
Solo Mining vs. Pool Solo mining = high rewards but rare, Pool mining = smaller, steady
Mining payouts.
Unit 3
Permissioned Blockchain
A permissioned blockchain is a type of blockchain where access to the network is restricted to
authorized participants. Unlike public blockchains (e.g., Bitcoin, Ethereum), where anyone can
join and validate transactions, permissioned blockchains require identity verification and access
control.

1. What is a Permissioned Blockchain?


🔹 A controlled-access blockchain where only pre-approved participants can read, write, or

🔹
validate transactions.

🔹 Uses identity management to ensure trust and compliance within the network.
Often used by enterprises, governments, and financial institutions.

2. Key Features of Permissioned Blockchains


✔ Restricted Access – Only authorized users can join the network.
✔ Efficient and Scalable – Fewer nodes result in faster transactions.
✔ Identity-Based Membership – Participants must verify their real-world identity.
✔ Governance Control – A central authority or consortium oversees operations.
✔ Lower Energy Consumption – No need for Proof of Work (PoW) like in Bitcoin.

3. Permissioned vs. Public Blockchains


Feature Permissioned Blockchain Public Blockchain
Restricted (Only authorized
Access Control Open to anyone
participants)
PoA, PBFT, PoET, or customized
Consensus PoW, PoS
mechanisms
Speed Faster (Less congestion) Slower (More nodes competing)
Energy Less efficient (Mining requires high
More efficient (No mining required)
Efficiency power)
Controlled by an organization or Fully decentralized (Community-
Governance
consortium driven)
Use Cases Enterprises, banks, supply chain Cryptocurrencies, decentralized apps
4. How Permissioned Blockchains Work?

🔹
✔ Step 1: User Authentication

🔹 Users must verify their identity (e.g., KYC verification).


Access is granted by a central authority or consortium.

🔹
✔ Step 2: Consensus Mechanism



Instead of Proof of Work (PoW), permissioned blockchains use:
Proof of Authority (PoA) – Blocks are validated by trusted nodes.

✅ PBFT (Practical Byzantine Fault Tolerance) – Ensures consensus in private networks.


Proof of Elapsed Time (PoET) – Random selection of block validators.

🔹
✔ Step 3: Transaction Validation & Block Addition

🔹 Only authorized nodes can validate transactions.


Once verified, transactions are added to the blockchain.

🔹
✔ Step 4: Network Governance & Updates

🔹 Governance rules are set by organizations or consortiums.


Regular updates and compliance checks ensure security.

5. Examples of Permissioned Blockchains


Blockchain Description Industry Use Case
Hyperledger Fabric Modular blockchain framework Supply chain, banking
Corda Financial blockchain by R3 Banking, trade finance
Quorum Ethereum-based private blockchain Finance, enterprise transactions
Ripple (XRP Ledger) Optimized for cross-border payments Banking, remittances

6. Use Cases of Permissioned Blockchain


🔹
🔹 Banking & Finance – Faster and secure cross-border payments.

🔹
🔹
Supply Chain Management – Transparency in tracking goods.
Healthcare – Secured patient data sharing among hospitals.
Government Services – Secure identity management and voting systems.

7. Advantages & Disadvantages


✔ Advantages

✅ Faster Transactions – Less congestion due to fewer participants.


Better Privacy – Data is shared only among authorized parties.

✅ Regulatory Compliance – Supports KYC and AML regulations.


Low Energy Consumption – No mining required.

🚨
🚨
Disadvantages
Centralized Control – Not fully decentralized.

🚨 Limited Transparency – Not open to public audit.


Risk of Manipulation – If governance is weak, rules can be unfairly changed.

Permissioned Blockchain Model & Use Cases


A permissioned blockchain is a blockchain network where only authorized participants can read,
write, and validate transactions. This model ensures privacy, security, and regulatory compliance,
making it suitable for enterprises, governments, and financial institutions.

1. What is a Permissioned Model in Blockchain?


🔹 Unlike public blockchains (e.g., Bitcoin, Ethereum), where anyone can join, permissioned

🔹
blockchains restrict access to verified participants.
It operates under centralized or consortium governance, ensuring control over network

🔹
participants.
Uses alternative consensus mechanisms instead of energy-intensive Proof of Work (PoW).


✔ Characteristics of the Permissioned Model



Controlled Access – Participants must be verified and authorized.
Identity Management – Users require KYC (Know Your Customer) or authentication.



Efficient & Scalable – Less congestion leads to faster transactions.
Customizable Governance – Organizations define rules and permissions.
Compliance & Security – Suitable for regulated industries (banks, healthcare, etc.).

2. How the Permissioned Model Works?


✔ Key Components of Permissioned Blockchain Model
1️⃣Identity & Access Control
• Participants must authenticate their identity before joining.
• Uses digital certificates or multi-factor authentication for security.
2️⃣Consensus Mechanism

🔹🔹
• Unlike public blockchains using PoW or PoS, permissioned blockchains use:
Proof of Authority (PoA) – Only pre-approved nodes validate transactions.
PBFT (Practical Byzantine Fault Tolerance) – Ensures agreement among trusted
🔹
nodes.
Proof of Elapsed Time (PoET) – Randomized leader selection for fairness.
3️⃣Transaction Validation & Block Addition
• Only authorized nodes validate transactions and add them to the blockchain.
• Network operators can set rules for smart contracts and access rights.
4️⃣Governance & Control
• A central entity or consortium manages the network, updating policies as needed.
• Compliance with regulatory frameworks (GDPR, HIPAA, etc.).

3. Use Cases of Permissioned Blockchain


🚀
🔹
1. Banking & Finance

🔹
🔹
Use Case: Secure cross-border payments & digital asset trading.
Example: JPM Coin (JPMorgan Chase) – A private blockchain for instant transactions.



Why?
Reduces settlement time & cost.
Ensures compliance with AML (Anti-Money Laundering) regulations.

🏭
🔹
2. Supply Chain Management

🔹
🔹
Use Case: Tracking goods from production to delivery with real-time visibility.
Example: IBM Food Trust (Hyperledger Fabric) – Used by Walmart, Nestlé, and Unilever.



Why?
Prevents fraud and counterfeiting.
Improves traceability in food & pharma industries.

🏥
🔹
3. Healthcare & Medical Records

🔹
🔹
Use Case: Secure patient data sharing between hospitals and insurance companies.
Example: MedRec (MIT Media Lab) – Blockchain-based patient record system.



Why?
Ensures data integrity & privacy.
Reduces duplicate records & medical fraud.

🏛️
🔹
4. Government & Identity Management

🔹
🔹
Use Case: Digital ID systems, land registries, and voting.
Example: Aadhaar Blockchain (India) – Securing digital identity records.



Why?
Prevents identity theft.
Provides tamper-proof government records.
🚗
🔹
5. Automotive & IoT

🔹
🔹
Use Case: Securing IoT devices, managing vehicle ownership records.
Example: MOBI (Mobility Open Blockchain Initiative) – Used by BMW, Ford, and GM.



Why?
Prevents car fraud & theft.
Enables secure vehicle-to-vehicle (V2V) communication.

4. Advantages & Disadvantages


✔ Advantages:

✅ Faster Transactions – No mining, only authorized nodes validate.



Better Privacy & Security – Limited access prevents data leaks.
Regulatory Compliance – Supports KYC, AML, and GDPR policies.


Low Energy Consumption – No PoW mining required.

🚨
🚨
Disadvantages:
Centralization Risks – Can be controlled by a few entities.

🚨 Limited Transparency – Not fully open to the public.


Network Governance Issues – Rules can be changed unfairly by the authority.

Design Issues for Permissioned Blockchains


While permissioned blockchains offer better control, privacy, and scalability compared to public
blockchains, they also face several design challenges. These challenges arise in areas like security,
consensus, governance, and scalability.

1. Identity & Access Management


🔹 Issue: Since permissioned blockchains require identity verification, managing user credentials

🔹
securely is critical.

✅ Challenges:



Preventing unauthorized access.
Ensuring KYC (Know Your Customer) and AML (Anti-Money Laundering) compliance.

🛠
Managing user revocation (e.g., removing a malicious participant).
Possible Solutions:
✔ Implement role-based access control (RBAC) to define different user privileges.
✔ Use zero-knowledge proofs (ZKP) for privacy-preserving authentication.
✔ Employ multi-factor authentication (MFA) and cryptographic keys.
2. Consensus Mechanism Selection
🔹 Issue: Public blockchains rely on PoW or PoS, but permissioned blockchains require

🔹
alternative mechanisms to maintain trust.

✅ Challenges:



Finding a balance between decentralization and efficiency.
Ensuring security against Sybil attacks (where an attacker floods the network with fake nodes).

🛠
Preventing collusion among validating nodes.
Possible Solutions:
✔ Use Proof of Authority (PoA) where trusted validators approve transactions.
✔ Implement Byzantine Fault Tolerance (BFT) mechanisms to prevent malicious activity.
✔ Use Proof of Elapsed Time (PoET) for fair leader selection.

3. Governance & Control


🔹 Issue: Since permissioned blockchains are governed by a central entity or consortium, ensuring

🔹
fair decision-making is crucial.

✅ Challenges:



Avoiding single-point control that can lead to manipulation.
Handling disputes among governing entities in a consortium model.

🛠
Ensuring network updates and rule changes are accepted by all stakeholders.
Possible Solutions:
✔ Implement smart contract-based governance to automate rule enforcement.
✔ Use multi-stakeholder voting mechanisms for decision-making.
✔ Maintain a transparent audit trail to ensure trust among participants.

4. Privacy & Data Security


🔹 Issue: Unlike public blockchains, permissioned blockchains require privacy controls to restrict

🔹
data access.

✅ Challenges:



Ensuring confidential transactions between parties.
Protecting sensitive business data from unauthorized access.

🛠
Addressing data breaches or insider threats.
Possible Solutions:
✔ Use zero-knowledge proofs (ZKPs) or secure multi-party computation (SMPC) for private
transactions.
✔ Implement on-chain and off-chain encryption techniques.
✔ Enforce strict data access policies and regular security audits.
5. Scalability & Performance
🔹 Issue: Large-scale enterprise applications require high-speed transactions, but increasing the

🔹
number of nodes can reduce efficiency.

✅ Challenges:



Maintaining low latency while processing transactions.
Preventing network congestion as the number of participants grows.

🛠
Managing block size and storage capacity for long-term scalability.
Possible Solutions:
✔ Implement sharding (splitting data across multiple partitions for parallel processing).
✔ Use off-chain scaling solutions (e.g., state channels, sidechains).
✔ Optimize block size and transaction batching for better efficiency.

6. Integration with Legacy Systems


🔹 Issue: Enterprises often need to integrate permissioned blockchains with existing IT

🔹
infrastructure.

✅ Challenges:



Ensuring interoperability with traditional databases and ERP systems.
Providing APIs for external applications to communicate with the blockchain.

🛠
Handling data migration and compatibility issues.
Possible Solutions:
✔ Develop middleware solutions for blockchain-to-legacy system communication.
✔ Use standardized APIs (REST, GraphQL, gRPC) for integration.
✔ Implement enterprise blockchain frameworks (e.g., Hyperledger Fabric, Corda) designed for
easy integration.

7. Legal & Regulatory Compliance


🔹 Issue: Many industries (banking, healthcare, government) operate under strict legal

🔹
frameworks that blockchains must adhere to.

✅ Challenges:



Compliance with GDPR, HIPAA, AML/KYC regulations.
Handling data ownership & user rights under blockchain immutability.

🛠
Ensuring cross-border transactions follow international laws.
Possible Solutions:
✔ Use private transaction channels to store only essential data on-chain.
✔ Implement data deletion mechanisms (off-chain storage with hashed references).
✔ Regular compliance audits and legal consultation for regulatory updates.
8. Attack Vectors & Security Threats
🔹
🔹 Issue: Even permissioned blockchains are vulnerable to attacks if not properly secured.



Challenges:
Preventing collusion among validators.

✅ Mitigating 51% attacks or node takeover.

🛠
Protecting against DDoS (Distributed Denial of Service) attacks.
Possible Solutions:
✔ Implement multi-signature transaction approval.
✔ Use geographically distributed validator nodes to avoid centralization.
✔ Enforce firewalls, intrusion detection systems (IDS), and access controls.

9. Smart Contract Security


🔹
🔹 Issue: Smart contracts automate processes but are prone to bugs and exploits.



Challenges:
Preventing reentrancy attacks (as seen in The DAO hack).

✅ Avoiding logic errors leading to fund loss.

🛠
Ensuring smart contract upgradability without compromising security.
Possible Solutions:
✔ Conduct formal verification and audits before deployment.
✔ Use upgradeable smart contract patterns like proxies.
✔ Implement timelocks and circuit breakers to stop malicious activity.

10. Network Governance & Fork Management


🔹 Issue: Unlike public blockchains, permissioned blockchains must handle updates and

🔹
disagreements systematically.

✅ Challenges:



Managing protocol upgrades without breaking compatibility.
Preventing hard forks due to disagreements among consortium members.

🛠
Handling disputed transactions or rollbacks fairly.
Possible Solutions:
✔ Use on-chain voting mechanisms for governance decisions.
✔ Implement soft fork-friendly upgrade mechanisms.
✔ Define a clear dispute resolution process for conflicts.
Execute Contracts & State Machine Replication in
Blockchain
1. Execute Contracts in Blockchain
🔹 What Does "Executing Contracts" Mean?
In blockchain, executing a contract refers to the process of running smart contracts, which are
self-executing programs stored on the blockchain. These contracts contain rules and conditions
that trigger transactions automatically when met.

✔ How Smart Contracts Work?


1️⃣Deployment – A developer writes a smart contract (e.g., in Solidity for Ethereum) and deploys it
on the blockchain.
2️⃣Triggering Events – The contract is activated when certain conditions are met (e.g., receiving
payment).
3️⃣Execution – The blockchain nodes execute the contract logic using the blockchain’s virtual
machine (e.g., Ethereum Virtual Machine - EVM).
4️⃣Consensus & Recording – Once validated, the contract execution results are recorded on the
blockchain.


✔ Key Characteristics of Smart Contracts



Immutable – Once deployed, a contract cannot be altered.
Trustless – No need for a central authority; execution is automated.

✅ Transparent – All participants can verify contract logic.


Tamper-proof – Transactions are cryptographically secured.

✔ Example of a Simple Smart Contract (Solidity - Ethereum)


pragma solidity ^0.8.0;

contract SimplePayment {
address payable public seller;

constructor() {
seller = payable(msg.sender);
}

function pay() public payable {


require(msg.value > 0, "Payment must be greater than 0");
seller.transfer(msg.value);
}
}

🔹 This contract receives payments and automatically transfers them to the seller.
2. State Machine Replication (SMR) in Blockchain
🔹 What is State Machine Replication?
State Machine Replication (SMR) is a fault-tolerant technique where multiple nodes maintain an
identical copy of a system’s state. In blockchain, this ensures that all nodes agree on the same
version of transactions and smart contract states.

🔹
✔ How SMR Works in Blockchain?

🔹
🔹
Every blockchain node stores a replica of the system’s state.
Transactions are ordered and executed deterministically on every node.

🔹 Consensus protocols (e.g., Proof of Work, PBFT) ensure all nodes reach the same state.
If a node fails, others maintain the correct state.


✔ Why SMR is Important in Blockchain?



Ensures consistency – All nodes maintain the same blockchain state.
Provides fault tolerance – The system continues to function even if some nodes fail.
Prevents double spending – All nodes validate transactions before state updates.

3. How Execute Contracts & SMR Work Together?


🔹
🔹 Smart contracts execute on every node, ensuring all nodes process the same contract logic.

🔹 State Machine Replication ensures the entire network agrees on contract execution results.
This combination makes decentralized applications (DApps) reliable and consistent.

Overview of Consensus Models for


Permissioned Blockchain
In a permissioned blockchain, participants are pre-approved entities (e.g., banks, supply chain
partners) rather than anonymous nodes. Distributed consensus in a closed environment ensures
that only authorized participants can validate transactions while maintaining security, efficiency,
and scalability.

🔹 Why Do Permissioned Blockchains Need Different


Consensus Models?
Unlike public blockchains (e.g., Bitcoin, Ethereum), where anyone can join and validate


transactions, permissioned blockchains require:

✅ Efficient and fast transaction validation (no need for mining).


Control over participant identities (ensuring trust).

✅ Scalability and compliance with regulatory frameworks.
Resistance to collusion attacks (ensuring fair governance).

🔹 Consensus Models for Permissioned Blockchains


1️⃣ Practical Byzantine Fault Tolerance (PBFT)
✔ How It Works:
• A leader node proposes a transaction.
• Other nodes verify and reach consensus via multiple rounds of voting.
• If at least (2/3 + 1) of the nodes agree, the transaction is committed.


✔ Advantages:

✅ Fast finality (no need for mining).

✅ High security against Byzantine faults (malicious nodes).


Used in enterprise blockchains like Hyperledger Fabric.


✔ Disadvantages:

❌ High communication overhead (each node must talk to all others).


Less scalable for large networks.

2️⃣ Raft Consensus


✔ How It Works:
• Uses a leader-based system where a single node proposes new transactions.
• If a majority (50% + 1 nodes) approve, the transaction is added.
• If the leader fails, a new leader is elected.


✔ Advantages:

✅ Fast and simple consensus mechanism.


Low communication overhead compared to PBFT.


✔ Disadvantages:

❌ Leader node can become a bottleneck.

❌ Less resilient to Byzantine failures (assumes honest participants).

🔹
Not suitable for adversarial environments.
Used in: Hyperledger Fabric (for internal state replication).

3️⃣ Proof of Authority (PoA)


✔ How It Works:
• A small group of trusted validators (authorities) approve transactions.
• Validators are identified entities (e.g., banks, enterprises).
• No mining is required, leading to faster transactions.


✔ Advantages:

✅ Extremely fast transactions and low energy consumption.


Good for consortium blockchains where participants are known.


✔ Disadvantages:

❌ Centralization risk (if validators collude).

🔹
Requires trust in selected authorities.
Used in: VeChain, Microsoft Azure Blockchain.

4️⃣ Proof of Stake (PoS) & Delegated Proof of Stake (DPoS)


✔ How It Works:
• Participants stake tokens to become validators.
• Validators are chosen based on stake + voting (in DPoS).
• Blocks are validated and added to the chain.


✔ Advantages:

✅ Energy-efficient (no mining required).


Scalable compared to PBFT.


✔ Disadvantages:

❌ Not suitable for private blockchains without a token system.

🔹
Rich get richer problem (large stakeholders dominate).
Used in: EOS (DPoS), some enterprise blockchains.

5️⃣ Federated Byzantine Agreement (FBA) – Used in Ripple & Stellar


✔ How It Works:
• Nodes belong to trusted groups (federations).
• Each group selects its own validators.
• Transactions are confirmed when a majority in overlapping federations agree.


✔ Advantages:

✅ Fast transaction processing (~5 sec finality).


Energy-efficient compared to PBFT.


✔ Disadvantages:

❌ Requires careful selection of validator groups.

🔹
Can lead to centralization if validator diversity is low.
Used in: Ripple, Stellar.
🔹 Summary: Comparing Consensus Models for
Permissioned Blockchains
Consensus Example

🔄
Speed Security Scalability

⚡ 🛡
Model Blockchains
Limited Hyperledger
PBFT Fast High
(communication-heavy) Fabric

Raft ⚡⚡ Very Fast 🛡 Moderate 🔄 Good


Hyperledger
Fabric (internal

⚡⚡⚡ 🛡 🔄
state)
Extremely VeChain, Azure
PoA Low-Medium High
Fast Blockchain

PoS/DPoS ⚡⚡ Fast 🛡 Moderate 🔄 High


EOS, Cardano
(some private

⚡⚡ 🛡 🔄
versions)
FBA Fast Moderate High Ripple, Stellar

Paxos & RAFT Consensus in Blockchain


1️⃣ Paxos Consensus Algorithm
🔹 What is Paxos?
Paxos is a fault-tolerant consensus algorithm designed for distributed systems where nodes need
to agree on a single value, even in the presence of failures. It is widely used in distributed
databases, cloud computing, and permissioned blockchains.

✔ How Paxos Works?


Paxos operates in three main roles:
• Proposer – Suggests a value for consensus.
• Acceptor – Votes on proposed values and ensures agreement.
• Learner – Learns the chosen value after consensus is reached.

Steps in Paxos Consensus


1️⃣Proposal Phase – The proposer selects a proposal number and sends it to acceptors.
2️⃣Acceptance Phase – Acceptors vote on the highest-numbered proposal.
3️⃣Commit Phase – If a proposal gets a majority vote, the value is agreed upon.


✔ Strengths & Weaknesses of Paxos

✅ Highly fault-tolerant (works even if some nodes fail).


Mathematically proven correctness in reaching consensus.

❌ High communication overhead (not ideal for large-scale blockchain networks).

🔹
Difficult to implement and scale.
Used in: Google Spanner, Amazon DynamoDB, and some blockchain networks for state
replication.

2️⃣ RAFT Consensus Algorithm


🔹 What is RAFT?
RAFT (Reliable, Replicated, and Fault-Tolerant) is a leader-based consensus algorithm that
simplifies Paxos by making it easier to understand and implement. It is used in private blockchain
networks and distributed databases.

✔ How RAFT Works?


RAFT divides consensus into three key roles:
• Leader – Proposes and commits transactions.
• Follower – Accepts leader proposals and maintains state.
• Candidate – Competes to become a leader in case of failure.

Steps in RAFT Consensus


1️⃣Leader Election – Nodes vote to elect a leader.
2️⃣Log Replication – The leader accepts transactions and replicates them across followers.
3️⃣Commit Phase – Once a majority agrees, the transaction is committed.
4️⃣Failure Handling – If the leader crashes, a new leader is elected.


✔ Strengths & Weaknesses of RAFT



Simpler than Paxos and easier to implement.
Efficient for permissioned blockchains (low-latency transactions).



Fast leader election ensures minimal downtime.
Leader-based system (can be a bottleneck).

🔹
Less fault-tolerant than Paxos in highly unstable environments.
Used in: Hyperledger Fabric (for internal state replication), etcd, Consul.

🔹 Paxos vs RAFT: Key Differences


Feature Paxos RAFT
Architecture Decentralized Leader-based
Complexity Complex Simpler
Fault Tolerance Higher Moderate
Scalability Difficult to scale Easier to scale
Feature Paxos RAFT
Performance High overhead Fast leader election

🔹

When to Use Paxos vs RAFT in Blockchain?

✅ Use Paxos when high fault tolerance is required (e.g., global distributed systems).
Use RAFT when performance and simplicity are more important (e.g., permissioned
blockchains like Hyperledger Fabric).

Byzantine Generals Problem & Byzantine Fault


Tolerant (BFT) Systems
1️⃣ Byzantine Generals Problem
🔹 What is the Byzantine Generals Problem?
The Byzantine Generals Problem (BGP) is a classic problem in distributed computing that
describes how a group of generals (computers/nodes) must reach agreement despite some of them

📌
being faulty or malicious.
Scenario:
• Several Byzantine generals are leading different parts of an army.
• They must decide on a common strategy (attack or retreat).
• Some generals may be traitors who send false messages.
• The loyal generals need a way to reach a consensus, even if some messages are unreliable.


✔ Challenges in the Byzantine Generals Problem:



Nodes may send conflicting information (malicious behavior).
Communication between nodes may be unreliable.
Some nodes may be compromised or faulty.

✔ Key Question:
How can the generals (nodes) ensure that all honest nodes agree on the same decision, despite faulty
or malicious ones?
2️⃣ Byzantine Fault Tolerant (BFT) Systems
🔹 What is Byzantine Fault Tolerance (BFT)?
A Byzantine Fault Tolerant (BFT) system is a distributed network that can reach consensus even

📌
if some nodes fail or act maliciously.
Rule of BFT: A system can tolerate up to (N-1)/3 Byzantine nodes, meaning it must have at
least 3f + 1 total nodes to handle f malicious nodes.

✔ How BFT Works?


• Nodes use a consensus algorithm to agree on valid transactions.
• Multiple rounds of message exchange ensure consistency.
• Even if some nodes send false data, the majority consensus remains correct.

🔹
✔ Examples of BFT Algorithms in Blockchain:
Practical Byzantine Fault Tolerance (PBFT)
• Used in Hyperledger Fabric and other private blockchains.
• Nodes vote on transactions in multiple rounds.

🔹
• Works best for smaller, controlled networks.
Federated Byzantine Agreement (FBA)
• Used in Stellar, Ripple.

🔹
• Nodes form trusted groups (quorums) to validate transactions.
Proof of Work (PoW) – Bitcoin’s Byzantine Fault Tolerance
• Bitcoin avoids Byzantine failures by making mining computationally expensive.

🔹
• Attackers need 51% of the total mining power to manipulate transactions.
Proof of Stake (PoS) – Ethereum 2.0 BFT
• Instead of mining, staked coins determine voting power.
• Attacks become expensive as dishonest validators lose their stake.

3️⃣ Why is Byzantine Fault Tolerance Important?



✅ Ensures Security – Transactions remain valid even with malicious nodes.

✅ Prevents Double Spending – Stops fraudulent transactions in cryptocurrencies.


Reliable Distributed Systems – Used in banking, cloud computing, and blockchains.
Lamport-Shostak-Pease BFT Algorithm &
BFT in Asynchronous Systems
1️⃣ Lamport-Shostak-Pease Byzantine Fault Tolerance (BFT)
Algorithm
🔹 What is the Lamport-Shostak-Pease BFT Algorithm?
The Lamport-Shostak-Pease Algorithm is a Byzantine Fault Tolerant (BFT) algorithm developed
by Leslie Lamport, Robert Shostak, and Marshall Pease. It provides a solution to the Byzantine
Generals Problem by ensuring that a group of nodes (or generals) can agree on a common value
even if some nodes are faulty or malicious.

✔ Key Idea:
The algorithm ensures consensus by having multiple rounds of message exchange, where nodes
filter out malicious inputs and derive a majority agreement.

✔ Assumption:
• The system consists of N nodes.
• Up to f faulty nodes can exist.
• To tolerate f Byzantine faults, the total number of nodes must be at least 3f + 1.

✔ Steps of the Algorithm:


1️⃣Message Exchange:
• Each node sends its value to all other nodes.
• Every node collects values from others, including potential faulty values.
2️⃣Recursive Majority Voting:
• Nodes perform multiple rounds of filtering, rejecting obviously false values.
• A majority-based mechanism determines the final agreed value.
3️⃣Agreement Formation:
• After f+1 rounds, nodes settle on a common value.

• If at least (2f+1) nodes share the same value, consensus is achieved.

✔ Example Scenario (N = 4, f = 1):


• 4 generals need to decide on Attack or Retreat.
• One general is faulty and sends conflicting messages.
• Using recursive rounds and majority voting, the remaining 3 honest generals agree on a
common decision, ignoring the faulty input.

✔ Strengths & Weaknesses of the Algorithm:



Mathematically proven solution for Byzantine faults.
Efficient for smaller networks.

❌ High communication complexity (O(N²) messages).


Not suitable for large-scale decentralized blockchains.

2️⃣ Byzantine Fault Tolerance in Asynchronous Systems


🔹 What is an Asynchronous System?


An asynchronous system is a distributed network where:

✅ There is no fixed upper bound on message delivery time.

✅ Nodes may process transactions at different speeds.


Network delays, node failures, or message loss may occur.

🔹 Why is BFT Difficult in Asynchronous Systems?


• Traditional BFT algorithms assume synchronous communication (all messages arrive
within a known time).
• In real-world blockchain networks, delays and network congestion make full
synchronization impossible.
• FLP Impossibility Theorem states that in a fully asynchronous system, achieving 100%
consensus with fault tolerance is impossible.

🔹
✔ BFT Solutions for Asynchronous Systems
Practical Byzantine Fault Tolerance (PBFT):
• Used in Hyperledger Fabric, Zilliqa.

🔹
• Works well in semi-synchronous networks with limited delay assumptions.
Asynchronous Byzantine Fault Tolerance (ABFT):
• Used in Hashgraph, Fantom, and Avalanche blockchains.

🔹
• Allows nodes to reach consensus without strict timing guarantees.
Proof-of-Work (PoW) as an Asynchronous BFT Mechanism:
• Bitcoin and Ethereum use mining difficulty to tolerate Byzantine faults.
• Consensus happens eventually, but not in a fixed time (probabilistic finality).

3️⃣ Summary: BFT in Different Environments


Feature Lamport-Shostak-Pease BFT BFT in Asynchronous Systems
Network Type Synchronous Asynchronous
Feature Lamport-Shostak-Pease BFT BFT in Asynchronous Systems
Consensus Time Fixed number of rounds Variable (depends on network delays)
Use Case Military coordination, small networks Large-scale blockchain networks
Examples Paxos, PBFT PoW, Hashgraph, Avalanche
Unit 4
Cross-Border Payments in Blockchain
1️⃣ What Are Cross-Border Payments?
Cross-border payments refer to financial transactions between individuals or businesses in
different countries. These transactions involve multiple intermediaries like banks, payment
processors, and regulatory bodies.


✔ Challenges in Traditional Cross-Border Payments:



Slow Processing Times – Transactions can take several days due to multiple intermediaries.
High Transaction Fees – Banks and intermediaries charge high processing fees.



Lack of Transparency – Users cannot track payments in real-time.
Currency Exchange Issues – Foreign exchange rates fluctuate, leading to unpredictable costs.
Risk of Fraud & Errors – Multiple intermediaries increase the chances of errors and fraud.

2️⃣ How Blockchain Improves Cross-Border Payments?


Blockchain technology eliminates intermediaries, enabling faster, cheaper, and more
transparent international transactions.


✔ Benefits of Blockchain in Cross-Border Payments:
Faster Transactions – Transactions settle in minutes or hours, compared to days in traditional


banking.
Lower Costs – Reduces banking fees, currency conversion costs, and intermediary


charges.

✅ Transparency & Security – Immutable ledger ensures real-time tracking and prevents fraud.
Smart Contracts – Automate payments based on predefined conditions, reducing the risk of


disputes.
Financial Inclusion – Provides access to banking services for unbanked populations
worldwide.

3️⃣ Blockchain-Based Cross-Border Payment Solutions


🔹 1. Ripple (XRP) & RippleNet
• Uses XRP cryptocurrency for instant settlement.
• Banks and financial institutions use RippleNet to process payments globally.
• Transaction fees are lower than traditional SWIFT transfers.
🔹 2. Stellar (XLM)
• Designed for low-cost international payments, especially for developing countries.
• Supports fiat currency and crypto asset transfers.
• Used by companies like IBM for cross-border remittances.

🔹 3. CBDCs (Central Bank Digital Currencies)


• Governments are exploring blockchain-based digital currencies to replace SWIFT-based
payments.
• Examples: China's Digital Yuan, India's E-Rupee, Europe's Digital Euro.

🔹 4. Bitcoin & Lightning Network


• Bitcoin allows peer-to-peer cross-border payments.
• The Lightning Network enables instant micropayments with low fees.

🔹 5. Stablecoins (USDT, USDC, DAI)


• Pegged to fiat currencies like USD to reduce volatility.
• Used by companies like PayPal (PYUSD) and Visa for cross-border transactions.

4️⃣ Blockchain vs Traditional Payment Systems


Feature Blockchain (Ripple, Stellar) Traditional (SWIFT, Banks)
Speed Seconds to minutes 3-5 business days
Cost Low fees (fractions of a cent) High fees ($10-$50 per transaction)
Transparency Fully traceable Limited tracking
Security Tamper-proof ledger Prone to fraud/errors
Peer-to-peer (No banks
Intermediaries Multiple intermediaries (Banks, SWIFT, etc.)
needed)

5️⃣ Future of Blockchain in Cross-Border Payments


🔹
🔹 More banks adopting blockchain for real-time settlements (e.g., JPM Coin by JPMorgan).

🔹
🔹
Growth of CBDCs (Central Bank Digital Currencies) replacing traditional fiat transfers.
Regulations evolving to support blockchain-based remittances.
Integration with AI & IoT for automated and intelligent payment processing.
Know Your Customer (KYC) in Blockchain
1️⃣ What is KYC?
Know Your Customer (KYC) is a process used by financial institutions to verify the identity of
customers before allowing them to use services. KYC helps prevent fraud, money laundering,
terrorist financing, and financial crimes.

✔ Traditional KYC Process:


1️⃣Identity Verification – Customers provide government-issued IDs, passports, or other
documents.
2️⃣Address Verification – Proof of address (utility bills, bank statements).
3️⃣Risk Assessment – Checking financial history, credit score, and potential risks.
4️⃣Ongoing Monitoring – Detecting suspicious activities and ensuring compliance.
📌
❌ Problems with Traditional KYC:



Slow & Expensive – Manual verification takes days and costs money.
Data Privacy Risks – Centralized databases are vulnerable to hacks.
Redundant Process – Customers must submit documents repeatedly for different institutions.

2️⃣ How Blockchain Improves KYC?


Blockchain technology enhances KYC by offering a decentralized, secure, and efficient
verification system.


✔ Benefits of Blockchain-Based KYC:



Single Digital Identity – Users verify their identity once and share it with multiple institutions.
Faster Verification – Reduces processing time from days to minutes.



Improved Security – Data is encrypted and stored in a tamper-proof blockchain.
Lower Costs – Eliminates repeated verification, reducing compliance costs.
User Control – Customers can choose who accesses their data, improving privacy.

3️⃣ Blockchain-Based KYC Process


🔹 Steps in Blockchain KYC:
1️⃣User Submits KYC Documents – Identity details are uploaded and encrypted on the
blockchain.
2️⃣Verification by Trusted Authority – A government or financial institution verifies the identity.
3️⃣Blockchain Stores a Digital Identity Hash – Instead of raw data, only a hash (unique
fingerprint) is stored.
4️⃣Instant Verification for Other Institutions – Other banks or services can verify identity using
the stored hash without redoing the entire KYC process.
5️⃣User Consent & Access Control – Users can grant or revoke access to their KYC data.

🔹 Example Use Case: Blockchain KYC in Banking


• A customer completes KYC once at Bank A.
• Later, they want to open an account at Bank B.
• Instead of resubmitting documents, Bank B verifies the existing KYC record on the
blockchain.
• Result: Instant onboarding, no duplicate verification.

4️⃣ Real-World Blockchain-Based KYC Solutions


🔹
🔹 Civic (CVC) – Offers a decentralized identity verification system.

🔹
🔹
IBM Blockchain for KYC – Helps banks securely share KYC data.
Sovrin Network – Uses self-sovereign identity (SSI) for decentralized identity management.
Hyperledger Indy – A blockchain framework for digital identity solutions.

5️⃣ Challenges of Blockchain KYC



❌ Regulatory Compliance – Governments have different KYC requirements.
Adoption Issues – Banks and regulators must integrate blockchain-based KYC into existing


systems.
Data Privacy Concerns – Blockchain is immutable, so incorrect data cannot be easily changed.

6️⃣ Future of Blockchain KYC


🔹 Integration with AI & Biometrics – AI-powered verification and facial recognition for

🔹
seamless KYC.
More Government Adoption – Countries like India (Aadhaar on Blockchain) and Dubai

🔹
(Smart KYC Blockchain) are exploring blockchain-based identity solutions.
Self-Sovereign Identity (SSI) – Users control their own identity without relying on centralized
databases.

Food Security and Blockchain


1️⃣ What is Food Security?
Food security means ensuring that all people have access to sufficient, safe, and nutritious food to
maintain a healthy life. It is based on four key pillars:
1️⃣Availability – Sufficient food production and supply.
2️⃣Accessibility – Affordable and physically accessible food.
3️⃣Utilization – Proper nutrition and food safety.
4️⃣Stability – Consistent food supply over time.
📌
❌ Challenges in Food Security:



Food Fraud & Contamination – Lack of transparency in the supply chain.
Inefficient Logistics – Poor tracking leads to food wastage.

❌ Lack of Farmer Fair Pricing – Middlemen exploit small farmers.


Climate Change & Crop Failures – Unpredictable weather impacts production.

2️⃣ Role of Blockchain in Food Security


Blockchain technology enhances transparency, traceability, and efficiency in food supply chains,
ensuring safer and more accessible food.


✔ Benefits of Blockchain in Food Security:



Food Traceability – Tracks food from farm to table, reducing fraud and contamination.
Supply Chain Efficiency – Reduces food wastage by optimizing logistics.

✅ Fair Trade & Pricing – Smart contracts ensure fair payment for farmers.
Food Safety – Quick identification of contaminated batches prevents large-scale foodborne


diseases.
Reduced Food Fraud – Eliminates fake labels and counterfeit food products.

3️⃣ How Blockchain Works in Food Security


🔹 Blockchain-Based Food Supply Chain:
1️⃣Farmers record crop data (harvest date, pesticide use, organic certification) on the blockchain.
2️⃣Transport & Logistics companies update location & storage conditions in real-time.
3️⃣Retailers & Consumers scan QR codes to check the entire journey of food.
4️⃣Smart Contracts automate payments to farmers and suppliers once food reaches the market.
📌 Example:
• A mango exported from India to the USA can have its journey verified on the
blockchain, ensuring freshness and authenticity.
• IBM Food Trust (using Hyperledger Fabric) helps companies like Walmart and Nestlé
track food origins in seconds instead of days.
4️⃣ Real-World Blockchain Solutions in Food Security
🔹
🔹 IBM Food Trust – Used by Walmart, Nestlé, Carrefour to track food safety.

🔹
🔹
AgriDigital – Ensures secure, transparent grain transactions for farmers.
TE-FOOD – Tracks livestock and fresh food across Asia and Africa.
VeChain – Verifies organic and high-quality food authenticity.

5️⃣ Challenges in Implementing Blockchain for Food Security



❌ High Initial Costs – Blockchain adoption requires investment in technology.

❌ Farmer Digital Literacy – Many farmers lack the skills to use blockchain-based systems.
Integration with Legacy Systems – Traditional food supply chains need to adapt.

6️⃣ Future of Blockchain in Food Security


🔹 AI + Blockchain for Smart Agriculture – AI-powered crop monitoring with blockchain

🔹
tracking.
Decentralized Farmer Cooperatives – Farmers using blockchain for direct sales and fair

🔹
pricing.
Government Adoption – Governments using blockchain to prevent food fraud and improve
subsidy distribution.

Mortgage Over Blockchain


1️⃣ What is a Mortgage?
A mortgage is a loan used to purchase real estate, where the property itself serves as collateral. The

📌
borrower repays the loan over time, typically in monthly installments.

❌ Challenges in Traditional Mortgage Processing:


Slow & Expensive – Mortgage approvals take weeks or months due to paperwork and


intermediaries.

❌ Fraud & Identity Theft – Manual verification increases the risk of fraud.

❌ Lack of Transparency – Borrowers don’t have clear visibility into loan status.
High Costs – Lenders charge high fees for processing and verification.

2️⃣ How Blockchain Improves Mortgages?


Blockchain technology enhances transparency, efficiency, and security in mortgage transactions.

✔ Benefits of Blockchain in Mortgages:



Faster Approvals – Smart contracts automate verification and approval.
Reduced Costs – Eliminates intermediaries, lowering fees.



Transparency & Security – Immutable blockchain records prevent fraud.
Fractional Ownership – Allows tokenization of real estate for easier investment.
Efficient Land Registry – Governments can use blockchain to prevent property disputes.

3️⃣ Blockchain-Based Mortgage Process


🔹 Steps in a Blockchain Mortgage System:
1️⃣Digital Identity Verification – Blockchain stores borrower’s KYC details.
2️⃣Smart Contract Execution – Automates loan terms, repayments, and penalties.
3️⃣Property Tokenization – Converts real estate into digital tokens for easy transfers.
4️⃣Instant Loan Disbursement – Smart contracts ensure fast fund transfers.
5️⃣Immutable Land Registry – Ensures secure property ownership records.
📌 Example:
• A borrower applies for a mortgage through a blockchain-based platform.
• Lenders verify their credit and property ownership using decentralized KYC records.
• Smart contracts manage loan disbursement and repayments automatically.

4️⃣ Real-World Blockchain Mortgage Solutions


🔹
🔹 Propy – Uses blockchain for real estate transactions and land registry.

🔹 Figure – A blockchain-powered mortgage lending platform.


Smartlands – Tokenizes real estate for fractional ownership.

5️⃣ Challenges in Implementing Blockchain Mortgages



❌ Regulatory Compliance – Different countries have varying mortgage laws.

❌ Adoption Barriers – Banks and lenders must integrate blockchain systems.


Smart Contract Risks – Bugs in smart contracts could cause financial losses.

6️⃣ Future of Blockchain in Mortgages


🔹
🔹 AI + Blockchain for Automated Loan Approvals

🔹 Government Adoption for Land Registry


Decentralized Mortgage Platforms
Blockchain-Enabled Trade
1️⃣ What is Trade?
Trade refers to the exchange of goods, services, or assets between parties. It can be domestic
(within a country) or international (across borders). Traditional trade relies on intermediaries like

📌
banks, customs, and regulatory bodies to verify transactions.



Challenges in Traditional Trade:
Slow Processing – Paper-based documentation delays transactions.



High Costs – Banks and intermediaries charge fees for verification.
Fraud & Counterfeit Goods – Difficult to track the authenticity of products.
Lack of Transparency – Buyers and sellers rely on third parties for trust.

2️⃣ How Blockchain Enables Trade?


Blockchain improves trade by offering decentralized, secure, and transparent transactions.


✔ Benefits of Blockchain in Trade:



Faster Transactions – Smart contracts automate trade settlements.
Lower Costs – Eliminates middlemen, reducing transaction fees.



Enhanced Security – Cryptographic encryption prevents fraud.
Real-Time Tracking – Blockchain ensures end-to-end product traceability.
Cross-Border Payments – Enables instant, low-cost international payments using
cryptocurrencies.

3️⃣ Blockchain-Based Trade Process


🔹 Steps in a Blockchain-Enabled Trade System:
1️⃣Smart Contracts – Automatically execute trade agreements upon meeting conditions.
2️⃣Supply Chain Transparency – Records product origin, shipment, and delivery.
3️⃣Decentralized Digital Identity – Verifies businesses and reduces fraud.
4️⃣Instant Cross-Border Payments – Uses blockchain-based digital currencies.
5️⃣Immutable Ledger – Prevents tampering and ensures data integrity.
📌 Example:
• A company in India exports coffee to a retailer in the USA.
• Blockchain records production, shipment, and payment details.
• Smart contracts release payment upon delivery confirmation.
• Result: Faster processing, reduced costs, and improved trust.
4️⃣ Real-World Blockchain Trade Solutions
🔹
🔹 TradeLens – A blockchain-based supply chain platform by IBM & Maersk.

🔹
🔹
We.trade – A blockchain trade finance network for European banks.
Marco Polo Network – A blockchain-powered trade finance network.
VeChain – Tracks goods and prevents counterfeiting in global trade.

5️⃣ Challenges in Blockchain Trade Adoption



❌ Regulatory Uncertainty – Governments have different blockchain policies.

❌ Integration with Legacy Systems – Businesses must update their existing IT infrastructure.
Scalability Issues – Public blockchains may struggle with high transaction volumes.

6️⃣ Future of Blockchain in Trade


🔹
🔹 AI + Blockchain for Automated Trade Settlement

🔹 CBDCs (Central Bank Digital Currencies) for Faster Payments


Global Standardization of Blockchain-Based Trade Systems

We.Trade – Blockchain-Based Trade Finance


Network
1️⃣ What is We.Trade?
We.Trade is a blockchain-powered trade finance platform that simplifies and secures
transactions between businesses and banks. It was developed by major European banks using

📌
IBM’s Hyperledger Fabric.



Key Features:
Smart Contracts – Automates payments when trade conditions are met.



Real-Time Tracking – Businesses track transactions end-to-end.
Fraud Prevention – Immutable records ensure transaction integrity.
Faster Cross-Border Trade – Reduces paperwork and bank delays.
2️⃣ How We.Trade Works?
1️⃣Buyer and Seller Agreement – Trade terms are recorded on the blockchain.
2️⃣Smart Contract Activation – Automatically executes when conditions are met.
3️⃣Bank Verification – Participating banks ensure compliance and funding.
4️⃣Payment Execution – Funds are released only when contractual obligations are met.
5️⃣Final Settlement – Transaction is completed and stored securely.
📌 Example:
• A company in Germany wants to buy raw materials from a supplier in Spain.
• Both parties agree on terms via We.Trade and initiate a smart contract.
• Once the goods are shipped and verified, the payment is automatically processed.
• No intermediaries, delays, or paperwork hassles.

3️⃣ Benefits of We.Trade



✅ Reduces Trade Risk – Smart contracts prevent payment defaults.



Enhances Efficiency – Cuts down paperwork and manual processing.
Cost Savings – Reduces transaction fees and banking charges.
Improves SME Trade Access – Small businesses gain access to reliable financing.

4️⃣ Banks Supporting We.Trade


🔹
🔹 HSBC

🔹
🔹
UniCredit
Société Générale

🔹 Deutsche Bank
Santander

5️⃣ Challenges in Adoption



❌ Regulatory Barriers – Different trade laws across countries.

❌ Bank Participation Required – We.Trade is limited to partner banks.


Business Awareness – Many SMEs are unaware of blockchain-based trade finance.

6️⃣ Future of We.Trade & Blockchain in Trade Finance


🔹
🔹 Expansion to More Banks & Regions

🔹 Integration with AI for Smart Risk Analysis


Collaboration with CBDCs (Central Bank Digital Currencies)
Supply Chain Financing & Identity on
Blockchain
1️⃣ Supply Chain Financing (SCF) on Blockchain
Supply Chain Financing (SCF) helps suppliers get early payments while buyers extend their
payment terms. Blockchain enhances SCF by making transactions faster, more transparent, and
secure.

🔹

Challenges in Traditional SCF:



Slow Payment Processing – Manual approvals delay payments.
Lack of Transparency – Suppliers struggle to verify payment status.

❌ High Costs & Middlemen – Banks and financial institutions charge high fees.
Fraud Risk – Fake invoices and identity fraud disrupt financing.

🔹

How Blockchain Improves SCF:



Smart Contracts – Automate payments upon fulfillment of trade terms.
Real-Time Tracking – All parties can verify payment status instantly.

✅ Lower Costs – Eliminates intermediaries and reduces fees.

📌
Fraud Prevention – Blockchain ensures authentic and immutable records.
Example:
• A supplier delivers goods to a retailer.
• A smart contract verifies delivery and automatically releases payment.
• Banks & lenders can view secure transaction history to offer financing.

🔹
🔹
Real-World Blockchain SCF Solutions:

🔹
🔹
IBM & Maersk’s TradeLens – Improves supply chain visibility and financing.
Marco Polo Network – Uses blockchain for real-time trade financing.
We.Trade – A blockchain SCF platform backed by major European banks.

2️⃣ Identity on Blockchain


Identity verification is crucial in finance, healthcare, and trade. Blockchain-based identity systems
provide secure, tamper-proof digital identities.

🔹

Problems with Traditional Identity Systems:

❌ Data Breaches – Centralized databases are vulnerable to hacking.


Lack of Control – Users don’t own their identity data.
❌ Time-Consuming Verifications – Repeated KYC (Know Your Customer) processes slow down


transactions.
Identity Fraud – Fake identities and document forgery are common.

🔹

How Blockchain Improves Identity Management:



Self-Sovereign Identity (SSI) – Users own and control their digital identity.
Tamper-Proof Records – No unauthorized changes to identity data.

✅ One-Time KYC – Verifications are reusable across platforms.

📌
Privacy & Security – Only authorized parties access identity data.
Example:
• A user creates a digital identity on a blockchain platform.
• A bank verifies and approves the identity once.
• The same identity can be used for multiple financial transactions without repeating KYC.

🔹
🔹
Real-World Blockchain Identity Solutions:

🔹
🔹
uPort – A self-sovereign identity platform.
Sovrin Network – Provides decentralized identity management.
Microsoft Azure AD Verifiable Credentials – Blockchain-based identity verification.

3️⃣ Future of Blockchain in SCF & Identity Management


🔹
🔹 Integration with AI for risk assessment & fraud detection.

🔹 Governments adopting blockchain-based digital identity systems.


Cross-border supply chain financing using CBDCs (Central Bank Digital Currencies).
Unit 5
Hyperledger Fabric – Architecture
1️⃣ What is Hyperledger Fabric?
Hyperledger Fabric is a permissioned blockchain framework designed for enterprise applications.
Unlike public blockchains like Bitcoin and Ethereum, Hyperledger Fabric is private and

📌
controlled by known participants.



Key Features:
Permissioned Network – Only authorized participants can join.



Pluggable Consensus – Supports different consensus mechanisms.
Smart Contracts (Chaincode) – Automates business logic.
Private Data Channels – Enables confidential transactions.

2️⃣ Hyperledger Fabric Architecture Components


🔹 1. Membership Service Provider (MSP)
• Manages identities and authentication of participants.
• Uses PKI (Public Key Infrastructure) for digital certificates.
• Ensures only authorized members can interact with the network.

🔹 2. Peer Nodes
• Store the blockchain ledger and execute smart contracts.

🔹🔹
• Types of Peers:
Endorsing Peer (Endorser): Simulates and signs transactions.

🔹Committing Peer (Committer): Validates and commits transactions.


Anchor Peer: Connects different organizations within a consortium.

🔹 3. Orderer Node (Ordering Service)


• Ensures transaction ordering and delivers blocks to peers.

🔹🔹
• Consensus Algorithms Used:
Solo – For testing purposes.

🔹Kafka/Zookeeper – For high throughput applications.


Raft – Crash fault-tolerant ordering.

🔹 4. Ledger
• A distributed database that stores transactions.
🔹🔹
• Consists of:
Blockchain: Immutable transaction records.
World State Database: Current state of assets (Stored in CouchDB or LevelDB).

🔹 5. Chaincode (Smart Contracts)


• Business logic deployed on the blockchain.
• Written in Go, Java, or Node.js.

🔹 6. Channels
• Private communication sub-networks between specific participants.
• Ensures confidentiality in enterprise transactions.

3️⃣ Hyperledger Fabric Transaction Flow


1️⃣Client submits a transaction proposal to endorsing peers.
2️⃣Endorsing peers simulate the transaction and sign the results.
3️⃣Proposal responses are sent back to the client.
4️⃣Client submits the transaction to the orderer.
5️⃣Orderer batches transactions into a block and sends it to peers.
6️⃣Peers validate and commit the block to the ledger.

4️⃣ Hyperledger Fabric Use Cases


🔹
🔹 Supply Chain Management – Walmart uses it for food safety tracking.

🔹 Healthcare – Secure patient record sharing.


Finance – Trade finance solutions like We.Trade.

5️⃣ Future of Hyperledger Fabric


🔹
🔹 Integration with AI for automation.

🔹 Scalability improvements using Layer 2 solutions.


More adoption in cross-border trade & digital identity.
Identities and Policies in Hyperledger Fabric
1️⃣ Identities in Hyperledger Fabric
🔹 What is an Identity?
An identity in Hyperledger Fabric represents a participant in the blockchain network, such as a
peer, orderer, client, or admin. It is used for authentication and authorization to control access.

🔹 How Identities Work?


• Hyperledger Fabric uses Public Key Infrastructure (PKI) to manage identities.
• Each identity is associated with a digital certificate issued by a Certificate Authority
(CA).
• The identity allows a participant to sign transactions and access network resources.

🔹 Membership Service Provider (MSP)


• MSP is a component that manages identities and permissions in the network.
• It verifies the authenticity of certificates issued by the CA.
• MSPs are used to define which participants are allowed to perform actions in the

📌
network.
Example:
• A supplier in a supply chain network has an identity.
• The network administrator assigns permissions based on the supplier’s role.
• The supplier can only submit transactions but cannot modify network settings.

2️⃣ Policies in Hyperledger Fabric


🔹 What are Policies?
Policies define the rules that control who can access, modify, or validate transactions in a
blockchain network.

🔹 Types of Policies
1️⃣Signature Policy:
• Defines which identities must sign a transaction for it to be valid.
• Example: A transaction may require signatures from at least 2 out of 3 organizations.
2️⃣ImplicitMeta Policy:
• Used for system-level policies (e.g., chaincode approvals).
• Example: Requires a majority of administrators to approve chaincode changes.
3️⃣Access Control List (ACL) Policy:
• Specifies who can invoke chaincode functions or query data.
• Example: Only users with admin roles can update network configurations.

🔹 How Policies Work?


• Policies are defined in the channel configuration and chaincode endorsement policies.

📌
• They ensure only authorized participants can perform certain actions.
Example:
• A bank’s trade finance network requires at least two bank representatives to approve a loan
transaction before it is recorded on the blockchain.
• The Signature Policy ensures that two signatures are required for validation.

3️⃣ Importance of Identities & Policies in Hyperledger Fabric



✅ Enhanced Security – Only verified participants can access the network.



Controlled Access – Permissions are assigned based on participant roles.
Regulatory Compliance – Organizations can enforce strict governance rules.
Prevention of Fraud – Ensures transactions are validated by authorized members.

Membership, Access Control, and Channels in


Hyperledger Fabric
1️⃣ Membership and Access Control in Hyperledger Fabric
🔹 Membership in Hyperledger Fabric
Hyperledger Fabric is a permissioned blockchain, meaning that only authorized participants can
join the network. Membership is managed using the Membership Service Provider (MSP),
which verifies the identities of users and organizations.

🔹 Membership Service Provider (MSP)


• Manages identities and authentication of users.
• Uses PKI (Public Key Infrastructure) for issuing and validating digital certificates.
• Ensures only trusted members can participate in transactions.
• Each organization in the network has its own MSP to define its participants.
📌 Example:
A supply chain network has three organizations (Org1, Org2, Org3). Each org has its own MSP,
which verifies the identities of users from that organization before allowing them to interact with
the blockchain.

🔹 Access Control in Hyperledger Fabric


Access control ensures that only authorized users can perform specific actions in the blockchain
network. It is defined using policies and roles.

🔹 Types of Access Control Policies


1️⃣Endorsement Policy: Defines which peers must approve a transaction before it is committed.
• Example: A transaction requires signatures from Org1 and Org2 before being added to the
blockchain.
2️⃣Access Control List (ACL) Policy: Controls who can invoke chaincode functions or query the
ledger.
• Example: Only users with the admin role can update network configurations.
3️⃣Channel Policies: Define who can read, write, or manage a private channel.
📌 Example:
In a banking network, only bank officials should be able to approve transactions, while customers
can only submit requests.

2️⃣ Channels in Hyperledger Fabric


🔹 What are Channels?
A channel is a private blockchain within the larger Hyperledger Fabric network. It allows specific
participants to share data without exposing it to others in the network.

🔹 How Channels Work?


• Each channel has its own ledger and smart contracts (chaincode).
• Only members with permission can access the channel’s data.
• Transactions in one channel are not visible to participants outside the channel.

🔹

Benefits of Channels



Privacy & Confidentiality – Only authorized participants can view transactions.
Data Isolation – Different business units can operate independently.

📌
Scalability – Reduces network congestion by splitting traffic into multiple channels.
Example:
A pharmaceutical supply chain involves manufacturers, distributors, and hospitals.
• Channel 1: Manufacturer ↔ Distributor (Tracks raw material supply).
• Channel 2: Distributor ↔ Hospital (Tracks medicine delivery).
• Data from Channel 1 is hidden from the hospital to protect business confidentiality.

3️⃣ How Membership, Access Control, and Channels Work


Together
🔹
🔹 Membership (MSP) verifies identities before allowing access.

🔹 Access Control Policies define what each participant can do.

📌
Channels ensure private communication between specific participants.
Real-World Use Case:


We.Trade (A blockchain trade finance platform) uses:

✅ MSP to verify banks and businesses.

✅ Access Control Policies to define who can approve payments.


Channels to isolate transactions between different banks and their clients.

Transaction Validation in Hyperledger Fabric


1️⃣ What is Transaction Validation?
Transaction validation in Hyperledger Fabric ensures that only legitimate, authorized, and
endorsed transactions are committed to the blockchain ledger.

🔹 Key Steps in Transaction Validation


1️⃣Proposal Submission – A client submits a transaction proposal to endorsing peers.
2️⃣Endorsement Phase – Endorsing peers simulate the transaction and generate signed responses.
3️⃣Ordering & Block Creation – The ordering service collects valid transactions and creates
blocks.
4️⃣Validation Phase – Committing peers validate transactions before adding them to the ledger.
5️⃣Commit to Ledger – Only valid transactions are added to the blockchain.

2️⃣ Transaction Validation Process


🔹 Step 1: Proposal Submission
• A client application submits a transaction proposal to endorsing peers.
• The proposal contains transaction details (e.g., asset transfer request).
🔹 Step 2: Endorsement Phase
• Endorsing peers simulate the transaction using the chaincode (smart contract).
• They do not commit the transaction yet but return a signed response.
• The client collects endorsements based on the endorsement policy (e.g., at least 2 out of 3
organizations must approve).

🔹 Step 3: Ordering & Block Creation


• The client submits the endorsed transaction to the ordering service.
• The ordering service batches transactions into blocks and sends them to committing peers.
• Ordering does not check transaction validity (it only sequences transactions).

🔹 Step 4: Validation Phase (MVCC Check & Endorsement Policy Check)


• Multi-Version Concurrency Control (MVCC) Check:
• Ensures the transaction is based on the latest ledger state.
• If another transaction modified the same data, a read-write conflict occurs (leading
to invalidation).
• Endorsement Policy Check:
• Confirms that the transaction has the required number of endorsements.
• If any signature is missing or tampered with, the transaction is rejected.

🔹 Step 5: Commit to Ledger


• Valid transactions are added to the ledger.
• Invalid transactions are marked as rejected but still recorded for audit purposes.

3️⃣ Importance of Transaction Validation



✅ Prevents Double Spending – Ensures assets are not spent twice.



Maintains Ledger Consistency – Avoids conflicting updates.
Enhances Security – Protects against unauthorized changes.
Ensures Compliance – Transactions adhere to endorsement policies.

4️⃣ Example: Valid vs. Invalid Transaction


📌
🔹 Scenario: A supply chain blockchain records product shipments.

🔹 ✅
Valid Transaction: A supplier gets endorsements from required participants and submits the
transaction without conflicts.


Invalid Transaction: If another supplier modifies the same product details before confirmation,
an MVCC conflict occurs, and the transaction is rejected.
Writing Smart Contracts Using Hyperledger
Fabric
1️⃣ What is a Smart Contract in Hyperledger Fabric?
A smart contract in Hyperledger Fabric is called Chaincode. It defines the business logic that runs

📌
on the blockchain, controlling how data is stored and modified.



Key Features:
Written in Go, Java, or Node.js



Runs on endorsing peers
Implements Create, Read, Update, and Delete (CRUD) operations on the ledger
Executes only when endorsed and validated

2️⃣ Steps to Write a Smart Contract in Hyperledger Fabric


🔹
🔹
Step 1: Set Up the Environment

🔹 Install Hyperledger Fabric binaries and Docker

🔹
Use Fabric Samples (e.g., fabric-samples/chaincode)
Choose a programming language (Go, Java, Node.js)

🔹 Step 2: Define the Chaincode Structure


A smart contract must:
1️⃣Initialize the ledger
2️⃣Define transaction functions
3️⃣Implement access control if needed
📌 Example Directory Structure for Node.js Chaincode:
plaintext
CopyEdit
mychaincode/
│── package.json # Node.js dependencies
│── index.js # Smart contract logic
│── lib/
│ ├── myContract.js # Business logic
│── META-INF/ # Indexing metadata for CouchDB

🔹
📌
Step 3: Implement the Smart Contract
Example: Asset Management Smart Contract (Node.js)
'use strict';

const { Contract } = require('fabric-contract-api');

class AssetContract extends Contract {

// Initialize ledger with sample data


async initLedger(ctx) {
const assets = [
{ ID: 'A1', Name: 'Laptop', Owner: 'Alice', Value: 1000 },
{ ID: 'A2', Name: 'Car', Owner: 'Bob', Value: 5000 }
];

for (let i = 0; i < assets.length; i++) {


await ctx.stub.putState(assets[i].ID,
Buffer.from(JSON.stringify(assets[i])));
}
}

// Create a new asset


async createAsset(ctx, id, name, owner, value) {
const asset = { ID: id, Name: name, Owner: owner, Value: parseInt(value)
};
await ctx.stub.putState(id, Buffer.from(JSON.stringify(asset)));
return `Asset ${id} added successfully`;
}

// Read an asset from the ledger


async readAsset(ctx, id) {
const assetBytes = await ctx.stub.getState(id);
if (!assetBytes || assetBytes.length === 0) {
throw new Error(`Asset ${id} not found`);
}
return assetBytes.toString();
}

// Update an asset
async updateAsset(ctx, id, newOwner) {
const assetBytes = await ctx.stub.getState(id);
if (!assetBytes || assetBytes.length === 0) {
throw new Error(`Asset ${id} not found`);
}
let asset = JSON.parse(assetBytes.toString());
asset.Owner = newOwner;
await ctx.stub.putState(id, Buffer.from(JSON.stringify(asset)));
return `Asset ${id} ownership updated to ${newOwner}`;
}

// Delete an asset
async deleteAsset(ctx, id) {
await ctx.stub.deleteState(id);
return `Asset ${id} deleted successfully`;
}
}

module.exports = AssetContract;

🔹 Step 4: Deploy the Chaincode


1️⃣Package the chaincode
peer lifecycle chaincode package mychaincode.tar.gz --path ./mychaincode --lang
node --label mychaincode_1

2️⃣Install the chaincode on peers


peer lifecycle chaincode install mychaincode.tar.gz

3️⃣Approve and Commit the Chaincode


peer lifecycle chaincode approveformyorg --channelID mychannel --name
mychaincode ...
peer lifecycle chaincode commit -o orderer.example.com:7050 --channelID
mychannel --name mychaincode ...

4️⃣Invoke the Smart Contract


peer chaincode invoke -C mychannel -n mychaincode -c '{"Args":["createAsset",
"A3", "Phone", "Charlie", "700"]}'

5️⃣Query the Ledger


peer chaincode query -C mychannel -n mychaincode -c '{"Args":["readAsset",
"A3"]}'

3️⃣ Smart Contract Lifecycle


📌
✅ Steps:



Development – Write the chaincode
Packaging & Deployment – Install and approve on peers

✅ Execution – Invoke transactions via applications


Validation & Commit – Ensure endorsement and update ledger

4️⃣ Key Features of Hyperledger Fabric Smart Contracts


🔹
🔹 Stateful Transactions – Can read and modify ledger state

🔹
🔹
Pluggable Endorsement Policies – Define custom transaction approval rules
Private Data Collection – Store sensitive data securely
Event Emission – Notify external systems of important changes

5️⃣ Real-World Use Cases of Hyperledger Fabric Smart


Contracts

✅ Supply Chain – Track products from manufacturer to consumer



Healthcare – Securely store and manage patient records
Trade Finance – Automate contract execution between banks
Identity Management – Secure digital identity verification
Writing Smart Contracts Using Ethereum
Ethereum smart contracts are self-executing programs deployed on the Ethereum Virtual Machine
(EVM). They are written in Solidity, a contract-oriented programming language.

1️⃣ Prerequisites

✅ Node.js & npm – Required for development



Truffle/Hardhat – Development framework (optional but recommended)
MetaMask – Ethereum wallet for testing

✅ Remix IDE – Online Solidity editor (good for beginners)


Ganache – Local Ethereum blockchain for testing

2️⃣ Structure of a Solidity Smart Contract


A basic contract contains:
• State Variables – Store contract data
• Functions – Define logic (read, write, modify data)
• Modifiers – Restrict access
• Events – Notify off-chain applications
• Constructor – Initialize contract state

3️⃣ Writing a Simple Smart Contract (Solidity)


📌 Example: A Simple Token Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyToken {
// State variables
string public name = "MyToken";
string public symbol = "MTK";
uint8 public decimals = 18;
uint256 public totalSupply;

mapping(address => uint256) public balanceOf;

// Events
event Transfer(address indexed from, address indexed to, uint256 value);

// Constructor: Runs once when the contract is deployed


constructor(uint256 _initialSupply) {
totalSupply = _initialSupply * (10 ** uint256(decimals));
balanceOf[msg.sender] = totalSupply;
}
// Transfer function
function transfer(address _to, uint256 _value) public returns (bool success)
{
require(balanceOf[msg.sender] >= _value, "Insufficient balance");
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
}

4️⃣ Deploying the Smart Contract


🔹 Method 1: Using Remix IDE (Beginner-Friendly)
1. Open Remix IDE
2. Create a new .sol file and paste the contract code

3. Compile the contract (Solidity Compiler tab)


4. Deploy using Injected Web3 (MetaMask) or JavaScript VM
5. Test the contract by calling functions

🔹 Method 2: Using Hardhat (Recommended for Developers)


1️⃣Install Hardhat
npm install --save-dev hardhat

2️⃣Create a Hardhat Project


npx hardhat

3️⃣Write a Deployment Script (deploy.js)


const hre = require("hardhat");

async function main() {


const MyToken = await hre.ethers.getContractFactory("MyToken");
const myToken = await MyToken.deploy(1000000); // Deploy with initial supply
await myToken.deployed();
console.log("Contract deployed at:", myToken.address);
}

main().catch((error) => {
console.error(error);
process.exit(1);
});

4️⃣Deploy to a Local Blockchain


npx hardhat node
npx hardhat run scripts/deploy.js --network localhost

5️⃣Deploy to a Testnet (Goerli, Sepolia)


npx hardhat run scripts/deploy.js --network goerli

5️⃣ Interacting with the Smart Contract


Once deployed, you can interact using:

✅ Ethers.js (JavaScript library for Ethereum)

✅ Web3.js (Legacy library for DApps)

📌
MetaMask & Remix (Manual interaction)
Example: Call transfer Function Using Ethers.js
const contract = new ethers.Contract(contractAddress, abi, signer);
await contract.transfer("0xRecipientAddress", ethers.utils.parseEther("10"));

6️⃣ Real-World Use Cases of Ethereum Smart Contracts



✅ DeFi (Decentralized Finance) – Lending, staking, and trading



NFTs (Non-Fungible Tokens) – Unique digital assets
DAOs (Decentralized Autonomous Organizations) – Community governance

✅ Supply Chain – Transparent tracking of goods


Gaming – Blockchain-based in-game assets

Overview of Ripple and Corda


1️⃣ Ripple (XRP Ledger)
🔹 Ripple is a real-time gross settlement (RTGS) system, currency exchange, and remittance
network developed by Ripple Labs. It is designed for fast, low-cost cross-border payments.

🔹

Key Features of Ripple:



XRP Ledger – A decentralized blockchain for fast transactions.
RippleNet – A global payment network connecting banks and financial institutions.
Consensus Protocol – Uses a unique Byzantine Fault Tolerant (BFT) consensus (not Proof of


Work).

✅ Fast Transactions – Finality in 3-5 seconds, handling 1,500 TPS.


Low Fees – Transaction fees are a fraction of a cent.

🔹 Components of Ripple Ecosystem:


1️⃣XRP – The native cryptocurrency for liquidity and bridging assets.
2️⃣RippleNet – A network of banks & financial institutions.
3️⃣XRP Ledger (XRPL) – A decentralized public blockchain for payments.
4️⃣Interledger Protocol (ILP) – Enables transactions across different ledgers.
🔹

Ripple Use Cases:



Cross-border payments – Used by banks for international transfers.
Liquidity management – Reduces reliance on pre-funded nostro accounts.
Central Bank Digital Currencies (CBDCs) – Some governments explore XRP Ledger for
CBDCs.

2️⃣ Corda (R3 Corda)


🔹 Corda is an enterprise blockchain platform designed for financial institutions and
businesses that require secure and private transactions.

🔹

Key Features of Corda:



Permissioned Blockchain – Only authorized participants can join the network.
Not a Traditional Blockchain – Uses a Directed Acyclic Graph (DAG) instead of blocks.

✅ Smart Contracts – Uses Kotlin/Java for business logic execution.


Privacy-Oriented – Transactions are shared only between involved parties, unlike public


blockchains.
Consensus Mechanism – Uses Notary services to verify transactions.

🔹 Components of Corda:
1️⃣Corda Nodes – Each participant runs a node to communicate and execute smart contracts.
2️⃣Corda Network – A group of permissioned nodes that interact securely.
3️⃣Notary Service – Prevents double spending by verifying transactions.
4️⃣CorDapps (Corda Applications) – Custom applications built on Corda.

🔹

Corda Use Cases:



Trade Finance – Secure, private trade transactions.
Supply Chain – Tracks asset movement with privacy.

✅ Digital Identity – Verifiable identity management.


Insurance & Banking – Automates claim settlements and regulatory compliance.

3️⃣ Key Differences Between Ripple & Corda


Feature Ripple (XRP) Corda (R3 Corda)
Type Public blockchain Permissioned enterprise blockchain
Purpose Fast, low-cost payments Secure, private business transactions
Consensus Ripple Consensus Algorithm (RPCA) Notary-based consensus
Privacy Public transactions Private transactions
Smart Contracts Limited (XRP Ledger) CorDapps (Java/Kotlin)
Use Case Cross-border payments, remittances Finance, supply chain, insurance
4️⃣ Summary
🔹 Ripple is best for fast, global payments, while Corda is designed for enterprise solutions

🔹
with privacy.

🔹 Ripple uses XRP Ledger, whereas Corda operates on a permissioned DAG network.
Both aim to improve financial operations but serve different use cases.

You might also like