Omnibus commited on
Commit
7014d23
·
1 Parent(s): de56fac

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +694 -0
app.py ADDED
@@ -0,0 +1,694 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import datetime
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import requests
8
+ from mychain import Blockchain
9
+ from mychain import MyChainSend
10
+ from mychain import MyChainRec
11
+ from mychain import MyChainTrans
12
+
13
+ from huggingface_hub import (create_repo,get_full_repo_name,upload_file,CommitOperationAdd,HfApi)
14
+
15
+ main_chain='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/chains/'
16
+ main_balance='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/balance/'
17
+ main_trans='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/transact/'
18
+
19
+ main_nodes='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/node_file1.json'
20
+ main_pending='https://huggingface.co/datasets/Omnibus/blockchain-sim/raw/main/pending1.json'
21
+ token_self = os.environ['HF_TOKEN']
22
+ pa=os.environ['PASS']
23
+
24
+ trans_name = 'trans1.json'
25
+ repo_d='Omnibus/static-bin'
26
+ chain_d='chain1.json'
27
+ node_file='node_file.json'
28
+ space='blockchain-simulator-dev1'
29
+ api = HfApi(token=token_self)
30
+
31
+
32
+
33
+ ######################## BLOCKCHAIN START ###############################
34
+
35
+ def bc_transactions(block):
36
+ #mes, out = issue_tokens(sender,recipient,amount)
37
+ print (f'block:: {block}')
38
+ try:
39
+ blockchain.new_transaction(block)
40
+ message = "Transaction Added to Pool"
41
+ data = pd.DataFrame(blockchain.trans_data_out)
42
+ except Exception as e:
43
+ message = e
44
+ data = None
45
+ return data,message
46
+
47
+ def create_chain(create=None):
48
+ global blockchain
49
+ blockchain = Blockchain(chain_load=main_chain,create=create)
50
+ #blockchain.reset(create=create)
51
+ return "New Chain Created",None,display_chain()
52
+
53
+ def display_chain():
54
+ response = {'chain': blockchain.chain,
55
+ 'length': len(blockchain.chain)}
56
+ return response
57
+
58
+ def mine_block(chain_r=None,chain_n=None):
59
+ if chain_n=="":
60
+ chain_n = chain_d
61
+ previous_block = blockchain.print_previous_block()
62
+ previous_proof = previous_block['proof']
63
+ proof = blockchain.proof_of_work(previous_proof)
64
+ previous_hash = blockchain.hash(previous_block)
65
+ block = blockchain.create_block(proof, previous_hash,chain_r,chain_n)
66
+
67
+ response = {'message': 'A block is MINED',
68
+ 'index': block['index'],
69
+ 'timestamp': block['timestamp'],
70
+ 'proof': block['proof'],
71
+ 'previous_hash': block['previous_hash']}
72
+ message = "A block is MINED"
73
+ show_chain = display_chain()
74
+ if len(blockchain.chain) > 1000:
75
+ blockchain.reset()
76
+ response = None
77
+ show_chain=display_chain()
78
+ message = "New Chain Created at Max 20 Blocks"
79
+ return response, show_chain,pd.DataFrame(blockchain.pending_transactions), message
80
+
81
+ def sort_valid():
82
+ #nodes=main_nodes.replace("'","")
83
+ f = requests.get(f'{main_nodes}')
84
+ t = open('tmp.json','w')
85
+ t.write(f.text)
86
+ t.close()
87
+ f = open('tmp.json','r')
88
+ f = f.read()
89
+ j = json.loads(f)
90
+ #j=f.json()
91
+ print (len(j))
92
+ cnt=0
93
+ valid_chains=[]
94
+ not_valid=[]
95
+ response=''
96
+ while cnt < len(j):
97
+ try:
98
+ r = requests.get(f'{j[cnt]["url"]}')
99
+ g = open('tmp1.json','w')
100
+ g.write(r.text)
101
+ g.close()
102
+ gg = open('tmp1.json','r')
103
+ ggg=gg.read()
104
+ print (ggg)
105
+ leng=len(json.loads(ggg))
106
+ print(f'Blockchain {cnt}: Length {leng} ')
107
+ valid,ind,mes = blockchain.chain_valid(json.loads(ggg))
108
+
109
+ except Exception:
110
+ valid=False
111
+ leng="No Data"
112
+ if valid:
113
+ valid_chains.append({"Chain": cnt, "Length": leng})
114
+ response = f'{response} Valid: {cnt}'
115
+ else:
116
+ not_valid.append({"Chain": cnt, "Length": leng})
117
+ response = f'{response} Invalid:{cnt}'
118
+
119
+ per = ((len(valid_chains)+1)/(len(j)+1))*100
120
+ cnt+=1
121
+ response=f'{int(per)}%-{response}'
122
+ print (f'Valid: {valid_chains}')
123
+ print (f'Not Valid: {not_valid}')
124
+ #p = json.loads(str(valid_chains))
125
+ p = valid_chains
126
+ cnt2=0
127
+ bot=0
128
+ out=[]
129
+ while cnt2 < len(p):
130
+ if p[cnt2]['Length'] > bot:
131
+ bot = p[cnt2]['Length']
132
+ out = [cnt2,bot]
133
+ else:
134
+ pass
135
+ cnt2+=1
136
+ print (out)
137
+ return response
138
+
139
+ def valid():
140
+ valid,ind,mes = blockchain.chain_valid(blockchain.chain)
141
+ if valid:
142
+ response = 'The Blockchain is valid.'
143
+ z=True
144
+ else:
145
+ response = f'Blockchain is not valid. {mes} at Index {ind}'
146
+ z=False
147
+ return response,z
148
+
149
+ def get_chain(repo_name=None,chain_name=None,token=None):
150
+ if repo_name == "":
151
+ repo_name = repo_d
152
+ if chain_name=="":
153
+ chain_name = chain_d
154
+ try:
155
+ r = requests.get(f'{main_chain}{chain_name}')
156
+ #create_chain(load=r.text)
157
+ global blockchain
158
+ blockchain = Blockchain(chain_load=main_chain,load=r.text)
159
+ response = {'chain': blockchain.chain,
160
+ 'length': len(blockchain.chain)}
161
+ message = f"Blockchain loaded from: {main_chain}{chain_name}"
162
+ return response,message
163
+ except:
164
+ message = f"Error loading from: {src}"
165
+ return ["Error Loading Chain"],message
166
+ def checkp(inp):
167
+ if inp == pa:
168
+ return gr.update(visible=False), gr.update(visible=True)
169
+ elif inp != pa:
170
+ return gr.update(visible=True), gr.update(visible=False)
171
+ def add_node(this_space,repo,space,chain_file):
172
+ #print(f"{api.whoami(['name'])}")
173
+ #repo = f'omnibus/{space}'
174
+ is_valid='True'
175
+ r = requests.get(f'{main_nodes}')
176
+ try:
177
+ lod = json.loads(r.text)
178
+ except:
179
+ lod=[]
180
+ pass
181
+ block = {'index': len(lod) + 1,
182
+ 'timestamp': str(datetime.datetime.now()),
183
+ 'url': f'https://huggingface.co/datasets/{repo}/{space}/raw/main/{chain_file}',
184
+ 'valid': f'{is_valid}'}
185
+ lod.append(block)
186
+
187
+ json_object = json.dumps(lod, indent=4)
188
+ with open("tmp1.json", "w") as outfile:
189
+ outfile.write(json_object)
190
+ try:
191
+ api.upload_file(
192
+ path_or_fileobj="tmp1.json",
193
+ path_in_repo=main_nodes.split('main/',1)[1],
194
+ repo_id=main_nodes.split('datasets/',1)[1].split('/raw',1)[0],
195
+ token=token_self,
196
+ repo_type="dataset",
197
+ )
198
+ os.remove("tmp1.json")
199
+
200
+ except Exception as e:
201
+ pass
202
+
203
+
204
+
205
+ #api = HfApi(token=token)
206
+ repo = main_balance.split('datasets/',1)[1].split('/raw',1)[0].split('/',1)[0]
207
+ name = main_balance.split('datasets/',1)[1].split('/raw',1)[0].split('/',1)[1]
208
+
209
+
210
+
211
+
212
+ ############################## BLOCKCHAIN END ###############################
213
+ ############################## MYCHAIN START ###############################
214
+
215
+
216
+
217
+ def get_my_chain_send(sender_name=None):
218
+ global mychain_send
219
+ global mychain_trans
220
+ mes_error = ""
221
+ try:
222
+ r = requests.get(f'{main_balance}{sender_name}.json')
223
+
224
+ #print (f'r={r.text}')
225
+ mychain_send = MyChainSend(chain_load=main_balance,load=r.text)
226
+
227
+ response = {'chain': mychain_send.chain,
228
+ 'length': len(mychain_send.chain)}
229
+ #print (f'response={response}')
230
+ try:
231
+ d = requests.get(f'{main_trans}{trans_name}')
232
+ mychain_trans = MyChainTrans(chain_load=main_trans,load=d.text)
233
+ except Exception as e:
234
+ print (f'error1:: {e}')
235
+ try:
236
+ mychain_trans = MyChainTrans(chain_load=main_trans,create=trans_name)
237
+ print ("this worked")
238
+ except Exception as ee:
239
+ print (f'error2:: {ee}')
240
+ pass
241
+ try:
242
+ response_trans = {'chain': mychain_trans.chain,
243
+ 'length': len(mychain_trans.chain)}
244
+ print(f'response_trans:: {response_trans}')
245
+ except Exception as e:
246
+ print (e)
247
+ pass
248
+
249
+ message = f"Blockchain loaded from: {main_balance}{sender_name}.json"
250
+ return response,message
251
+ except Exception:
252
+ message = f"Error loading from: {sender_name}"
253
+ print (message)
254
+ return ["Error Loading Chain"],message
255
+
256
+ def get_my_chain_rec(recipient_name=None):
257
+ global mychain_rec
258
+
259
+ try:
260
+ r = requests.get(f'{main_balance}{recipient_name}.json')
261
+ mychain_rec = MyChainRec(chain_load=main_balance,load=r.text)
262
+ response = {'chain': mychain_rec.chain,
263
+ 'length': len(mychain_rec.chain)}
264
+ message = f"Blockchain loaded from: {main_balance}{recipient_name}.json"
265
+ return response,message
266
+ except Exception:
267
+ try:
268
+ mychain_rec = MyChainRec(chain_load=main_balance,create=recipient_name)
269
+ response = {'chain': mychain_rec.chain,
270
+ 'length': len(mychain_rec.chain)}
271
+
272
+ message = f"Blockchain loaded from: {main_balance}{recipient_name}.json"
273
+ return response,message
274
+ except Exception:
275
+ message = f"Error loading from: {recipient_name}"
276
+ return ["Error Loading Chain"],message
277
+
278
+ def display_chain_send():
279
+ response = {'chain': mychain_send.chain,
280
+ 'length': len(mychain_send.chain)}
281
+ return response
282
+
283
+ def display_chain_rec():
284
+ response = {'chain': mychain_rec.chain,
285
+ 'length': len(mychain_rec.chain)}
286
+ return response
287
+
288
+ def valid_send():
289
+ valid,ind,mes = mychain_send.chain_valid(mychain_send.chain)
290
+ if valid:
291
+ response = 'The Blockchain is valid.'
292
+ z=True
293
+ else:
294
+ response = f'Sender Blockchain is not valid. {mes} at Index {ind}'
295
+ z=False
296
+ return response,z,mes,ind
297
+
298
+ def valid_rec():
299
+ valid,ind,mes = mychain_rec.chain_valid(mychain_rec.chain)
300
+ if valid:
301
+ response = 'The Blockchain is valid.'
302
+ z=True
303
+ else:
304
+ response = f'Blockchain is not valid. {mes} at Index {ind}'
305
+ z=False
306
+ return response,z, mes, ind
307
+
308
+
309
+
310
+ def mychain_mine_block_send(balance, chain_r=None,chain_n=None):
311
+ previous_block = mychain_send.print_previous_block()
312
+ previous_proof = previous_block['proof']
313
+ proof = mychain_send.proof_of_work(previous_proof)
314
+ previous_hash = mychain_send.hash(previous_block)
315
+ block = mychain_send.create_block(balance, proof, previous_hash,len(blockchain.chain)+1,chain_r,chain_n)
316
+
317
+ response = {'message': 'A block is MINED',
318
+ 'index': block['index'],
319
+ 'timestamp': block['timestamp'],
320
+ 'balance': block['balance'],
321
+ 'proof': block['proof'],
322
+ 'previous_hash': block['previous_hash']
323
+ }
324
+
325
+ message = "A block is MINED"
326
+ show_chain = display_chain_send()
327
+
328
+ if len(mychain_send.chain) > 1000:
329
+ mychain_send.reset()
330
+ response = None
331
+ show_chain=display_chain_send()
332
+ message = "New Chain Created at Max 20 Blocks"
333
+
334
+ return response, show_chain,message
335
+
336
+ def mychain_mine_block_trans(balance, chain_r=None,chain_n=None):
337
+ previous_block = mychain_trans.print_previous_block()
338
+ previous_proof = previous_block['proof']
339
+ proof = mychain_trans.proof_of_work(previous_proof)
340
+ previous_hash = mychain_trans.hash(previous_block)
341
+ block = mychain_trans.create_block(balance, proof, previous_hash,len(blockchain.chain)+1,chain_r,chain_n)
342
+
343
+ response = {'message': 'A block is MINED',
344
+ 'index': block['index'],
345
+ 'timestamp': block['timestamp'],
346
+ 'balance': block['balance'],
347
+ 'proof': block['proof'],
348
+ 'previous_hash': block['previous_hash']
349
+ }
350
+
351
+ message = "A block is MINED"
352
+ show_chain = display_chain_send()
353
+
354
+ if len(mychain_trans.chain) > 1000:
355
+ mychain_trans.reset()
356
+ response = None
357
+ show_chain=display_chain_send()
358
+ message = "New Chain Created at Max 20 Blocks"
359
+
360
+ return response, show_chain,message
361
+
362
+
363
+
364
+ def mychain_mine_block_rec(balance, chain_r=None,chain_n=None):
365
+ previous_block = mychain_rec.print_previous_block()
366
+ previous_proof = previous_block['proof']
367
+ proof = mychain_rec.proof_of_work(previous_proof)
368
+ previous_hash = mychain_rec.hash(previous_block)
369
+ block = mychain_rec.create_block(balance, proof, previous_hash,len(blockchain.chain)+1,chain_r,chain_n)
370
+
371
+ response = {'message': 'A block is MINED',
372
+ 'index': block['index'],
373
+ 'timestamp': block['timestamp'],
374
+ 'balance': block['balance'],
375
+ 'proof': block['proof'],
376
+ 'previous_hash': block['previous_hash']
377
+ }
378
+ message = "A block is MINED"
379
+ show_chain = display_chain_rec()
380
+ if len(mychain_rec.chain) > 1000:
381
+ mychain_rec.reset()
382
+ response = None
383
+ show_chain=display_chain_rec()
384
+ message = "New Chain Created at Max 20 Blocks"
385
+ return response, show_chain, message
386
+
387
+ def merge_trans():
388
+ trans_bx = []
389
+ previous_post_send = mychain_send.print_previous_block()
390
+ previous_post_rec = mychain_rec.print_previous_block()
391
+
392
+ send_block = {
393
+ 'role': 'Sender',
394
+ 'name': previous_post_send['transactions'][0]['sender'],
395
+ 'index': previous_post_send['index'],
396
+ 'timestamp': previous_post_send['timestamp'],
397
+ 'recipient': previous_post_send['transactions'][0]['recipient'],
398
+ 'amount': previous_post_send['transactions'][0]['amount'],
399
+ 'balance': previous_post_send['balance'],
400
+ 'proof': previous_post_send['proof'],
401
+ 'previous_hash': previous_post_send['previous_hash'],
402
+ 'block': len(blockchain.chain)+1}
403
+ rec_block = {
404
+ 'role': 'Recipient',
405
+ 'name': previous_post_rec['transactions'][0]['recipient'],
406
+ 'index': previous_post_rec['index'],
407
+ 'timestamp': previous_post_rec['timestamp'],
408
+ 'sender': previous_post_rec['transactions'][0]['sender'],
409
+ 'amount': previous_post_rec['transactions'][0]['amount'],
410
+ 'balance': previous_post_rec['balance'],
411
+ 'proof': previous_post_rec['proof'],
412
+ 'previous_hash': previous_post_rec['previous_hash'],
413
+ 'block': len(blockchain.chain)+1}
414
+
415
+ trans_bx.append(send_block)
416
+ trans_bx.append(rec_block)
417
+ return trans_bx
418
+
419
+
420
+
421
+
422
+ def issue_tokens(send,rec,amount):
423
+ response_send={}
424
+ response_rec={}
425
+ show_chain_send={}
426
+ show_chain_rec={}
427
+ data_send=None
428
+ data_rec=None
429
+ rec_send=None
430
+ rec_drop=None
431
+ message_send=None
432
+ message_rec=None
433
+ trans_data=None
434
+ trans_mes=None
435
+ balance_send = 0
436
+ balance_rec = 0
437
+ mes = "blank message"
438
+ try:
439
+ b_mes,z=valid()
440
+ if z == True:
441
+ try:
442
+ response,message = get_my_chain_send(send)
443
+ #print (f'response:{response}::message{message}')
444
+ #r = requests.get(f'{main_balance}{send}.json')
445
+ lod=response
446
+ #lod = json.loads(response)
447
+ #print (lod)
448
+ p=True
449
+ except Exception as e:
450
+ lod=[]
451
+ p=False
452
+ mes = f"Sender has no wallet {e}"
453
+ pass
454
+ mes1,val,mes2,ind = valid_send()
455
+ print (f'val:: {val}')
456
+ if val == False:
457
+ p=False
458
+ mes = f"Sender: {send} Blockchain is not valid. {mes2} at Index {ind}"
459
+ #mes = "Blockchain is not valid."
460
+
461
+ #if val == True:
462
+ if p==True:
463
+ try:
464
+ balance = lod["chain"][-1]["balance"]
465
+ except Exception:
466
+ balance = 0
467
+ p=False
468
+ #print (balance)
469
+ balance_send =int(balance)-int(amount)
470
+ if balance_send >=0:
471
+ p=True
472
+ response,message = get_my_chain_rec(rec)
473
+ lod_rec = response
474
+ mes1,val,mes2,ind = valid_rec()
475
+ print (f'val:: {val}')
476
+ if val == False:
477
+ p=False
478
+ mes = f"Recipient: {rec} Blockchain is not valid. {mes2} at Index {ind}"
479
+ #mes = "Blockchain is not valid."
480
+ #print (lod_rec)
481
+ if val == True:
482
+ try:
483
+ balance = lod_rec["chain"][-1]["balance"]
484
+ #print (balance)
485
+ except Exception:
486
+ p=False
487
+ balance = 0
488
+ balance_rec =int(balance)+int(amount)
489
+
490
+ if balance_send < 0:
491
+ mes ="Not enough tokens"
492
+ p = False
493
+
494
+ print(mes)
495
+
496
+ if z==False:
497
+ mes = b_mes
498
+ p=False
499
+ except Exception as e:
500
+ mes = f"Blockchain not loaded? {e}"
501
+ p=False
502
+ print (mes)
503
+
504
+ if p==False:
505
+ return (mes, p,None,None,None,None,None,None,None,None,None,None,None)
506
+
507
+ #return (mes, p,{},{},{},{},{},{},None,None,None,None,{})
508
+ #json, json, json, json, dataframe, dataframe, textbox, textbox, dropdown, dropdown, dataframe
509
+ if p==True:
510
+
511
+
512
+ mychain_send.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_send}")
513
+ mychain_trans.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_send}")
514
+
515
+ message_send = "Transaction Added to Pool"
516
+ data_send = pd.DataFrame(mychain_send.pending_transactions)
517
+ mychain_rec.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_rec}")
518
+ message_rec = "Transaction Added to Pool"
519
+ data_rec = pd.DataFrame(mychain_rec.pending_transactions)
520
+ response_send, show_chain_send, message_send = mychain_mine_block_send(balance_send, chain_r=None,chain_n=send)
521
+
522
+ mychain_mine_block_trans(balance_send, chain_r=None,chain_n=send)
523
+
524
+ response_rec, show_chain_rec, message_rec = mychain_mine_block_rec(balance_rec, chain_r=None,chain_n=rec)
525
+ mes = (f'Send: {message_send} :: Recieve: {message_rec}')
526
+ _,rec_send=update_send_list()
527
+ _,rec_drop=update_rec_list()
528
+ trans_bx = merge_trans()
529
+ trans_data, mes = bc_transactions(trans_bx)
530
+ return (mes, p, response_send, response_rec, show_chain_send, show_chain_rec, data_send, data_rec, message_send, message_rec, rec_send, rec_drop,trans_data)
531
+
532
+
533
+
534
+
535
+ ############################## MYCHAIN END ###############################
536
+
537
+ def res_source():
538
+ block = {'index': 1,
539
+ 'timestamp': str(datetime.datetime.now()),
540
+ 'transactions': [],
541
+ 'balance': 10000000000000000000,
542
+ 'proof': 1,
543
+ 'previous_hash': 0}
544
+
545
+ pending_transactions_x = []
546
+ pending_transactions_x.append(block)
547
+ json_object = json.dumps(pending_transactions_x, indent=4)
548
+ with open("tmp_send.json", "w") as outfile:
549
+ outfile.write(json_object)
550
+ try:
551
+ api.upload_file(
552
+ path_or_fileobj="tmp_send.json",
553
+ path_in_repo="balance/__Source__.json",
554
+ repo_id=main_balance.split('datasets/',1)[1].split('/raw',1)[0],
555
+ token=token_self,
556
+ repo_type="dataset",
557
+ )
558
+ os.remove("tmp_send.json")
559
+ return "__Source__ Reset"
560
+ except Exception as e:
561
+ return e
562
+
563
+
564
+ def update_send_list():
565
+ f_ist = (api.list_repo_files(repo_id=f'{repo}/{name}', repo_type="dataset"))
566
+ send_list =[]
567
+ for i,ea in enumerate(f_ist):
568
+ if "balance/" in ea:
569
+ try:
570
+ send_list.append(ea.split("/",1)[1].split(".",1)[0])
571
+ except Exception:
572
+ pass
573
+ return send_list, gr.Dropdown.update(label="Sender", choices=[f for f in send_list])
574
+ send_list,send_drop = update_send_list()
575
+
576
+ def update_rec_list():
577
+ f_ist = (api.list_repo_files(repo_id=f'{repo}/{name}', repo_type="dataset"))
578
+ rec_list =[]
579
+ for i,ea in enumerate(f_ist):
580
+ if "balance/" in ea:
581
+ try:
582
+ if not "__Source__" in ea:
583
+ rec_list.append(ea.split("/",1)[1].split(".",1)[0])
584
+ except Exception:
585
+ pass
586
+ return rec_list, gr.Dropdown.update(label="Recipient", choices=[f for f in rec_list])
587
+ rec_list, rec_drop = update_rec_list()
588
+
589
+ with gr.Blocks() as bc:
590
+ with gr.Row(visible=True) as invalid:
591
+ pass_box = gr.Textbox()
592
+ pass_btn = gr.Button()
593
+
594
+ with gr.Box(visible=False) as valida:
595
+ gr.Markdown("""<h1><center>Blockchain Simulator<br><h3>(Transactions have no value)<br><h4>Chain will reset at 20 blocks""")
596
+ blockchain = gr.State()
597
+ with gr.Row():
598
+ with gr.Column():
599
+ with gr.Accordion(label="Load",open=False):
600
+ with gr.Row():
601
+ chain_repo=gr.Textbox(label="repo/name")
602
+ chain_n=gr.Textbox(label="Chain file")
603
+ with gr.Row():
604
+ in_chain_btn=gr.Button("Load Chain")
605
+ create_bc = gr.Button("Create New Blockchain")
606
+ #send=gr.Textbox(label="Sender")
607
+ send = gr.Dropdown(label="Sender", choices=[f for f in send_list], value = "Bank")
608
+ rec=gr.Dropdown(label="Recipient", choices=[f for f in rec_list], allow_custom_value=True)
609
+ am=gr.Textbox(label="Amount")
610
+ send_trans=gr.Button("Post Transaction")
611
+ mine_b = gr.Button("Mine Block")
612
+ check = gr.Button("Check Chain")
613
+ check_trans = gr.Button("Check Transactions")
614
+ check_all = gr.Button("Check All")
615
+ with gr.Column():
616
+ block_text = gr.Textbox()
617
+ trans_data = gr.Dataframe()
618
+ json_out = gr.JSON()
619
+ chain_json = gr.JSON()
620
+ with gr.Accordion("Nodes", open=False):
621
+ with gr.Row():
622
+ this_space=gr.Textbox(label="This Repo/Space")
623
+ with gr.Row():
624
+ node_repo=gr.Textbox(label="Node Repo")
625
+ node_space=gr.Textbox(label="Node Space")
626
+ node_file=gr.Textbox(label="Node File")
627
+ node_add=gr.Button("Add Node")
628
+ with gr.Accordion("Tokens", open=False):
629
+ with gr.Row():
630
+ with gr.Column():
631
+ issue_btn=gr.Button()
632
+ with gr.Column():
633
+ with gr.Row():
634
+ reset_blockchain=gr.Button("Reset Main Blockchain")
635
+ reset_source=gr.Button("Reset __Source__")
636
+ with gr.Row():
637
+ reset_sender=gr.Button("Reset Sender")
638
+ reset_recieve=gr.Button("Reset Recipient")
639
+ out_box_bool=gr.Textbox()
640
+ with gr.Row():
641
+ with gr.Column():
642
+ block_text_send = gr.Textbox()
643
+ trans_data_send = gr.Dataframe()
644
+ json_out_send = gr.JSON()
645
+ chain_json_send = gr.JSON()
646
+ with gr.Column():
647
+ block_text_rec = gr.Textbox()
648
+ trans_data_rec = gr.Dataframe()
649
+ json_out_rec = gr.JSON()
650
+ chain_json_rec = gr.JSON()
651
+
652
+ def res_bc():
653
+ blockchain.reset(create="chain1.json")
654
+ return ("Main Blockchain Reset")
655
+ def res_send(send):
656
+ mychain_send = MyChainSend(chain_load=main_balance,create=send)
657
+ return ("Sender Blockchain Reset")
658
+
659
+ def deep_trans():
660
+ chain1=mychain_send.chain
661
+ chain2=blockchain.chain
662
+ valid,ind,mes = mychain_send.deep_valid_send(chain1,chain2)
663
+
664
+ if valid:
665
+ response = 'The Blockchain is valid.'
666
+ z=True
667
+ else:
668
+ response = f'Blockchain is not valid. {mes} at Index {ind}'
669
+ z=False
670
+ return response,z
671
+
672
+
673
+ check_trans.click(deep_trans,None,[block_text,out_box_bool])
674
+
675
+ reset_sender.click(res_send,send,block_text)
676
+ reset_blockchain.click(res_bc,None,block_text)
677
+ reset_source.click(res_source,None,block_text)
678
+
679
+ send_trans.click(issue_tokens,[send,rec,am],[block_text,out_box_bool,json_out_send,json_out_rec,chain_json_send,chain_json_rec,trans_data_send,trans_data_rec,block_text_send,block_text_rec,send,rec,trans_data])
680
+ issue_btn.click(issue_tokens,[send,rec,am],[block_text,out_box_bool,json_out_send,json_out_rec,chain_json_send,chain_json_rec,trans_data_send,trans_data_rec,block_text_send,block_text_rec,send,rec,trans_data])
681
+ #issue_btn.click(issue_tokens,[send,rec,am],[block_text,out_box_bool,json_out_send])
682
+
683
+ node_add.click(add_node,[this_space,node_repo,node_space,node_file],block_text)
684
+ pass_btn.click(checkp,pass_box,[invalid,valida])
685
+ in_chain_btn.click(get_chain,[chain_repo,chain_n],[chain_json,block_text])
686
+ create_bc.click(create_chain,[chain_n],[block_text,json_out,chain_json])
687
+ check.click(valid,None,[block_text,out_box_bool])
688
+ check_all.click(sort_valid,None,block_text)
689
+
690
+ #send_trans.click(bc_transactions,[send,rec,am],[trans_data,block_text,send,rec,am])
691
+ mine_b.click(mine_block,[chain_repo,chain_n],[json_out,chain_json,trans_data,block_text])
692
+
693
+
694
+ bc.launch(enable_queue=False)