Inspiration
import hashlib import datetime
class Block: def init(self, data, previous_hash): self.timestamp = datetime.datetime.utcnow() self.data = data self.previous_hash = previous_hash self.hash = self.calculate_hash()
def calculate_hash(self):
hash_string = str(self.timestamp) + str(self.data) + str(self.previous_hash)
return hashlib.sha256(hash_string.encode('utf-8')).hexdigest()
class Blockchain: def init(self): self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block("Genesis Block", "0")
def get_last_block(self):
return self.chain[-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_last_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)
Tạo blockchain
my_blockchain = Blockchain()
Thêm các block vào blockchain
my_blockchain.add_block(Block("Transaction 1", "")) my_blockchain.add_block(Block("Transaction 2", "")) my_blockchain.add_block(Block("Transaction 3", ""))
In ra thông tin của từng block trong blockchain
for block in my_blockchain.chain: print("Timestamp:", block.timestamp) print("Data:", block.data) print("Previous Hash:", block.previous_hash) print("Hash:", block.hash) print("------------------------------------")
Log in or sign up for Devpost to join the conversation.