DEV Community

Discussion on: Trying to understand blockchain by making one!

Collapse
 
ahmed_ezzat12 profile image
Ezzat

thank you for the post it really cleared many concepts i was struggling to understand.

here is the implementation in python

first file

blockchainLib.py

import hashlib
import time

blocks = []


def encrypt_string(hash_string):
    sha_signature = \
        hashlib.sha256(hash_string.encode()).hexdigest()
    return sha_signature


def isValidhash(hash):
    if hash.startswith("0000"):
        return True
    return False


def hashBlock(data, timestamp, previoushash, index):
    _hash = ""
    nonce = 0
    while not isValidhash(_hash):
        _input = data + str(timestamp) + str(previoushash) + str(index) + str(nonce)
        _hash = encrypt_string(_input)
        nonce += 1
        print(nonce)
    blocks.append(_hash)


def getLastHash():
    return blocks[len(blocks) - 1]


def addNewBlock(mmessage):
    _index = len(blocks)
    timestamp = time.time()
    previousHash = getLastHash()
    hashBlock(mmessage, timestamp, previousHash, _index)


def getAllBlocks():
    for i in range(0, len(blocks)):
        print(blocks[i])


def initBlock():
    data = "hello world"
    timestamp = time.time()
    previoushash = 0
    index = 0
    hashBlock(data, timestamp, previoushash, index)
Enter fullscreen mode Exit fullscreen mode

the second file

main.py

#!/bin/python3


import blockchainLib as bl

if __name__ == "__main__":

    bl.initBlock()
    bl.addNewBlock("hello world")
    bl.addNewBlock("hello world 2")
    bl.getAllBlocks()
Enter fullscreen mode Exit fullscreen mode