Created
April 9, 2021 18:20
-
-
Save cbscribe/2637b6cc2c0c83a90627212aae998d7d to your computer and use it in GitHub Desktop.
Blockchain example
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 | |
import json | |
from time import time | |
class Blockchain: | |
def __init__(self): | |
self.chain = [] | |
self.pending_transactions = [] | |
self.new_block(previous_hash="1234", proof=100) | |
def new_block(self, proof, previous_hash=None): | |
block = { | |
'index': len(self.chain) + 1, | |
'timestamp': time(), | |
'transactions': self.pending_transactions, | |
'proof': proof, | |
'previous_hash': previous_hash or self.hash(self.chain[-1]) | |
} | |
self.pending_transactions = [] | |
self.chain.append(block) | |
return block | |
def new_transaction(self, sender, recipient, amount): | |
transaction = { | |
'sender': sender, | |
'recipient': recipient, | |
'amount': amount | |
} | |
self.pending_transactions.append(transaction) | |
return self.last_block['index'] + 1 | |
@property | |
def last_block(self): | |
return self.chain[-1] | |
def hash(self, block): | |
string_object = json.dumps(block, sort_keys=True) | |
block_string = string_object.encode() | |
raw_hash = hashlib.sha256(block_string) | |
hex_hash = raw_hash.hexdigest() | |
return hex_hash | |
b = Blockchain() | |
t1 = b.new_transaction("Bob", "Alice", 5) | |
t2 = b.new_transaction("Alice", "Eve", 3) | |
t3 = b.new_transaction("Adam", "Bob", 5) | |
b.new_block(12345) | |
t4 = b.new_transaction("Max", "Jacob", 25) | |
t5 = b.new_transaction("Emily", "Joseph", 10) | |
t6 = b.new_transaction("Naum", "Jaden", 5) | |
b.new_block(5678) | |
from pprint import pprint | |
pprint(b.chain) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment