Sample Blockchain using Python & Flask
# 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(nonce = 1, previousHash = '0')
def createBlock(self, nonce, previousHash):
block = {'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'nonce': nonce,
'previousHash': previousHash}
self.chain.append(block)
return block
def getPreviousBlock(self):
return self.chain[-1]
def proofOfWork(self, previousnonce):
new_nonce = 1
check_nonce = False
while check_nonce is False:
hash_operation = hashlib.sha256(str(new_nonce**2 - previousnonce**2).encode()).hexdigest()
if hash_operation[:4] == '0000':
check_nonce = True
else:
new_nonce += 1
return new_nonce
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
previousnonce = previousBlock['nonce']
nonce = block['nonce']
hash_operation = hashlib.sha256(str(nonce**2 - previousnonce**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()
previousnonce = previousBlock['nonce']
nonce = blockchain.proofOfWork(previousnonce)
previousHash = blockchain.hash(previousBlock)
block = blockchain.createBlock(nonce, previousHash)
response = {'message': 'Congratulations, you just mined a block!',
'index': block['index'],
'timestamp': block['timestamp'],
'nonce': block['nonce'],
'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)
Comments
Post a Comment