Posts

Implement a simple Proof-of-Work scheme to the Minimal working blockchain

Bane Sons

import hashlib

import time


class Block:

    def __init__(self, idx, data, prev_hash, diff=4):

        self.idx = idx

        self.data = data

        self.prev_hash = prev_hash

        self.time = time.time()

        self.nonce, self.hash = self.mine(diff)


    def mine(self, diff):

        nonce = 0

        prefix = '0' * diff

        while True:

            s = f"{self.idx}{self.time}{self.data}{self.prev_hash}{nonce}"

            h = hashlib.sha256(s.encode()).hexdigest()

            if h.startswith(prefix):

                return nonce, h

            nonce += 1



class Blockchain:

    def __init__(self):

        self.chain = [Block(0, "Genesis", "0")]

        self.diff = 4


    def add(self, data):

        last = self.chain[-1]

        self.chain.append(Block(last.idx + 1, data, last.hash, self.diff))


    def show(self):

        for b in self.chain:

            print(

                f"Block {b.idx}\n"

                f"  Hash: {b.hash}\n"

                f"  Nonce: {b.nonce}\n"

                f"  Prev: {b.prev_hash}\n"

                f"  Data: {b.data}\n"

            )



# Demo

if __name__ == "__main__":

    bc = Blockchain()

    bc.add("First after genesis")

    bc.add("Second block")

    bc.add("Third block")

    bc.show()

Post a Comment