File size: 27,872 Bytes
769f5da
 
 
 
 
 
 
 
 
 
 
 
7720271
769f5da
 
 
adc07b6
 
 
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5af41c1
769f5da
 
 
 
5af41c1
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5af41c1
769f5da
 
 
 
5af41c1
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bc0835
adc07b6
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
0bc0835
 
 
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bc0835
 
 
 
 
 
 
 
 
 
 
 
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7612893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53eb22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7612893
 
 
53eb22d
7612893
53eb22d
 
28de83b
53eb22d
 
7612893
53eb22d
 
 
7612893
 
 
 
adc07b6
7612893
 
 
 
 
 
 
 
436fd6d
53eb22d
7612893
 
 
5178552
7612893
 
53eb22d
7612893
436fd6d
7612893
53eb22d
7612893
 
 
53eb22d
 
 
adc07b6
 
 
 
 
 
0bc0835
adc07b6
769f5da
e1cfb3a
 
7720271
769f5da
 
 
 
 
 
 
0bc0835
 
769f5da
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
import gradio as gr
import pandas as pd 
import datetime
import hashlib
import json
import os
import requests
from mychain import Blockchain
from mychain import MyChainSend 
from mychain import MyChainRec 
from mychain import MyChainTrans
import bc_utils
import crypt

from huggingface_hub import (create_repo,get_full_repo_name,upload_file,CommitOperationAdd,HfApi)

main_chain='https://huggingface.co/datasets/Omnibus/chat-at/raw/main/chains/'
main_balance='https://huggingface.co/datasets/Omnibus/chat-at/raw/main/balance/'
main_trans='https://huggingface.co/datasets/Omnibus/chat-at/raw/main/transact/'

#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']

trans_name = 'trans1.json'
#repo_d='Omnibus/static-bin'
chain_d='chain1.json'
#node_file='node_file.json'
#space='blockchain-simulator-dev1'
api = HfApi(token=token_self)



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]




##############################   BLOCKCHAIN END  ###############################

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)

##############################   MYCHAIN START   ###############################

        

def get_my_chain_send(sender_name=None):
    global mychain_send
    global mychain_trans
    mes_error = ""
    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}')
        try:
            d = requests.get(f'{main_trans}{trans_name}') 
            mychain_trans = MyChainTrans(chain_load=main_trans,load=d.text)
        except Exception as e:
            print (f'error1:: {e}')
            try:
                mychain_trans = MyChainTrans(chain_load=main_trans,create=trans_name)
                print ("this worked")
            except Exception as ee:
                print (f'error2:: {ee}')
                pass
        try:
            response_trans = {'chain': mychain_trans.chain,
                'length': len(mychain_trans.chain)}
            print(f'response_trans:: {response_trans}')
        except Exception as e:
            print (e)
            pass 
            
        message = f"Blockchain loaded from: {main_balance}{sender_name}.json"
        return response,message
    except Exception:
        message = f"Error loading from: {sender_name}"
        print (message)
        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 valid_send():
    valid,ind,mes = mychain_send.chain_valid(mychain_send.chain)
    if valid:
        response = 'The Blockchain is valid.'
        z=True
    else:
        response = f'Sender Blockchain is not valid. {mes} at Index {ind}'
        z=False
    return response,z,mes,ind
    
