sourav11295/Blockchain
2
1# -*- coding: utf-8 -*-2"""Blockchain.ipynb3 4Automatically generated by Colaboratory.5 6Original file is located at7 https://colab.research.google.com/drive/1wfXS6MTMX2J77EP5X1qFiKQzdo_eh5118"""9 10import datetime11import hashlib12import json13 14class Blockchain:15 16 def __init__(self):17 self.chain = []18 self.create_block(proof=1, previous_hash='0')19 20 def create_block(self, proof, previous_hash):21 block = {'index': len(self.chain) + 1,22 'timestamp': str(datetime.datetime.now()),23 'proof': proof,24 'previous_hash': previous_hash}25 self.chain.append(block)26 return block27 28 def print_previous_block(self):29 return self.chain[-1]30 31 def proof_of_work(self, previous_proof):32 new_proof = 133 check_proof = False34 35 while check_proof is False:36 hash_operation = hashlib.sha256(37 str(new_proof**2 - previous_proof**2).encode()).hexdigest()38 if hash_operation[:5] == '00000':39 check_proof = True40 else:41 new_proof += 142 43 return new_proof44 45 def hash(self, block):46 encoded_block = json.dumps(block, sort_keys=True).encode()47 return hashlib.sha256(encoded_block).hexdigest()48 49 def chain_valid(self, chain):50 previous_block = chain[0]51 block_index = 152 53 while block_index < len(chain):54 block = chain[block_index]55 if block['previous_hash'] != self.hash(previous_block):56 return False57 58 previous_proof = previous_block['proof']59 proof = block['proof']60 hash_operation = hashlib.sha256(61 str(proof**2 - previous_proof**2).encode()).hexdigest()62 63 if hash_operation[:5] != '00000':64 return False65 previous_block = block66 block_index += 167 68 return True69 70def create_chain():71 global blockchain72 blockchain = Blockchain()73 return "Chain Instantiated"74 75def del_chain():76 global blockchain77 del blockchain78 return "Chain Deleted"79 80def mine_block():81 previous_block = blockchain.print_previous_block()82 previous_proof = previous_block['proof']83 proof = blockchain.proof_of_work(previous_proof)84 previous_hash = blockchain.hash(previous_block)85 block = blockchain.create_block(proof, previous_hash)86 87 response = {'message': 'A block is MINED',88 'index': block['index'],89 'timestamp': block['timestamp'],90 'proof': block['proof'],91 'previous_hash': block['previous_hash']}92 93 return response94 95def hack_block(index,value):96 index=int(index.split(" ")[1])-197 blockchain.chain[index]['proof']=value98 return f"block modified at index:{index+1}"99 100def display_chain():101 try:102 response = {'chain': blockchain.chain,'length': len(blockchain.chain)}103 104 except:105 response = "No chain found"106 return response107 108def valid():109 valid = blockchain.chain_valid(blockchain.chain)110 111 if valid:112 response = {'message': 'The Blockchain is valid.'}113 else:114 response = {'message': 'The Blockchain is not valid.'}115 return response116 117import gradio as gr118 119with gr.Blocks(title='Blockchain Simulator') as demo:120 gr.Image(value="./Blockchain.jpg",show_label=False,shape=(1500,300))121 with gr.Row():122 with gr.Column(scale=3):123 display = gr.Textbox(label="Blockchain Output",lines=5)124 dblock = gr.Button("Display/Refresh Blockchain")125 with gr.Column(scale=2):126 cblock = gr.Button("Instantiate Blockchain")127 mblock = gr.Button("Mine a Block")128 vblock = gr.Button("Validate Blockchain")129 delblock = gr.Button("Delete Blockchain") 130 with gr.Column(scale=2):131 index = gr.Radio(choices=["index 1", "index 2", "index 3"],label="Choose an Index to hack")132 value = gr.Textbox(label="New Value", placeholder = "Enter a Value")133 hblock = gr.Button("Hack a Block")134 dblock.click(fn=display_chain, inputs=[], outputs=[display],show_progress=True)135 cblock.click(fn=create_chain, inputs=[], outputs=[display],show_progress=True)136 mblock.click(fn=mine_block, inputs=[], outputs=[display],show_progress=True)137 vblock.click(fn=valid, inputs=[], outputs=[display],show_progress=True)138 delblock.click(fn=del_chain, inputs=[], outputs=[display],show_progress=True)139 hblock.click(fn=hack_block, inputs=[index,value], outputs=[display],show_progress=True)140 141demo.launch()