Omnibus commited on
Commit
f850533
·
0 Parent(s):

Duplicate from Omnibus/Blockchain-Simulator-dev3

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