Skip to content

Instantly share code, notes, and snippets.

@allekok
Created May 19, 2022 18:19
Show Gist options
  • Save allekok/d06f6d2407c712858d36144b0918dbc4 to your computer and use it in GitHub Desktop.
Save allekok/d06f6d2407c712858d36144b0918dbc4 to your computer and use it in GitHub Desktop.
Blockchain
import hashlib
blockchain = []
difficulty = 3
mine_pattern = '0' * difficulty
def add_block(data):
block = make_block(data)
block['prev'] = '' if blockchain == [] else blockchain[-1]['hash']
mine_block(block)
blockchain.append(block)
def make_block(data):
return {'data': data, 'nonce': 0}
def mine_block(block):
while not is_block_mined(block):
block['nonce'] += 1
block['hash'] = hash_block(block)
def is_block_mined(block):
return mine_pattern == hash_block(block)[:difficulty]
def hash_block(block):
return hash(f'{block["data"]}{block["nonce"]}{block["prev"]}')
def hash(str):
return hashlib.sha256(str.encode()).hexdigest()
# Test Blockchain
add_block('First block')
add_block('Second block')
for i in range(len(blockchain)):
print(blockchain[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment