0% found this document useful (0 votes)
8 views7 pages

Exp-2 200

Uploaded by

asmi.takle
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)
8 views7 pages

Exp-2 200

Uploaded by

asmi.takle
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/ 7

K. J.

Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

Batch: BCT-3 Roll No: 16010121200


Experiment No. 2

Title: Implementation of PoS and PoW

Objective:
Implementation of PoS and PoW

Expected Outcome of Experiment:

CO Outcome
Describe the basic concepts of Blockchain and Distributed Ledger
CO1
Technology.
Apply cryptographic hash required for Blockchain.
CO2

Books/ Journals/ Websites referred:


1. https://youtu.be/PraPZFMj6h8
2. https://brilliant.org/wiki/merkle-tree/

Abstract:
Proof of Work:
Proof of Work (PoW) is a consensus mechanism used in blockchain technology to
secure and validate transactions. It's a method that ensures that a certain amount of
computational effort is expended to add a new block to the blockchain. The concept
was popularized by Bitcoin and serves as the foundation for its security and
decentralized nature.
In a PoW system, miners compete to solve complex mathematical puzzles. The first
miner to find a solution is allowed to add a new block of transactions to the blockchain
and is rewarded with newly minted cryptocurrency and transaction fees.
The key principles of Proof of Work include:
1. Mining Competition: Miners compete against each other to solve a difficult
cryptographic puzzle. The puzzle requires significant computational power and
effort to solve.
2. Consensus Mechanism: When a miner successfully solves the puzzle, they
broadcast their solution to the network. Other participants quickly verify the
solution, and if it's correct, the new block is added to the blockchain.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 1
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

3. Difficulty Adjustment: The network automatically adjusts the difficulty of the


puzzle based on the total computational power of the network. This ensures that
blocks are added to the blockchain at a relatively constant rate, regardless of
changes in the network's computational power.
4. Security and Immutability: PoW ensures that a malicious actor would need an
immense amount of computational power to alter past transactions. Changing a
block would require redoing the work for that block and all subsequent blocks,
making it infeasible.
5. Energy Consumption: One major criticism of PoW is its energy consumption.
The computational power required for mining can lead to substantial electricity
usage, particularly in large-scale networks.
6. Decentralization: PoW promotes decentralization by allowing anyone with the
necessary hardware to participate in the network. However, over time, it has
become more difficult for individual miners to compete against mining pools.
Proof of Work has played a significant role in the development of blockchain
technology, establishing the idea of decentralized consensus and trust without relying
on intermediaries. However, due to its energy-intensive nature, there's been exploration
into more energy-efficient alternatives like Proof of Stake and other consensus
mechanisms.

Proof of Stake:
Proof of Stake (PoS) is a consensus mechanism used in blockchain technology to
validate and add new transactions to the blockchain. Unlike Proof of Work (PoW),
which relies on computational power and competition, PoS selects validators based on
the amount of cryptocurrency they hold and are willing to "stake" as collateral.
In a PoS system, validators are chosen to create new blocks based on their stake in the
network. Validators are required to lock up a certain amount of cryptocurrency as
collateral, demonstrating their commitment to the network's security and integrity. The
higher the stake, the higher the chances of being selected to validate transactions and
create new blocks.
The key principles of Proof of Stake include:
1. Staking: Validators lock up a certain amount of cryptocurrency as a stake in a
smart contract. This stake serves as collateral and indicates their commitment to
the network's proper functioning.
2. Validator Selection: Validators are chosen to create new blocks based on a
combination of factors, such as the size of their stake and a randomization
process. This avoids the energy-intensive competition seen in PoW.
3. Validation and Reward: Validators validate transactions and create new blocks.
In return, they receive transaction fees and newly minted cryptocurrency as
rewards. Validators have a financial incentive to act honestly, as their stakes are
at risk.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 2
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

4. Penalties: If a validator acts maliciously or fails to validate transactions


correctly, a portion of their stake can be slashed as a penalty. This ensures that
validators have a vested interest in maintaining the network's integrity.
5. Energy Efficiency: PoS is often considered more energy-efficient than PoW, as
it doesn't require the massive computational power associated with solving
complex puzzles. This makes PoS networks more environmentally friendly.
6. Decentralization: While PoS promotes decentralization, it's essential to maintain
a balance between large stakeholders and smaller participants to avoid
centralization of power.
7. Security: PoS networks can still achieve a high level of security by requiring
validators to lock up a significant amount of cryptocurrency, making it
financially impractical for malicious actors to attempt an attack.
Proof of Stake has gained popularity as an alternative to PoW due to its energy
efficiency and lower resource requirements. Ethereum, one of the largest blockchain
platforms, is in the process of transitioning from PoW to PoS with Ethereum 2.0 to
address scalability and environmental concerns.
Implementation Details:
PoW:
import hashlib

class Block:
def __init__(self, data, prev_hash):
self.data = data
self.prev_hash = prev_hash
self.nonce = 0
self.hash = self.calculate_hash()

def calculate_hash(self):
sha = hashlib.sha256()
sha.update(
str(self.data).encode('utf-8') +
str(self.prev_hash).encode('utf-8') +
str(self.nonce).encode('utf-8')
)
return sha.hexdigest()

