Skip to content

Instantly share code, notes, and snippets.

@aglove2189
Last active April 3, 2024 19:57
Show Gist options
  • Save aglove2189/01cc7cd2995182a3d7810de8c850bcbd to your computer and use it in GitHub Desktop.
Save aglove2189/01cc7cd2995182a3d7810de8c850bcbd to your computer and use it in GitHub Desktop.
barebones blockchain example
import hashlib
import time
class Block:
def __init__(self, data, previous_hash=None):
self.data = data
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()
def calculate_hash(self):
data = str(self.data) + str(self.previous_hash) + str(self.nonce)
return hashlib.sha256(data.encode()).hexdigest()
def mine_block(self, difficulty):
start_time = time.time()
while self.hash[0:difficulty] != "0" * difficulty:
self.hash = self.calculate_hash()
print(f"Mining... {self.nonce=:,} {self.hash=}")
self.nonce += 1
print(f"Block mined in {int(self.nonce / (time.time() - start_time)):,} H/s")
def __repr__(self):
return f"{self.__class__.__name__}({self.previous_hash=}, {self.nonce=:,}, {self.data=})"
class Blockchain(list):
def __init__(self):
super().__init__([Block("Genesis Block", "0")])
def add_block(self, new_block, difficulty=4):
new_block.previous_hash = self[-1].hash
new_block.mine_block(difficulty)
self.append(new_block)
if __name__ == "__main__":
blockchain = Blockchain()
blockchain.add_block(Block(["Create 2,171,879,003 coins"]))
print("\033[92m", *blockchain, "\033[0m", sep="\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment