0% found this document useful (0 votes)
12 views14 pages

Raj All Practical FBC Final PDF

The document provides a comprehensive overview of blockchain technology, focusing on Merkle trees, blocks, ERC-20 tokens, and decentralization. It explains the structure and functionality of these components, including their applications in cryptocurrencies like Bitcoin and Ethereum. Additionally, it discusses the benefits and challenges of decentralization in blockchain and outlines real-world use cases across various industries.

Uploaded by

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

Raj All Practical FBC Final PDF

The document provides a comprehensive overview of blockchain technology, focusing on Merkle trees, blocks, ERC-20 tokens, and decentralization. It explains the structure and functionality of these components, including their applications in cryptocurrencies like Bitcoin and Ethereum. Additionally, it discusses the benefits and challenges of decentralization in blockchain and outlines real-world use cases across various industries.

Uploaded by

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

Enrollment no.

:202202100710071
Practical : 5
Case study on a Merkle tree to understand the Blockchain with its example.

Introduction
A Merkle Tree (or hash tree) is a cryptographic structure used in blockchain technology to ensure
data integrity and efficient verification. It enables quick and secure validation of large datasets,
making it a fundamental component of blockchain implementations like Bitcoin and Ethereum.

Concept of Merkle Trees


Merkle Trees organize transactions in a hierarchical structure where:

• Leaf Nodes contain the cryptographic hash of each transaction.


• Intermediate Nodes contain the hash of concatenated child node hashes.
• Merkle Root is the final hash obtained at the top of the tree, representing the integrity of
all transactions.

Code:
import hashlib

class MerkleTree: def __init__(self,

transactions): self.transactions =

transactions self.tree = []

self.root = self.build_merkle_tree()

def hash_function(self, data):

return hashlib.sha256(data.encode()).hexdigest()

def build_merkle_tree(self):

leaves = [self.hash_function(tx) for tx in self.transactions]


self.tree.append(leaves)

while len(leaves) > 1:


Enrollment no.:202202100710071
new_level = [] for i in

range(0, len(leaves), 2): if i +

1 < len(leaves):

combined = leaves[i] + leaves[i + 1]

else:

combined = leaves[i] # Duplicate last node for odd count