def mine_block(self, difficulty):


target = '0' * difficulty
while self.hash[:difficulty] != target:
self.nonce += 1
self.hash = self.calculate_hash()

genesis_block = Block("Genesis Block", "0")


genesis_block.mine_block(1)
block1 = Block("Transaction data 1", genesis_block.hash)
block1.mine_block(2)
block2 = Block("Transaction data 2", block1.hash)
block2.mine_block(3)
block3 = Block("Transaction data 3", block2.hash)
block3.mine_block(4)
block4 = Block("Transaction data 4", block3.hash)
block4.mine_block(5)
block5 = Block("Transaction data 5", block4.hash)
block5.mine_block(6)

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 3
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

block6 = Block("Transaction data 6", block5.hash)


block6.mine_block(7)

print("Genesis Block Hash:", genesis_block.hash)


print("Block 1 Hash:", block1.hash)
print("Block 2 Hash:", block2.hash)
print("Block 3 Hash:", block3.hash)
print("Block 4 Hash:", block4.hash)
print("Block 5 Hash:", block5.hash)
print("Block 6 Hash:", block6.hash)

PoS:
import hashlib
import random

class Block:
def __init__(self, data, prev_hash):
self.data = data
self.prev_hash = prev_hash
self.validator = None
self.hash = self.calculate_hash()

def calculate_hash(self):
sha = hashlib.sha256()
sha.update(
str(self.data).encode('utf-8') +
str(self.prev_hash).encode('utf-8') +
str(self.validator).encode('utf-8')
)

return sha.hexdigest()

difficulty_level = 3 # Number of leading zeros in the target hash

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

def create_genesis_block(self):
return Block("Genesis Block", "0")

def add_block(self, new_block):


new_block.prev_hash = self.chain[-1].hash
self.chain.append(new_block)

blockchain = Blockchain()
genesis_block = blockchain.create_genesis_block()
blockchain.add_block(genesis_block)

block1 = Block("Transaction data 1", blockchain.chain[-1].hash)


block2 = Block("Transaction data 2", blockchain.chain[-1].hash)
block3 = Block("Transaction data 3", blockchain.chain[-1].hash)

blockchain.add_block(block1)
blockchain.add_block(block2)
blockchain.add_block(block3)

for block in blockchain.chain:


print("\nBlock Data:", block.data)
print("Block Hash:", block.hash)

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 4
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

Screenshots:

PoW:

PoS:

1. Enlist all the Steps followed and various options explored.

Proof of Work:

 Define a Block class with attributes: data, prev_hash, nonce, and hash.
 Implement a calculate_hash method that computes the hash of the block's
data and previous hash.
 Implement a mine_block method that simulates the PoW process by finding
a valid hash with a specified number of leading zeros.
 Define a Blockchain class with a list of blocks and methods for creating the
genesis block and adding blocks to the chain.
 Create a genesis_block and add it to the blockchain.
 Create additional blocks (block1, block2, block3), link them with the
previous block's hash, and simulate mining them using the mine_block
method.
 Print the hashes of the blocks.

Proof of Stake:

 Define a Block class with attributes: data, prev_hash, and validator.


 Implement a calculate_hash method that computes the hash of the block's
data, previous hash, and validator.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 5
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

 Define a Blockchain class with a list of blocks and methods for creating the
genesis block and adding validators and blocks to the chain.
 Create a genesis_block and add it to the blockchain.
 Add validators to the blockchain.
 Create additional blocks (block1, block2, block3), link them with the
previous block's hash, and set a validator for each block.
 Print the data, validator, and hash of each block.

2. Explain your program logic, classes and methods used.

Proof of Work:

The program simulates a basic blockchain using the PoW consensus mechanism.
The Block class represents a block with its attributes. The calculate_hash method
generates a hash based on block data, previous hash, and nonce. The mine_block
method simulates mining by finding a hash that matches the specified difficulty
level.

The Blockchain class maintains a chain of blocks. The create_genesis_block


method initializes the blockchain with a genesis block. The add_block method adds
new blocks to the chain, linking them with the previous block's hash.

Proof of Stake:

The program demonstrates a basic blockchain using the PoS consensus mechanism.
The Block class represents a block with its attributes. The calculate_hash method
generates a hash based on block data, previous hash, and validator.

The Blockchain class maintains a chain of blocks and a list of validators. The
create_genesis_block method initializes the blockchain with a genesis block. The
add_block method adds new blocks to the chain, linking them with the previous
block's hash and assigning a validator.

3. Explain the Importance of the approach followed by you.

The approach in both code examples showcases the fundamental concepts of


blockchain, PoW, and PoS in a simplified manner. While these examples don't
capture the full complexities of real-world blockchain systems, they provide a clear
understanding of how blocks are structured, linked, and mined/validated in different
consensus mechanisms.

By breaking down the logic into classes and methods, the code becomes modular
and easier to understand. This approach promotes code reusability and
maintainability, making it convenient to extend the functionality for more complex
implementations.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 6
K. J. Somaiya College of Engineering, Mumbai-77

Department of Computer Engineering

Conclusion:

Implemented both Proof of Work (PoW) and Proof of Stake (PoS) using python.

Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 7

You might also like