def valid_rec():
    valid,ind,mes = mychain_rec.chain_valid(mychain_rec.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, mes, ind



def mychain_mine_block_send(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(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_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_trans(balance, chain_r=None,chain_n=None):
    previous_block = mychain_trans.print_previous_block()
    previous_proof = previous_block['proof']
    proof = mychain_trans.proof_of_work(previous_proof)
    previous_hash = mychain_trans.hash(previous_block)
    block = mychain_trans.create_block(balance, proof, previous_hash,len(bc_utils.blockchain.chain)+1,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_trans.chain) > 1000:
        mychain_trans.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(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(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_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 merge_trans():
    trans_bx = []
    previous_post_send = mychain_send.print_previous_block()
    previous_post_rec = mychain_rec.print_previous_block()
    
    send_block = {
            'role': 'Sender',
            'name': previous_post_send['transactions'][0]['sender'],
            'index': previous_post_send['index'],
            'timestamp': previous_post_send['timestamp'],
            'recipient': previous_post_send['transactions'][0]['recipient'],
            'amount': previous_post_send['transactions'][0]['amount'],
            'balance': previous_post_send['balance'], 
            'proof': previous_post_send['proof'],
            'previous_hash': previous_post_send['previous_hash'],
            'block': len(bc_utils.blockchain.chain)+1}
    rec_block = {
            'role': 'Recipient',
            'name': previous_post_rec['transactions'][0]['recipient'],
            'index': previous_post_rec['index'],
            'timestamp': previous_post_rec['timestamp'],
            'sender': previous_post_rec['transactions'][0]['sender'],
            'amount': previous_post_rec['transactions'][0]['amount'],
            'balance': previous_post_rec['balance'], 
            'proof': previous_post_rec['proof'],
            'previous_hash': previous_post_rec['previous_hash'],
            'block': len(bc_utils.blockchain.chain)+1}

    trans_bx.append(send_block)
    trans_bx.append(rec_block)
    return trans_bx



    
def issue_tokens(send,rec,amount):
    response_send={}
    response_rec={}
    show_chain_send={}
    show_chain_rec={}
    data_send=None
    data_rec=None
    rec_send=None
    rec_drop=None
    message_send=None
    message_rec=None    
    trans_data=None
    trans_mes=None
    balance_send = 0
    balance_rec = 0
    mes = "blank message"
    try:
        b_mes,z=bc_utils.valid()
        if z == True:
            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
            mes1,val,mes2,ind = valid_send()
            print (f'val:: {val}')
            if val == False:
                p=False 
                mes = f"Sender: {send} Blockchain is not valid. {mes2} at Index {ind}"
                #mes = "Blockchain is not valid."
            
            #if val == True:
            if p==True:
                try:
                    balance = lod["chain"][-1]["balance"]
                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 = response
                    mes1,val,mes2,ind = valid_rec()
                    print (f'val:: {val}')
                    if val == False:
                        p=False 
                        mes = f"Recipient: {rec} Blockchain is not valid. {mes2} at Index {ind}"
                        #mes = "Blockchain is not valid."
                    #print (lod_rec)
                    if val == True:
                        try:
                            balance = lod_rec["chain"][-1]["balance"]
                            #print (balance)
                        except Exception:
                            p=False
                            balance = 0
                        balance_rec =int(balance)+int(amount)

                if balance_send < 0:
                    mes ="Not enough tokens"
                    p = False
             
            print(mes)

        if z==False:
            mes = b_mes
            p=False
    except Exception as e:
        mes = f"Blockchain not loaded? {e}" 
        p=False
    print (mes)
    
    if p==False:
        return (mes, p,None,None,None,None,None,None,None,None,None,None,None)
        
        #return (mes, p,{},{},{},{},{},{},None,None,None,None,{})
        #json, json, json, json, dataframe, dataframe, textbox, textbox, dropdown, dropdown, dataframe
    if p==True:
        

        mychain_send.new_transaction(f"{send}",f"{rec}",f"{amount}",f"{balance_send}")
        mychain_trans.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)
        
        mychain_mine_block_trans(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}')
        _,rec_send=update_send_list()
        _,rec_drop=update_rec_list()
        trans_bx = merge_trans()
        trans_data, mes = bc_utils.bc_transactions(trans_bx)
        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)

#global send_list
#global rec_list
        
def create_new_chain(address):
    address = str(address.strip("b").strip("'"))
    mychain_rec = MyChainRec(chain_load=main_balance,create=address)
    response = {'chain': mychain_rec.chain,
            'length': len(mychain_rec.chain)}
    
    message = f"Blockchain loaded from: {main_balance}{address}.json"
    send_list,send_drop = update_send_list()
    rec_list, rec_drop = update_rec_list()

    return response,message,send_drop,rec_drop    
##############################   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


def update_send_list():
    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
    return send_list, gr.Dropdown.update(label="Sender", choices=[f for f in send_list])
send_list,send_drop = update_send_list()

def update_rec_list():
    f_ist = (api.list_repo_files(repo_id=f'{repo}/{name}', repo_type="dataset"))
    rec_list =[]
    for i,ea in enumerate(f_ist):
        if "balance/" in ea:
            try:
                if not "__Source__" in ea:
                    rec_list.append(ea.split("/",1)[1].split(".",1)[0])
            except Exception:
                pass
    return rec_list, gr.Dropdown.update(label="Recipient", choices=[f for f in rec_list])
rec_list, rec_drop = update_rec_list()

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("""<h1><center>Blockchain Simulator<br><h3>(Transactions have no value)<br><h4>Chain will reset at 20 blocks""")
        #blockchain = gr.State()
        with gr.Row():
            

            with gr.Tab("OG"):
                with gr.Row():
                    with gr.Column():
                        with gr.Accordion(label="Load",open=False):
                            with gr.Row():
                                chain_repo=gr.Textbox(label="repo/name")
                                chain_n=gr.Textbox(label="Chain file")
                            with gr.Row():
                                in_chain_btn=gr.Button("Load Chain")
                                create_bc = gr.Button("Create New Blockchain")
                        #send=gr.Textbox(label="Sender")
                        send = gr.Dropdown(label="Sender", choices=[f for f in send_list], value = "Bank")
                        rec=gr.Dropdown(label="Recipient", choices=[f for f in rec_list], allow_custom_value=True)
                        send_mes=gr.Textbox(label="Message", lines=6)

                        #am=gr.Textbox(label="Amount")
                        send_trans=gr.Button("Post Transaction")
                        mine_b = gr.Button("Mine Block")
                        check = gr.Button("Check Chain")
                        check_trans = gr.Button("Check Transactions")
                        check_all = gr.Button("Check All")
                    with gr.Column():
                        block_text = gr.Textbox()
                        trans_data = gr.Dataframe()
                        json_out = gr.JSON()
                        chain_json = gr.JSON()
                with gr.Accordion("Nodes", open=False):
                    with gr.Row():
                        this_space=gr.Textbox(label="This Repo/Space")
                    with gr.Row():
                        node_repo=gr.Textbox(label="Node Repo")
                        node_space=gr.Textbox(label="Node Space")
                        node_file=gr.Textbox(label="Node File")
                    node_add=gr.Button("Add Node")
                with gr.Accordion("Tokens", open=False):
                    with gr.Row():
                        with gr.Column():
                            issue_btn=gr.Button()
                        with gr.Column():
                            with gr.Row():
                                reset_blockchain=gr.Button("Reset Main Blockchain")
                                reset_source=gr.Button("Reset __Source__")
                            with gr.Row():
                                reset_sender=gr.Button("Reset Sender")
                                reset_recieve=gr.Button("Reset Recipient")
                    out_box_bool=gr.Textbox()
                    with gr.Row():
                        with gr.Column():
                            block_text_send = gr.Textbox()
                            trans_data_send = gr.Dataframe()
                            json_out_send = gr.JSON()
                            chain_json_send = gr.JSON()            
                        with gr.Column():
                            block_text_rec = gr.Textbox()
                            trans_data_rec = gr.Dataframe()
                            json_out_rec = gr.JSON()
                            chain_json_rec = gr.JSON()     
            with gr.Tab("BC"):
                with gr.Row():
                    with gr.Tab("Gen Wal"):
                        gen_wal_btn=gr.Button()
                        seed = gr.Textbox(label='Seed Phrase')
                        img1=gr.Pil(label='Private Key')
                        out1 = gr.Textbox(label='Private Key',max_lines=4)
                        img2=gr.Pil(label='Public Key')
                        out2 = gr.Textbox(label='Public Key',max_lines=4)
                        img3=gr.Pil(label='Address')
                        out3 = gr.Textbox(label='Address')
                    with gr.Tab("Encrypt"):
                        rsa_to_enc = gr.Textbox(label="txt to encrypt")
                        pub_key_in = gr.Image(label="Public Key", type="filepath")
                        priv_key_in1 = gr.Image(label="Private Key(sig)", type="filepath")
                        rsa_enc_btn = gr.Button("RSA Encrypt")
                        rsa_enc_mes = gr.Textbox(label="encoded", max_lines=4)
                        qr_enc_mes = gr.Image(type="filepath")
                    with gr.Tab("Decrypt"):
                        mes_in = gr.Image(label="Message", type="filepath")
                        priv_key_in = gr.Image(label="Private Key", type="filepath")
                        rsa_dec_btn = gr.Button("RSA Decrypt")
                        rsa_dec_mes = gr.Textbox(label="decoded")

            with gr.Tab("Messages"):
                with gr.Accordion("Key"):
                    with gr.Row():
                        input_address = gr.Image(label="Wallet",type="filepath")
                        input_key = gr.Image(label="Key",type="filepath")
                        
                with gr.Row():
                    with gr.Column():
                        
                        #send_mes=gr.Textbox(label="Message", lines=6)
                        send_mes_btn=gr.Button()
                    rec_mes = gr.Textbox(lines=6)

    def res_bc():
        bc_utils.blockchain.reset(create="chain1.json")
        return ("Main Blockchain Reset")
    def res_send(send):
        mychain_send = MyChainSend(chain_load=main_balance,create=send)
        return ("Sender Blockchain Reset")

    def deep_trans():
        chain1=mychain_send.chain
        chain2=bc_utils.blockchain.chain
        valid,ind,mes = mychain_send.deep_valid_send(chain1,chain2)

        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 mine_block(chain_r=None,chain_n=None):
        try:
            a,b,c,d = bc_utils.mine_block(chain_r=None,chain_n=None)
            mychain_trans.reset(create=trans_name)
            return a,b,c,d
        except Exception as e:
            print (e) 
            return e,None,None,e

    def send_message(send,rec,amount):
        response_send={}
        response_rec={}
        show_chain_send={}
        show_chain_rec={}
        data_send=None
        data_rec=None
        rec_send=None
        rec_drop=None
        message_send=None
        message_rec=None    
        trans_data=None
        trans_mes=None
        balance_send = 0
        balance_rec = 0
        mes = "blank message"
        try:
            #b_mes,z=bc_utils.valid()
            #if z == True:
            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
            mes1,val,mes2,ind = valid_send()
            print (f'val:: {val}')
            if val == False:
                p=False 
                mes = f"Sender: {send} Blockchain is not valid. {mes2} at Index {ind}"
                #mes = "Blockchain is not valid."
            
            #if val == True:
            if p==True:
                
                response,message = get_my_chain_rec(rec)
                lod_rec = response
                mes1,val,mes2,ind = valid_rec()
                print (f'val:: {val}')
                if val == False:
                    p=False 
                    mes = f"Recipient: {rec} Blockchain is not valid. {mes2} at Index {ind}"
                    #mes = "Blockchain is not valid."
                #print (lod_rec)
               

             
            print(mes)
    
            #if z==False:
            #    mes = b_mes
            #    p=False
        except Exception as e:
            mes = f"Blockchain not loaded? {e}" 
            p=False
        print (mes)
        
        if p==False:
            return (mes, p,None,None,None,None,None,None,None,None,None,None,None)
            
            #return (mes, p,{},{},{},{},{},{},None,None,None,None,{})
            #json, json, json, json, dataframe, dataframe, textbox, textbox, dropdown, dropdown, dataframe
        if p==True:
            
    
            mychain_send.new_transaction(f"{send}",f"{rec}",f"{amount}")
            #mychain_trans.new_transaction(f"{send}",f"{rec}",f"{amount}")
    
            message_send = "Transaction Added to Pool"
            data_send = pd.DataFrame(mychain_send.pending_transactions)
            mychain_rec.new_transaction(f"{send}",f"{rec}",f"{amount}")
            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(chain_r=None,chain_n=send)
            
            #mychain_mine_block_trans(balance_send, chain_r=None,chain_n=send)
            
            response_rec, show_chain_rec, message_rec = mychain_mine_block_rec(chain_r=None,chain_n=rec)
            mes = (f'Send: {message_send} :: Recieve: {message_rec}')
            _,rec_send=update_send_list()
            _,rec_drop=update_rec_list()
            #trans_bx = merge_trans()
            #trans_data, mes = bc_utils.bc_transactions(trans_bx)
            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)
    
    
    
        #os.environ['PRIV'] = ""


    send_trans.click(send_message,[send,rec,send_mes],[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])
    #send_mes_btn.click(send_message,[send_mes,input_address,input_key],[rec_mes])

    gen_wal_btn.click(crypt.generate_keys,None,[out2,out1, img3,out3,img1,img2]).then(create_new_chain,out3,[json_out,block_text,send,rec]).then(crypt.test_fn,[img1,img2],[priv_key_in,pub_key_in,priv_key_in1])
    rsa_enc_btn.click(crypt.encrypt_text,[rsa_to_enc,pub_key_in,priv_key_in1,out3],[rsa_enc_mes,qr_enc_mes]).then(crypt.test_fn2,qr_enc_mes,mes_in)
    rsa_dec_btn.click(crypt.decrypt_text,[mes_in,priv_key_in],rsa_dec_mes)
            
    check_trans.click(deep_trans,None,[block_text,out_box_bool])
    
    reset_sender.click(res_send,send,block_text)
    reset_blockchain.click(res_bc,None,block_text)
    reset_source.click(res_source,None,block_text)

    #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])
    #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])
    #issue_btn.click(issue_tokens,[send,rec,am],[block_text,out_box_bool,json_out_send])
    
    node_add.click(bc_utils.add_node,[this_space,node_repo,node_space,node_file],block_text)
    pass_btn.click(checkp,pass_box,[invalid,valida])
    in_chain_btn.click(bc_utils.get_chain,[chain_repo,chain_n],[chain_json,block_text])
    create_bc.click(bc_utils.create_chain,[chain_n],[block_text,json_out,chain_json])
    check.click(bc_utils.valid,None,[block_text,out_box_bool])
    #check_all.click(sort_valid,None,block_text)

    #send_trans.click(bc_transactions,[send,rec,am],[trans_data,block_text,send,rec,am])
    mine_b.click(mine_block,[chain_repo,chain_n],[json_out,chain_json,trans_data,block_text])


bc.launch(enable_queue=False)