Blockchain
Blockchain
Practical 2
Implementation:
Input:
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, transactions, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.transactions = transactions
self.timestamp = int(time.time())
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
data_string = str(self.index) + self.previous_hash + str(self.transactions) + str(self.timestamp) +
str(self.nonce)
return hashlib.sha256(data_string.encode()).hexdigest()
def __str__(self):
IAR/12989 CE410P BT
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 2
def create_genesis_block(self):
return Block(0, "0", ["Genesis transaction"])
def get_latest_block(self):
return self.chain[-1]
def is_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
# Create a blockchain
blockchain = Blockchain()
Output: