Creating sample Blockchain using Python, Flask and Postman

# Creating a Blockchain using Python by Dr B P Sharma

# To be installed:
# pip install Flask
# Postman HTTP Client from https://www.getpostman.com

# Importing the required libraries
import datetime
import hashlib
import json
from flask import Flask, jsonify

# Building a sample Blockchain

class Blockchain:

    def __init__(self):
        self.chain = []
        self.createBlock(proof = 1, previousHash = '0')

    def createBlock(self, proof, previousHash):
        block = {'index': len(self.chain) + 1,
                 'timestamp': str(datetime.datetime.now()),
                 'proof': proof,  #nonce
                 'previousHash': previousHash}
        self.chain.append(block)
        return block

    def getPreviousBlock(self):
        return self.chain[-1]

    def proofOfWork(self, previousProof):
        new_proof = 1
        check_proof = False
        while check_proof is False:
            hash_operation = hashlib.sha256(str(new_proof**2 - previousProof**2).encode()).hexdigest()
            if hash_operation[:4] == '0000':
                check_proof = True
            else:
                new_proof += 1
        return new_proof
 
    def hash(self, block):
        encoded_block = json.dumps(block, sort_keys = True).encode()
        return hashlib.sha256(encoded_block).hexdigest()
 
    def isChainValid(self, chain):
        previousBlock = chain[0]
        blockIndex = 1
        while blockIndex < len(chain):
            block = chain[blockIndex]
            if block['previousHash'] != self.hash(previousBlock):
                return False
            previousProof = previousBlock['proof']
            proof = block['proof']
            hash_operation = hashlib.sha256(str(proof**2 - previousProof**2).encode()).hexdigest()
            if hash_operation[:4] != '0000':
                return False
            previousBlock = block
            blockIndex += 1
        return True

# Mining the Blockchain

# Creating a Web Application using Flask
app = Flask(__name__)

# Creating a Blockchain instance
blockchain = Blockchain()

# Mining a new block
@app.route('/mineBlock', methods = ['GET'])
def mineBlock():
    previousBlock = blockchain.getPreviousBlock()
    previousProof = previousBlock['proof']
    proof = blockchain.proofOfWork(previousProof)
    previousHash = blockchain.hash(previousBlock)
    block = blockchain.createBlock(proof, previousHash)
    response = {'message': 'Congratulations, you just mined a block!',
                'index': block['index'],
                'timestamp': block['timestamp'],
                'proof': block['proof'],
                'previousHash': block['previousHash']}
    return jsonify(response), 200

# Getting the full Blockchain
@app.route('/getChain', methods = ['GET'])
def getChain():
    response = {'chain': blockchain.chain,
                'length': len(blockchain.chain)}
    return jsonify(response), 200

# Checking if the Blockchain is valid
@app.route('/isValid', methods = ['GET'])
def isValid():
    isValid = blockchain.isChainValid(blockchain.chain)
    if isValid:
        response = {'message': 'All good. The Blockchain is valid.'}
    else:
        response = {'message': 'Houston, we have a problem. The Blockchain is not valid.'}
    return jsonify(response), 200

# Running the app
app.run(host = '0.0.0.0', port = 5000)


#run the application in web browser or postman using URLs
# http://localhost:5000/getChain
# http://localhost:5000/mineBlock
# http://localhsot:5000/isValid

# Keep Learning

Comments

  1. Cryptocurrency exchange software Create your own crypto bank.
    We deliver the best cryptocurrency exchange software with latest features like Margin
    Trading, Lending, Grouping etc
    cryptocurrency exchange software.
    cryptocurrency exchange platform .
    top blockchain companies.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to import an account to geth?

Why to create a full node?