new_level.append(self.hash_function(combined) leaves =

new_level self.tree.append(leaves) return leaves[0] if

leaves else None

def get_merkle_root(self):

return self.root def

get_merkle_tree(self):

return self.tree

# Example usage if

__name__ == "__main__":

transactions = ["Tx1", "Tx2", "Tx3", "Tx4"]

merkle_tree = MerkleTree(transactions) print("Merkle

Root:", merkle_tree.get_merkle_root()) print("Merkle

Tree:", merkle_tree.get_merkle_tree())

OUTPUT:

MerkleRoot:
5b260dbcbff182d10cdbd21d8cb9e4446fe71820bb91c8dced8dcfd0e8a9c8ac
Enrollment no.:202202100710071
MerkleTree:

[['55f743d0d1b9bd86bbd96a46ba4272ddde19f09e3f6e47832e34bb2779a120b5',
'80ed43f7a11b3295850dd90cc0cfc9a80334f433af8d3d88a1c5e78aff14988f',
'13288c2ba4bbc9af05aa9ccd39b0cc603dc9e30471d97565c9ef3c3604b7ca23',
'75af2038a4bcf0230372d08b917047bdcbad80e5f130061bd5b31596df174b67'],
['0971909734e9c49e0f45caeb15a450d717de387a0a27df245e7e924bb7e62b0e',
'2b4b1ceff3308595e26df24646583f4e3b38f4448c692ab80558f69fea74a3d7'],
['5b260dbcbff182d10cdbd21d8cb9e4446fe71820bb91c8dced8dcfd0e8a9c8ac']]

Explanation of the Code

1. Hashing Transactions: Each transaction is hashed using SHA-256.


2. Constructing the Tree: Pairs of hashes are combined and rehashed to form the next level.
3. Merkle Root Calculation: The process continues until a single hash (Merkle Root) is
obtained.

Use Case in Blockchain

1. Bitcoin and Merkle Trees


In Bitcoin, Merkle Trees are used in blocks to efficiently verify transactions. Instead of downloading
all transactions, lightweight nodes can verify specific transactions using Merkle Proofs without
storing the entire blockchain.

2. Efficient Data Verification


With Merkle Trees, only a small subset of the tree (Merkle Proof) is required to verify a transaction,
ensuring:

• Faster transaction validation


• Reduced storage requirements
• Improved security against tampering
Enrollment no.:202202100710071
Practical : 6

Case study a block for Blockchain to understand the Blockchain.

Introduction
A block in a blockchain is a fundamental data structure that stores transactional information
securely and immutably. Blocks are linked using cryptographic hashes, forming a chain of blocks—
hence the term blockchain.

Each block contains:

• Block Header: Metadata such as timestamp, previous block hash, and Merkle root.
• Transactions: A list of verified transactions.
• Nonce: A unique number used in the mining process.
• Hash: A unique identifier generated using the block's data.

Code:
import hashlib

import time

class Block:

def __init__(self, index, previous_hash, transactions,

timestamp=None):

self.index = index

self.previous_hash = previous_hash

self.transactions = transactions
self.timestamp = timestamp or

time.time()
Enrollment no.:202202100710071
self.nonce = 0

self.hash = self.compute_hash()

def compute_hash(self):

block_string=f"{self.index}{self.previous_ hash}

{self.transactions}{self.timestamp}{ self.nonce}"

return

hashlib.sha256(block_string.encode()).he

xdigest()

def mine_block(self, difficulty):

while self.hash[:difficulty] != "0" * difficulty

self.nonce += 1

self.hash = self.compute_hash()

print(f"Block mined: {self.hash}")


# Example usage

if __name__ == "__main__":

transactions = ["Alice pays Bob 5 BTC",

"Bob pays Charlie 2 BTC"]


Enrollment no.:202202100710071
genesis_block=Block(0,"0",transactions) print("GenesisBlockHash:",genesis_block

.hash)

new_block=Block(1,genesis_block.hash, ["Charlie

pays Dave 3 BTC"])

new_block.mine_block(difficulty=4)

print("New Block Hash:",

new_block.hash)

OUTPUT:
GenesisBlockHash:

773e98aaa966aaad5f8ae7bceec093dad4

f71856352bed4ee4e1ffe482948e0b

Blockmined:

0000d9d181e49cc8b7c04ca26f8e645ce8

d4f66f289dceba2616fdddf987b3fe
Enrollment no.:202202100710071
NewBlockHash:

0000d9d181e49cc8b7c04ca26f8e645ce8

d4f66f289dceba2616fdddf987b3fe

Explanation of the Code

1. Creating a Block: A block stores its index, previous block hash, transactions, timestamp, and
a nonce.
2. Computing Hash: The block’s hash is computed using SHA-256.
3. Mining a Block: A simple proof-of-work mechanism is implemented where the hash must
start with a certain number of leading zeros.

Structure of a Blockchain Block


Field Description
Index The position of the block in the chain
Previous Hash The hash of the previous block (ensures immutability)
Transactions A list of valid transactions stored in the block
Timestamp The time the block was created
Nonce A variable used in mining to find a valid hash
Hash A unique identifier computed using block data
Real-World Applications
1. Bitcoin and Ethereum

• Bitcoin uses blocks to store transactions securely.


• Ethereum extends blocks to include smart contract execution.

2. Supply Chain Management

• Blocks store product movement details, ensuring transparency.

3. Secure Voting Systems

• Blockchain blocks prevent election fraud by ensuring data


integrity.
Enrollment no.:202202100710071
Practical : 7

Case study on a Creating ERC20 token to understand the Blockchain.

Introduction
An ERC-20 token is a standard for fungible tokens on the Ethereum blockchain. It ensures that all
tokens follow a common interface, making them compatible with wallets, exchanges, and smart
contracts.

Key Features of ERC-20 Tokens

• Fungibility: Each token is identical in value and function.


• Interoperability: Compatible with wallets and decentralized applications (DApps).
• Smart Contracts: Automate and secure token transactions.

Understanding ERC-20 Token Standards


An ERC-20 token smart contract must implement the following functions:

Function Description
totalSupply() Returns the total supply of tokens balanceOf(address) Returns the
balance of a given address transfer(address, uint256) Transfers tokens from sender to
another address approve(address, uint256) Approves another address to spend tokens
transferFrom(address,address,

uint256) Allows an approved address to transfer tokens

Checks how many tokens an approved address can


allowance(address, address)
spend

Deploying the ERC-20 Token


To deploy the smart contract:

1. Install Solidity: Use Remix or Hardhat for development.


2. Compile the Contract: Deploy using Remix IDE or Hardhat.
3. Deploy on Ethereum: Use MetaMask and Ether to deploy on Ethereum Mainnet or Testnet
(Goerli, Sepolia).
Enrollment no.:202202100710071
Interacting with the Token
Once deployed, you can:

• Check balance: balanceOf(address)


• Transfer tokens: transfer(recipient, amount)
• Approve spending: approve(spender, amount)

Real-World Use Cases


1. DeFi (Decentralized Finance): ERC-20 tokens power lending, staking, and liquidity pools.
2. Gaming: Games use ERC-20 tokens as in-game currency.
3. Stablecoins: USDT and USDC are ERC-20 stablecoins pegged to the USD.
Enrollment no.:202202100710071
Practical : 8
Prepare a detailed case study on decentralization using Blockchain.

1. Introduction
Decentralization is a key principle of blockchain technology, removing reliance on central
authorities and enabling peer-to-peer (P2P) transactions. By distributing control and decisionmaking
across a network, decentralization enhances security, transparency, and trust.

2. Understanding Decentralization in Blockchain


Traditional systems (like banks and governments) rely on a central authority to manage
transactions, data, and decision-making. Blockchain disrupts this model by introducing:

• Distributed Ledger Technology (DLT): Every participant (node) in the network has a copy of
the ledger.
• Consensus Mechanisms: Transactions are validated through consensus (e.g., Proof-ofWork,
Proof-of-Stake).
• Cryptographic Security: Data integrity is maintained using encryption and hashing.

3. Key Benefits of Decentralization


Benefit Explanation
Security Eliminates a single point of failure, reducing cyberattack risks.
Transparency Public blockchains provide an immutable, verifiable transaction history.
Trust Removes the need for intermediaries, enabling direct peer-to-peer transactions.
Resilience Networks remain operational even if some nodes fail.
Smart contracts automate processes, reducing costs and delays. Efficiency

4. Real-World Example: Bitcoin as a Decentralized Currency How


Bitcoin Uses Decentralization

• Peer-to-Peer Transactions: No central bank or authority controls Bitcoin.


• Consensus via Proof-of-Work (PoW): Miners validate transactions and add blocks to the
chain.
• Immutable Ledger: Transactions cannot be altered once recorded.
Enrollment no.:202202100710071
Impact of Bitcoin’s Decentralization

• Financial Inclusion: Provides banking access to unbanked populations.


• Eliminates Intermediaries: No reliance on banks or payment processors.
• Borderless Transactions: Enables seamless global payments.

5. Case Study: Decentralized Finance (DeFi) What


is DeFi?
Decentralized Finance (DeFi) leverages blockchain to remove banks from financial transactions,
offering:

• Decentralized Lending & Borrowing: Platforms like Aave and Compound allow users to
lend/borrow crypto assets.
• Automated Market Makers (AMMs): Uniswap enables direct trading without
intermediaries.
• Yield Farming: Users earn rewards by providing liquidity to decentralized exchanges.

Impact of DeFi’s Decentralization

✅ No KYC or bank accounts needed


✅ Transparent and auditable smart contracts
✅ Greater financial autonomy for individuals

6. Challenges of Decentralization
Challenge Explanation
Scalability Processing transactions across a decentralized network can be slow.
Regulatory
Governments struggle to regulate decentralized systems. Uncertainty
Proof-of-Work networks (e.g., Bitcoin) require significant computational
Energy Consumption power.
User Responsibility No centralized authority means lost private keys = lost funds.

7. Future of Decentralization with Blockchain


• Web3: A decentralized internet where users control their data.
• Decentralized Identity: Users own their digital identities without reliance on big tech.
• DAOs (Decentralized Autonomous Organizations): Community-driven governance without
central leadership.
Enrollment no.:202202100710071

Practical : 9
Prepare a detailed case study on any two known implementations of
Blockchain.

1. Introduction
Blockchain technology has revolutionized industries by introducing decentralization,
transparency, and security. This case study explores two well-known blockchain implementations:

1. Bitcoin – A decentralized digital currency.


2. Ethereum – A smart contract platform enabling decentralized applications (DApps).

Both blockchains have unique use cases but share common principles of distributed ledger
technology (DLT).

2. Case Study 1: Bitcoin – The First Blockchain Implementation


Overview
Bitcoin, introduced by Satoshi Nakamoto in 2008, is the first successful blockchain
implementation. It serves as a peer-to-peer digital currency, eliminating the need for
intermediaries like banks.

How Bitcoin Works

1. Decentralized Ledger: Transactions are recorded on a public blockchain accessible to


everyone.
2. Proof-of-Work (PoW) Consensus: Miners validate transactions by solving cryptographic
puzzles.
3. Fixed Supply: Only 21 million BTC will ever exist, ensuring scarcity.
4. Immutable Transactions: Once recorded, transactions cannot be altered or deleted.

Key Components of Bitcoin’s Blockchain


Component Description
Blocks Contain transaction data and a cryptographic hash of the previous block.
Miners Compete to solve PoW puzzles and add new blocks.
Nodes Verify transactions and maintain a copy of the blockchain.
Public & Private Keys Users sign transactions using cryptographic keys.
Enrollment no.:202202100710071
Use Cases of Bitcoin

✅ Digital Gold – Store of value and hedge against inflation.


✅ Cross-Border Payments – Enables instant, low-cost transactions globally.
✅ Financial Inclusion – Allows unbanked individuals to access financial services.

Challenges of Bitcoin

❌ Scalability Issues – Limited to ~7 transactions per second (TPS).


❌ High Energy Consumption – Mining requires large computational power.
❌ Price Volatility – BTC value fluctuates significantly.

Impact of Bitcoin
Bitcoin has influenced global finance, inspiring the development of thousands of cryptocurrencies
and blockchain projects. Institutional investors and governments are now exploring Bitcoin
adoption.

3. Case Study 2: Ethereum – The Smart Contract Blockchain


Overview
Ethereum, launched by Vitalik Buterin in 2015, extends blockchain functionality beyond simple
transactions. It enables programmable smart contracts and decentralized applications (DApps).

How Ethereum Works

1. Smart Contracts: Self-executing contracts that automate agreements without


intermediaries.
2. Ethereum Virtual Machine (EVM): A decentralized computing environment for executing
smart contracts.
3. Proof-of-Stake (PoS) Consensus: Ethereum transitioned from PoW to PoS in 2022
(Ethereum 2.0) for energy efficiency.
4. ERC-20 Tokens: A standard for creating fungible tokens, used in DeFi and ICOs.

Key Components of Ethereum’s Blockchain


Component Description
Smart Contracts Code that runs on Ethereum, automating transactions.
DApps Decentralized applications without a central authority.
Ether (ETH) Native cryptocurrency used for transactions and smart contract execution.
Gas Fees Transaction fees paid in ETH for processing on the network.
Enrollment no.:202202100710071
Use Cases of Ethereum

✅ Decentralized Finance (DeFi) – Platforms like Aave, Uniswap, and Compound provide financial
services without banks.
✅ NFTs (Non-Fungible Tokens) – Ethereum powers digital ownership through ERC-721 tokens.
✅ Decentralized Autonomous Organizations (DAOs) – Community-led governance models
without central leadership.

Challenges of Ethereum

❌ High Gas Fees – Transaction fees can become expensive during network congestion.
❌ Scalability Issues – Ethereum can process ~30 TPS, leading to delays.
❌ Smart Contract Vulnerabilities – Poorly coded contracts can be exploited (e.g., DAO hack).

Impact of Ethereum
Ethereum has transformed the blockchain ecosystem, enabling innovation in DeFi, NFTs, and the
Web3 movement. The transition to PoS significantly reduced energy consumption, making
Ethereum more sustainable.

5. Bitcoin vs. Ethereum: Key Differences

Feature Bitcoin (BTC) Ethereum (ETH)


Primary Use Digital currency Smart contracts & DApps
Consensus Proof-of-Work (PoW) Proof-of-Stake (PoS)
Block Time ~10 minutes ~12-15 seconds
Transaction Speed 7 TPS 30 TPS
Token Standard Native BTC ERC-20, ERC-721 (NFTs)
Smart Contracts ❌ No ✅ Yes
Supply Cap 21 million BTC Unlimited ETH

You might also like