Blockchain Lab Manual
Blockchain Lab Manual
Aim:
To simulate and compare the working of Proof of Work (PoW) and Proof of Stake (PoS) consensus
mechanisms using Python in Anaconda, and understand their applications in blockchain for IoT
security.
- Python 3.x
Theory:
Blockchain is a decentralized ledger technology used in cryptocurrencies and IoT for secure and
tamper-proof transactions.
Proof of Work (PoW): A consensus mechanism where nodes (miners) solve complex mathematical
Proof of Stake (PoS): Validators are chosen based on the number of coins they hold and are willing
IoT Relevance: Blockchain ensures secure communication between IoT devices. PoS is more
Python Code:
import hashlib
import time
import random
def proof_of_work(difficulty):
prefix = '0' * difficulty
nonce = 0
start_time = time.time()
while True:
data = "IoT Data Block" + str(nonce)
hash_result = hashlib.sha256(data.encode()).hexdigest()
if hash_result.startswith(prefix):
break
nonce += 1
end_time = time.time()
print(f"Nonce: {nonce}, Hash: {hash_result}, Time: {end_time - start_time:.4f} sec")
def proof_of_stake(validators):
total_stake = sum(validators.values())
pick = random.uniform(0, total_stake)
current = 0
for validator, stake in validators.items():
current += stake
if current > pick:
print(f"Selected: {validator} with Stake: {stake}")
break
Expected Output:
Nonce: [number]
Hash: [value]
Conclusion:
PoW consumes more time and power, making it less suitable for IoT.
Viva Questions: