Skip to content

Instantly share code, notes, and snippets.

@ma7dev
Created November 19, 2021 06:21
Show Gist options
  • Save ma7dev/072dd4bc45ccddc1bf2c0331aa93735c to your computer and use it in GitHub Desktop.
Save ma7dev/072dd4bc45ccddc1bf2c0331aa93735c to your computer and use it in GitHub Desktop.
A blockchain made from scratch in ~50 lines
# source: https://twitter.com/PrasoonPratham/status/1461267623266635778/photo/1 (@PrasoonPratham on Twitter)
import datetime
import hashlib
class Block:
def __init__(self, data):
self.data = data
self.blockNo = 0
self.next = None
self.nonce = 0
self.previous_hash = 0x0
self.timestamp = datetime.datetime.now()
# get block hash
def hash(self):
h = hashlib.sha256()
h.update(
str(self.nonce).encode('utf-8') +
str(self.data).encode('utf-8') +
str(self.previous_hash).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.blockNo).encode('utf-8')
)
return h.hexdigest()
def __str__(self):
return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes:" + str(self.nonce) +"\n--------------"
class Blockchain:
def __init__(self):
self.diff = 20
self.maxNonce = 2**32
self.target = 2 ** (256-self.diff)
self.block = Block("Genesis")
self.dummy = self.head = self.block
# add a block
def add(self, block):
block.previous_hash = self.block.hash()
block.blockNo = self.block.blockNo + 1
self.block.next = block
self.block = self.block.next
# mine a block
def mine(self, block):
for _ in range (self.maxNonce):
if int(block.hash(), 16) <= self.target:
self.add(block)
print(block)
break
else:
block.nonce += 1
# create a blockchain
blockchain = Blockchain()
# mine 16 blocks
for n in range (16):
blockchain.mine(Block("Block " + str(n+1)))
# print the blockchain
while blockchain.head != None:
print(blockchain.head)
blockchain.head = blockchain.head.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment