import hashlib
import json
from time import time
class BDCcoinBlockchain:
def init(self):
"""Initialize the blockchain with the genesis block"""
self.chain = []
self.transactions = []
self.create_block(proof=1, previous_hash='0') # Genesis block
def create_block(self, proof, previous_hash):
"""Create a new block and add it to the chain"""
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.transactions,
'proof': proof,
'previous_hash': previous_hash
}
self.transactions = []
self.chain.append(block)
return block
def get_last_block(self):
"""Return the last block in the chain"""
return self.chain[-1]
def add_transaction(self, sender, receiver, amount):
"""Add a new transaction to the list"""
self.transactions.append({
'sender': sender,
'receiver': receiver,
'amount': amount,
'coin': 'BDCcoin'
})
return self.get_last_block()['index'] + 1
def proof_of_work(self, previous_proof):
"""
Proof of Work Algorithm:
- Find a number 'new_proof' such that hash(new_proof^2 - previous_proof^2) starts with 4 zeros
"""
new_proof = 1
while True:
hash_val = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_val[:4] == '0000':
return new_proof
new_proof += 1
def hash(self, block):
"""Create SHA-256 hash of a block"""
encoded_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
def is_chain_valid(self, chain):
"""Verify if the given blockchain is valid"""
previous_block = chain[0]
for index in range(1, len(chain)):
block = chain[index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_val = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_val[:4] != '0000':
return False
previous_block = block
return True
================================
✅ ব্যবহার (Demo Example)
================================
if name == "main":
blockchain = BDCcoinBlockchain()
# একটি লেনদেন যুক্ত করা
blockchain.add_transaction(sender='Alice', receiver='Bob', amount=100)
# ব্লক মাইন করা
previous_block = blockchain.get_last_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)
print("✅ Block mined successfully:")
print(json.dumps(block, indent=4))
import json
from time import time
class BDCcoinBlockchain:
def init(self):
"""Initialize the blockchain with the genesis block"""
self.chain = []
self.transactions = []
self.create_block(proof=1, previous_hash='0') # Genesis block
================================
✅ ব্যবহার (Demo Example)
================================
if name == "main":
blockchain = BDCcoinBlockchain()