Created
May 19, 2022 18:19
-
-
Save allekok/d06f6d2407c712858d36144b0918dbc4 to your computer and use it in GitHub Desktop.
Blockchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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