BCT 1a

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

ASSIGNMENT -2

Objective: Understand the core concepts of how a blockchain works. Task: Write code
in Python or JavaScript to simulate a simple blockchain. Implement features like
block creation, adding transactions, proof-of-work (PoW), and validating the chain.
Test your blockchain by adding transactions and creating blocks. Deliverables: The
code of the blockchain. A report explaining the functionality of the blockchain.

CODE:
import hashlib
import time

# Define the Block structure


class Block:
def __init__(self, index, previous_hash, transactions, timestamp, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.transactions = transactions
self.timestamp = timestamp
self.nonce = nonce
self.hash = self.calculate_hash()

# Calculate the block's hash


def calculate_hash(self):
block_string = str(self.index) + self.previous_hash + str(self.transactions) +
str(self.timestamp) + str(self.nonce)
return hashlib.sha256(block_string.encode()).hexdigest()

# Implement proof of work (PoW) to solve the hashing puzzle


def mine_block(self, difficulty):
target = "0" * difficulty
while self.hash[:difficulty] != target:
self.nonce += 1
self.hash = self.calculate_hash()
print(f"Block mined: {self.hash}")

# Define the Blockchain structure


class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 4
self.pending_transactions = []
self.mining_reward = 100

# Create the genesis block (first block)


def create_genesis_block(self):
return Block(0, "0", [], time.time())
# Get the last block in the chain
def get_latest_block(self):
return self.chain[-1]

# Add a new transaction


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

# Mine a new block and reward the miner


def mine_pending_transactions(self, miner_address):
new_block = Block(len(self.chain), self.get_latest_block().hash,
self.pending_transactions, time.time())
new_block.mine_block(self.difficulty)
self.chain.append(new_block)
self.pending_transactions = [{'from': None, 'to': miner_address, 'amount':
self.mining_reward}] # Reward miner

# Validate the blockchain


def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True

# Test the blockchain


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

# Add transactions and mine blocks


my_coin.add_transaction({"from": "Alice", "to": "Bob", "amount": 50})
my_coin.add_transaction({"from": "Bob", "to": "Charlie", "amount": 30})

print("Mining first block...")


my_coin.mine_pending_transactions("Miner1")

my_coin.add_transaction({"from": "Charlie", "to": "Alice", "amount": 20})


print("Mining second block...")
my_coin.mine_pending_transactions("Miner1")

# Check if blockchain is valid


print(f"Is the blockchain valid? {my_coin.is_chain_valid()}")

Report on the Functionality of the Blockchain


1. Block Creation
Each block contains an index, previous block hash, list of transactions, timestamp,
and a nonce (which is used in the mining process). The block also includes a hash
calculated from these values, ensuring immutability and security.
2. Adding Transactions
Transactions are added to the list of pending transactions. When a new block is
mined, these transactions are included in the block, and the list of pending
transactions is cleared.
3. Proof of Work (PoW)
The PoW algorithm is implemented in the mine_block function. It requires the block's
hash to start with a certain number of zeroes (determined by the difficulty parameter).
The nonce is incremented until this condition is met, ensuring that mining a block
takes computational effort.
4. Chain Validation
To ensure the integrity of the blockchain, the is_chain_valid function checks two
conditions for each block:

● The hash of the block is correct.


● The previous block's hash matches the previous_hash value in the current
block.

5. Mining Reward
When a block is successfully mined, the miner is rewarded with a fixed amount of
cryptocurrency. The reward transaction is added as the first transaction in the next
block.
Testing the Blockchain
In the test section, two blocks are mined, each with a set of transactions. After mining,
the blockchain is validated to check its integrity.

You might also like