Created
September 10, 2018 14:41
-
-
Save atomgomba/5cb235ea2b0d774be964347d85a272df to your computer and use it in GitHub Desktop.
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
from collections import namedtuple | |
from hashlib import sha256 | |
from typing import List, Optional | |
def makehash(data: str) -> str: | |
return sha256(data.encode()).hexdigest() | |
Block = namedtuple("Block", ["data", "hash", "prevhash"]) | |
class BlockChain: | |
def __init__(self): | |
self.blocks = [] # type: List[Block] | |
def add_block(self, data: str): | |
prevblock = self.blocks[-1] if self.blocks else None # type: Block | |
prevhash = "" if prevblock is None else prevblock.hash | |
newblock = Block(data, makehash(prevhash + makehash(data)), prevhash) | |
self.blocks.append(newblock) | |
if __name__ == "__main__": | |
data = ["My hovercraft is full of eels", "Frobnicating in chains", | |
"Dick Laurent is dead", "Rosebud"] | |
chain = BlockChain() | |
for i, item in enumerate(data): | |
chain.add_block(item) | |
print("block #%d: %s" % (i + 1, chain.blocks[i].hash)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment