import gradio as gr import pandas as pd import datetime import hashlib import json import os import requests from blockchain import Blockchain from mychain import MyChainSend from mychain import MyChainRec from huggingface_hub import (create_repo,get_full_repo_name,upload_file,CommitOperationAdd,HfApi) main_chain='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/chains/' main_balance='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/balance/' main_nodes='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/node_file1.json' main_pending='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/pending1.json' token_self = os.environ['HF_TOKEN'] pa=os.environ['PASS'] repo_d='Omnibus/static-bin' chain_d='chain1.json' node_file='node_file.json' space='blockchain-simulator-dev1' api = HfApi(token=token_self) ######################## BLOCKCHAIN START ############################### def bc_transactions(sender,recipient,amount): mes, out = issue_tokens(sender,recipient,amount) if out == True: blockchain.new_transaction(f"{sender}",f"{recipient}",f"{amount}") message = "Transaction Added to Pool" data = pd.DataFrame(blockchain.pending_transactions) if out == False: message = mes data = None return data,message,None,None,None def create_chain(create=None): global blockchain blockchain = Blockchain(chain_load=main_chain,create=create) #blockchain.reset(create=create) return "New Chain Created",None,display_chain() def display_chain(): response = {'chain': blockchain.chain, 'length': len(blockchain.chain)} return response def mine_block(chain_r=None,chain_n=None): previous_block = blockchain.print_previous_block() previous_proof = previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) block = blockchain.create_block(proof, previous_hash,chain_r,chain_n) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'proof': block['proof'], 'previous_hash': block['previous_hash']} message = "A block is MINED" show_chain = display_chain() if len(blockchain.chain) > 1000: blockchain.reset() response = None show_chain=display_chain() message = "New Chain Created at Max 20 Blocks" return response, show_chain,pd.DataFrame(blockchain.pending_transactions), message def sort_valid(): #nodes=main_nodes.replace("'","") f = requests.get(f'{main_nodes}') t = open('tmp.json','w') t.write(f.text) t.close() f = open('tmp.json','r') f = f.read() j = json.loads(f) #j=f.json() print (len(j)) cnt=0 valid_chains=[] not_valid=[] response='' while cnt < len(j): try: r = requests.get(f'{j[cnt]["url"]}') g = open('tmp1.json','w') g.write(r.text) g.close() gg = open('tmp1.json','r') ggg=gg.read() print (ggg) leng=len(json.loads(ggg)) print(f'Blockchain {cnt}: Length {leng} ') valid,ind,mes = blockchain.chain_valid(json.loads(ggg)) except Exception: valid=False leng="No Data" if valid: valid_chains.append({"Chain": cnt, "Length": leng}) response = f'{response} Valid: {cnt}' else: not_valid.append({"Chain": cnt, "Length": leng}) response = f'{response} Invalid:{cnt}' per = ((len(valid_chains)+1)/(len(j)+1))*100 cnt+=1 response=f'{int(per)}%-{response}' print (f'Valid: {valid_chains}') print (f'Not Valid: {not_valid}') #p = json.loads(str(valid_chains)) p = valid_chains cnt2=0 bot=0 out=[] while cnt2 < len(p): if p[cnt2]['Length'] > bot: bot = p[cnt2]['Length'] out = [cnt2,bot] else: pass cnt2+=1 print (out) return response def valid(): valid,ind,mes = blockchain.chain_valid(blockchain.chain) if valid: response = 'The Blockchain is valid.' z=True else: response = f'Blockchain is not valid. {mes} at Index {ind}' z=False return response,z def get_chain(repo_name=None,chain_name=None,token=None): if repo_name == "": repo_name = repo_d if chain_name=="": chain_name = chain_d #src = f"https://huggingface.co/spaces/{repo_name}/raw/main/{chain_name}" #ff = open('chain1.json','r') #src = ff.read() #src = json.loads(ff) try: r = requests.get(f'{main_chain}{chain_name}') #create_chain(load=r.text) global blockchain blockchain = Blockchain(chain_load=main_chain,load=r.text) #return "New Chain Created",display_chain() #create_chain(src) response = {'chain': blockchain.chain, 'length': len(blockchain.chain)} message = f"Blockchain loaded from: {main_chain}{chain_name}" return response,message except: message = f"Error loading from: {src}" return ["Error Loading Chain"],message def checkp(inp): if inp == pa: return gr.update(visible=False), gr.update(visible=True) elif inp != pa: return gr.update(visible=True), gr.update(visible=False) def add_node(this_space,repo,space,chain_file): #print(f"{api.whoami(['name'])}") #repo = f'omnibus/{space}' is_valid='True' r = requests.get(f'{main_nodes}') try: lod = json.loads(r.text) except: lod=[] pass block = {'index': len(lod) + 1, 'timestamp': str(datetime.datetime.now()), 'url': f'https://huggingface.co/datasets/{repo}/{space}/raw/main/{chain_file}', 'valid': f'{is_valid}'} lod.append(block) json_object = json.dumps(lod, indent=4) with open("tmp1.json", "w") as outfile: outfile.write(json_object) try: api.upload_file( path_or_fileobj="tmp1.json", path_in_repo=main_nodes.split('main/',1)[1], repo_id=main_nodes.split('datasets/',1)[1].split('/raw',1)[0], token=token_self, repo_type="dataset", ) os.remove("tmp1.json") except Exception as e: pass #api = HfApi(token=token) repo = main_balance.split('datasets/',1)[1].split('/raw',1)[0].split('/',1)[0] name = main_balance.split('datasets/',1)[1].split('/raw',1)[0].split('/',1)[1] f_ist = (api.list_repo_files(repo_id=f'{repo}/{name}', repo_type="dataset")) send_list =[] for i,ea in enumerate(f_ist): if "balance/" in ea: try: send_list.append(ea.split("/",1)[1].split(".",1)[0]) except Exception: pass ############################## BLOCKCHAIN END ############################### ############################## MYCHAIN START ############################### def get_my_chain_send(sender_name=None): global mychain_send try: r = requests.get(f'{main_balance}{sender_name}.json') #print (f'r={r.text}') mychain_send = MyChainSend(chain_load=main_balance,load=r.text) response = {'chain': mychain_send.chain, 'length': len(mychain_send.chain)} #print (f'response={response}') message = f"Blockchain loaded from: {main_balance}{sender_name}.json" return response,message except Exception: message = f"Error loading from: {sender_name}" return ["Error Loading Chain"],message def get_my_chain_rec(recipient_name=None): global mychain_rec try: r = requests.get(f'{main_balance}{recipient_name}.json') mychain_rec = MyChainRec(chain_load=main_balance,load=r.text) response = {'chain': mychain_rec.chain, 'length': len(mychain_rec.chain)} message = f"Blockchain loaded from: {main_balance}{recipient_name}.json" return response,message except Exception: try: mychain_rec = MyChainRec(chain_load=main_balance,create=recipient_name) response = {'chain': mychain_rec.chain, 'length': len(mychain_rec.chain)} message = f"Blockchain loaded from: {main_balance}{recipient_name}.json" return response,message except Exception: message = f"Error loading from: {recipient_name}" return ["Error Loading Chain"],message def display_chain_send(): response = {'chain': mychain_send.chain, 'length': len(mychain_send.chain)} return response def display_chain_rec(): response = {'chain': mychain_rec.chain, 'length': len(mychain_rec.chain)} return response def mychain_mine_block_send(balance, chain_r=None,chain_n=None): previous_block = mychain_send.print_previous_block() previous_proof = previous_block['proof'] proof = mychain_send.proof_of_work(previous_proof) previous_hash = mychain_send.hash(previous_block) block = mychain_send.create_block(balance, proof, previous_hash,chain_r,chain_n) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'balance': block['balance'], 'proof': block['proof'], 'previous_hash': block['previous_hash'] } message = "A block is MINED" show_chain = display_chain_send() if len(mychain_send.chain) > 1000: mychain_send.reset() response = None show_chain=display_chain_send() message = "New Chain Created at Max 20 Blocks" return response, show_chain,message def mychain_mine_block_rec(balance, chain_r=None,chain_n=None): previous_block = mychain_rec.print_previous_block() previous_proof = previous_block['proof'] proof = mychain_rec.proof_of_work(previous_proof) previous_hash = mychain_rec.hash(previous_block) block = mychain_rec.create_block(balance, proof, previous_hash,chain_r,chain_n) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'balance': block['balance'], 'proof': block['proof'], 'previous_hash': block['previous_hash'] } message = "A block is MINED" show_chain = display_chain_rec() if len(mychain_rec.chain) > 1000: mychain_rec.reset() response = None show_chain=display_chain_rec() message = "New Chain Created at Max 20 Blocks" return response, show_chain, message def issue_tokens(send,rec,amount): response_send={} response_rec={} show_chain_send={} show_chain_rec={} data_send=None data_rec=None message_send=None message_rec=None #print(f"CURRENT USER:: {api.whoami(['name'])}") #repo = f'omnibus/{space}' #is_valid='True' balance_send = 0 balance_rec = 0 try: _,z=valid() if z == True: mes = None try: response,message = get_my_chain_send(send) print (f'response:{response}::message{message}') #r = requests.get(f'{main_balance}{send}.json') lod=response #lod = json.loads(response) #print (lod) p=True except Exception as e: lod=[] p=False mes = f"Sender has no wallet {e}" pass if p==True: try: #if lod["chain"][-1]["index"] > 1: balance = lod["chain"][-1]["balance"] #if lod["chain"][-1]["index"] == 1: # balance = 0 except Exception: balance = 0 p=False print (balance) balance_send =int(balance)-int(amount) if balance_send >=0: p=True response,message = get_my_chain_rec(rec) #lod_rec = json.loads(response) lod_rec = response try: if lod_rec["chain"][-1]["index"] > 1: balance = lod_rec[-1]["balance"] if lod_rec["chain"][-1]["index"] == 1: balance = 0 except Exception: p=False try: if lod_rec["chain"][0]["index"] > 1: balance = lod_rec[0]["balance"] if lod_rec["chain"][0]["index"] == 1: balance = 0 p=True except Exception: p=False balance_rec =int(balance)+int(amount) if balance_send < 0: mes ="Not enough tokens" p = False if z==False: mes = "Invalid Blockchain" p=False except Exception as e: mes = f"Blockchain not loaded? {e}" p=False if p==True: mychain_send.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_send}") message_send = "Transaction Added to Pool" data_send = pd.DataFrame(mychain_send.pending_transactions) mychain_rec.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_rec}") message_rec = "Transaction Added to Pool" data_rec = pd.DataFrame(mychain_rec.pending_transactions) response_send, show_chain_send, message_send = mychain_mine_block_send(balance_send, chain_r=None,chain_n=send) response_rec, show_chain_rec, message_rec = mychain_mine_block_rec(balance_rec, chain_r=None,chain_n=rec) mes = (f'Send: {message_send} :: Recieve: {message_rec}') return (mes, p, response_send, response_rec, show_chain_send, show_chain_rec, data_send, data_rec, message_send, message_rec) #return (mes, p, response_send) ############################## MYCHAIN END ############################### def res_source(): block = {'index': 1, 'timestamp': str(datetime.datetime.now()), 'transactions': [], 'balance': 10000000000000000000, 'proof': 1, 'previous_hash': 0} pending_transactions_x = [] pending_transactions_x.append(block) json_object = json.dumps(pending_transactions_x, indent=4) with open("tmp_send.json", "w") as outfile: outfile.write(json_object) try: api.upload_file( path_or_fileobj="tmp_send.json", path_in_repo="balance/__Source__.json", repo_id=main_balance.split('datasets/',1)[1].split('/raw',1)[0], token=token_self, repo_type="dataset", ) os.remove("tmp_send.json") return "__Source__ Reset" except Exception as e: return e with gr.Blocks() as bc: with gr.Row(visible=True) as invalid: pass_box = gr.Textbox() pass_btn = gr.Button() with gr.Box(visible=False) as valida: gr.Markdown("""