forked from ton-blockchain/mytonctrl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mytoncore.py
executable file
·4274 lines (3839 loc) · 130 KB
/
mytoncore.py
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf_8 -*-l
from fastcrc import crc16
import struct
import random
import hashlib
import requests
import re
from mypylib.mypylib import *
local = MyPyClass(__file__)
class LiteClient:
def __init__(self):
self.appPath = None
self.configPath = None
self.pubkeyPath = None
self.addr = None
self.ton = None # magic
#end define
def Run(self, cmd, **kwargs):
index = kwargs.get("index")
liteclient_timeout = local.db.liteclient_timeout if local.db.liteclient_timeout else 3
timeout = kwargs.get("timeout", liteclient_timeout)
useLocalLiteServer = kwargs.get("useLocalLiteServer", True)
validatorStatus = self.ton.GetValidatorStatus()
validatorOutOfSync = validatorStatus.get("outOfSync")
args = [self.appPath, "--global-config", self.configPath, "--verbosity", "0", "--cmd", cmd]
if index is not None:
index = str(index)
args += ["-i", index]
elif useLocalLiteServer and self.pubkeyPath and validatorOutOfSync < 20:
args = [self.appPath, "--addr", self.addr, "--pub", self.pubkeyPath, "--verbosity", "0", "--cmd", cmd]
else:
liteServers = local.db.get("liteServers")
if liteServers is not None and len(liteServers):
index = random.choice(liteServers)
index = str(index)
args += ["-i", index]
#end if
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
output = process.stdout.decode("utf-8")
err = process.stderr.decode("utf-8")
if len(err) > 0:
local.add_log("args: {args}".format(args=args), "error")
raise Exception("LiteClient error: {err}".format(err=err))
return output
#end define
#end class
class ValidatorConsole:
def __init__(self):
self.appPath = None
self.privKeyPath = None
self.pubKeyPath = None
self.addr = None
#end define
def Run(self, cmd, **kwargs):
console_timeout = local.db.console_timeout if local.db.console_timeout else 3
timeout = kwargs.get("timeout", console_timeout)
if self.appPath is None or self.privKeyPath is None or self.pubKeyPath is None:
raise Exception("ValidatorConsole error: Validator console is not settings")
args = [self.appPath, "-k", self.privKeyPath, "-p", self.pubKeyPath, "-a", self.addr, "-v", "0", "--cmd", cmd]
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
output = process.stdout.decode("utf-8")
err = process.stderr.decode("utf-8")
if len(err) > 0:
local.add_log("args: {args}".format(args=args), "error")
raise Exception("ValidatorConsole error: {err}".format(err=err))
return output
#end define
#end class
class Fift:
def __init__(self):
self.appPath = None
self.libsPath = None
self.smartcontsPath = None
#end define
def Run(self, args, **kwargs):
fift_timeout = local.db.fift_timeout if local.db.fift_timeout else 3
timeout = kwargs.get("timeout", fift_timeout)
for i in range(len(args)):
args[i] = str(args[i])
includePath = self.libsPath + ':' + self.smartcontsPath
args = [self.appPath, "-I", includePath, "-s"] + args
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
output = process.stdout.decode("utf-8")
err = process.stderr.decode("utf-8")
if len(err) > 0:
local.add_log("args: {args}".format(args=args), "error")
raise Exception("Fift error: {err}".format(err=err))
return output
#end define
#end class
class Wallet:
def __init__(self, name, path, version):
self.name = name
self.path = path
self.addrFilePath = f"{path}.addr"
self.privFilePath = f"{path}.pk"
self.bocFilePath = f"{path}-query.boc"
self.addrFull = None
self.workchain = None
self.addr = None
self.addrB64 = None
self.addrB64_init = None
self.oldseqno = None
self.account = None
self.subwallet = None
self.version = version
#end define
def Delete(self):
os.remove(self.addrFilePath)
os.remove(self.privFilePath)
#end define
#end class
class Account:
def __init__(self, workchain, addr):
self.workchain = workchain
self.addr = addr
self.addrB64 = None
self.addrFull = None
self.status = "empty"
self.balance = 0
self.lt = None
self.hash = None
self.codeHash = None
#end define
#end class
class Domain(dict):
def __init__(self):
self["name"] = None
self["adnlAddr"] = None
self["walletName"] = None
#end define
#end class
class Block():
def __init__(self, str=None):
self.workchain = None
self.shardchain = None
self.seqno = None
self.rootHash = None
self.fileHash = None
self.ParsBlock(str)
#end define
def ParsBlock(self, str):
if str is None:
return
buff = str.split(':')
self.rootHash = buff[1]
self.fileHash = buff[2]
buff = buff[0]
buff = buff.replace('(', '')
buff = buff.replace(')', '')
buff = buff.split(',')
self.workchain = int(buff[0])
self.shardchain = buff[1]
self.seqno = int(buff[2])
#end define
def __str__(self):
result = f"({self.workchain},{self.shardchain},{self.seqno}):{self.rootHash}:{self.fileHash}"
return result
#end define
def __repr__(self):
return self.__str__()
#end define
def __eq__(self, other):
if other is None:
return False
return self.rootHash == other.rootHash and self.fileHash == other.fileHash
#end define
#end class
class Trans():
def __init__(self, block, addr=None, lt=None, hash=None):
self.block = block
self.addr = addr
self.lt = lt
self.hash = hash
#end define
def __str__(self):
return str(self.__dict__)
#end define
def __repr__(self):
return self.__str__()
#end define
def __eq__(self, other):
if other is None:
return False
return self.hash == other.hash
#end define
#end class
class Message():
def __init__(self):
self.trans = None
self.type = None
self.time = None
self.srcWorkchain = None
self.destWorkchain = None
self.srcAddr = None
self.destAddr = None
self.value = None
self.body = None
self.comment = None
self.ihr_fee = None
self.fwd_fee = None
self.total_fees = None
self.ihr_disabled = None
#end define
def GetFullAddr(self, workchain, addr):
if addr is None:
return
return f"{workchain}:{addr}"
#end define
def __str__(self):
return str(self.__dict__)
#end define
def __repr__(self):
return self.__str__()
#end define
def __eq__(self, other):
if other is None:
return False
return self.hash == other.hash
#end define
#end class
class Pool:
def __init__(self, name, path):
self.name = name
self.path = path
self.addrFilePath = f"{path}.addr"
self.bocFilePath = f"{path}-query.boc"
self.addrFull = None
self.workchain = None
self.addr = None
self.addrB64 = None
self.addrB64_init = None
self.account = None
#end define
def Delete(self):
os.remove(self.addrFilePath)
#end define
#end class
class MyTonCore():
def __init__(self):
self.walletsDir = None
self.dbFile = None
self.contractsDir = None
self.poolsDir = None
self.tempDir = None
self.nodeName = None
self.liteClient = LiteClient()
self.validatorConsole = ValidatorConsole()
self.fift = Fift()
self.Refresh()
self.Init()
#end define
def Init(self):
# Check all directorys
os.makedirs(self.walletsDir, exist_ok=True)
os.makedirs(self.contractsDir, exist_ok=True)
os.makedirs(self.poolsDir, exist_ok=True)
#end define
def Refresh(self):
if self.dbFile:
local.load_db(self.dbFile)
#end if
if not self.walletsDir:
self.walletsDir = local.buffer.my_work_dir + "wallets/"
self.contractsDir = local.buffer.my_work_dir + "contracts/"
self.poolsDir = local.buffer.my_work_dir + "pools/"
self.tempDir = local.buffer.my_temp_dir
self.nodeName = local.db.get("nodeName")
if self.nodeName is None:
self.nodeName=""
else:
self.nodeName = self.nodeName + "_"
liteClient = local.db.get("liteClient")
if liteClient is not None:
self.liteClient.ton = self # magic
self.liteClient.appPath = liteClient["appPath"]
self.liteClient.configPath = liteClient["configPath"]
liteServer = liteClient.get("liteServer")
if liteServer is not None:
self.liteClient.pubkeyPath = liteServer["pubkeyPath"]
self.liteClient.addr = "{0}:{1}".format(liteServer["ip"], liteServer["port"])
#end if
validatorConsole = local.db.get("validatorConsole")
if validatorConsole is not None:
self.validatorConsole.appPath = validatorConsole["appPath"]
self.validatorConsole.privKeyPath = validatorConsole["privKeyPath"]
self.validatorConsole.pubKeyPath = validatorConsole["pubKeyPath"]
self.validatorConsole.addr = validatorConsole["addr"]
#end if
fift = local.db.get("fift")
if fift is not None:
self.fift.appPath = fift["appPath"]
self.fift.libsPath = fift["libsPath"]
self.fift.smartcontsPath = fift["smartcontsPath"]
#end if
# Check config file
self.CheckConfigFile(fift, liteClient)
#end define
def CheckConfigFile(self, fift, liteClient):
mconfig_path = local.buffer.db_path
backup_path = mconfig_path + ".backup"
if fift is None or liteClient is None:
local.add_log("The config file is broken", "warning")
print(f"local.db: {local.db}")
if os.path.isfile(backup_path):
local.add_log("Restoring the configuration file", "info")
args = ["cp", backup_path, mconfig_path]
subprocess.run(args)
self.Refresh()
elif os.path.isfile(backup_path) == False:
local.add_log("Create backup config file", "info")
args = ["cp", mconfig_path, backup_path]
subprocess.run(args)
#end define
def GetVarFromWorkerOutput(self, text, search):
if ':' not in search:
search += ':'
if search is None or text is None:
return None
if search not in text:
return None
start = text.find(search) + len(search)
count = 0
bcount = 0
textLen = len(text)
end = textLen
for i in range(start, textLen):
letter = text[i]
if letter == '(':
count += 1
bcount += 1
elif letter == ')':
count -= 1
if letter == ')' and count < 1:
end = i + 1
break
elif letter == '\n' and count < 1:
end = i
break
result = text[start:end]
if count != 0 and bcount == 0:
result = result.replace(')', '')
return result
#end define
def GetSeqno(self, wallet):
local.add_log("start GetSeqno function", "debug")
cmd = "runmethodfull {addr} seqno".format(addr=wallet.addrB64)
result = self.liteClient.Run(cmd)
if "cannot run any methods" in result:
return None
if "result" not in result:
return 0
seqno = self.GetVarFromWorkerOutput(result, "result")
seqno = seqno.replace(' ', '')
seqno = parse(seqno, '[', ']')
seqno = int(seqno)
return seqno
#end define
def GetAccount(self, inputAddr):
#local.add_log("start GetAccount function", "debug")
workchain, addr = self.ParseInputAddr(inputAddr)
account = Account(workchain, addr)
cmd = "getaccount {inputAddr}".format(inputAddr=inputAddr)
result = self.liteClient.Run(cmd)
storage = self.GetVarFromWorkerOutput(result, "storage")
if storage is None:
return account
addr = self.GetVarFromWorkerOutput(result, "addr")
workchain = self.GetVar(addr, "workchain_id")
address = self.GetVar(addr, "address")
addrFull = "{}:{}".format(workchain, xhex2hex(address))
balance = self.GetVarFromWorkerOutput(storage, "balance")
grams = self.GetVarFromWorkerOutput(balance, "grams")
value = self.GetVarFromWorkerOutput(grams, "value")
state = self.GetVarFromWorkerOutput(storage, "state")
code_buff = self.GetVarFromWorkerOutput(state, "code")
data_buff = self.GetVarFromWorkerOutput(state, "data")
code = self.GetVarFromWorkerOutput(code_buff, "value")
data = self.GetVarFromWorkerOutput(data_buff, "value")
code = self.GetBody(code)
data = self.GetBody(data)
codeHash = self.GetCodeHash(code)
status = parse(state, "account_", '\n')
account.workchain = int(workchain)
account.addr = xhex2hex(address)
account.addrB64 = self.AddrFull2AddrB64(addrFull)
account.addrFull = addrFull
account.status = status
account.balance = ng2g(value)
account.lt = parse(result, "lt = ", ' ')
account.hash = parse(result, "hash = ", '\n')
account.codeHash = codeHash
return account
#end define
def GetCodeHash(self, code):
if code is None:
return
codeBytes = bytes.fromhex(code)
codeHash = hashlib.sha256(codeBytes).hexdigest()
return codeHash
#end define
def GetAccountHistory(self, account, limit):
local.add_log("start GetAccountHistory function", "debug")
addr = f"{account.workchain}:{account.addr}"
lt = account.lt
transHash = account.hash
history = list()
while True:
data, lt, transHash = self.LastTransDump(addr, lt, transHash)
history += data
if lt is None or len(history) >= limit:
return history
#end define
def LastTransDump(self, addr, lt, transHash, count=10):
history = list()
cmd = f"lasttransdump {addr} {lt} {transHash} {count}"
result = self.liteClient.Run(cmd)
data = self.Result2Dict(result)
prevTrans = self.GetKeyFromDict(data, "previous transaction")
prevTransLt = self.GetVar(prevTrans, "lt")
prevTransHash = self.GetVar(prevTrans, "hash")
for key, item in data.items():
if "transaction #" not in key:
continue
block_str = parse(key, "from block ", ' ')
description = self.GetKeyFromDict(item, "description")
type = self.GetVar(description, "trans_")
time = self.GetVarFromDict(item, "time")
#outmsg = self.GetVarFromDict(item, "outmsg_cnt")
total_fees = self.GetVarFromDict(item, "total_fees.grams.value")
messages = self.GetMessagesFromTransaction(item)
transData = dict()
transData["type"] = type
transData["trans"] = Trans(Block(block_str))
transData["time"] = time
#transData["outmsg"] = outmsg
transData["total_fees"] = total_fees
history += self.ParsMessages(messages, transData)
return history, prevTransLt, prevTransHash
#end define
def ParsMessages(self, messages, transData):
history = list()
#for item in messages:
for data in messages:
src = None
dest = None
ihr_disabled = self.GetVarFromDict(data, "message.ihr_disabled")
bounce = self.GetVarFromDict(data, "message.bounce")
bounced = self.GetVarFromDict(data, "message.bounced")
srcWorkchain = self.GetVarFromDict(data, "message.info.src.workchain_id")
address = self.GetVarFromDict(data, "message.info.src.address")
srcAddr = xhex2hex(address)
#if address:
# src = "{}:{}".format(workchain, xhex2hex(address))
#end if
destWorkchain = self.GetVarFromDict(data, "message.info.dest.workchain_id")
address = self.GetVarFromDict(data, "message.info.dest.address")
destAddr = xhex2hex(address)
#if address:
# dest = "{}:{}".format(workchain, xhex2hex(address))
#end if
grams = self.GetVarFromDict(data, "message.info.value.grams.value")
ihr_fee = self.GetVarFromDict(data, "message.info.ihr_fee.value")
fwd_fee = self.GetVarFromDict(data, "message.info.fwd_fee.value")
import_fee = self.GetVarFromDict(data, "message.info.import_fee.value")
#body = self.GetVarFromDict(data, "message.body.value")
message = self.GetItemFromDict(data, "message")
body = self.GetItemFromDict(message, "body")
value = self.GetItemFromDict(body, "value")
body = self.GetBodyFromDict(value)
comment = self.GetComment(body)
#storage_ph
#credit_ph
#compute_ph.gas_fees
#compute_ph.gas_used
#compute_ph.gas_limit
message = Message()
message.type = transData.get("type")
message.block = transData.get("block")
message.trans = transData.get("trans")
message.time = transData.get("time")
#message.outmsg = transData.get("outmsg")
message.total_fees = ng2g(transData.get("total_fees"))
message.ihr_disabled = ihr_disabled
message.bounce = bounce
message.bounced = bounced
message.srcWorkchain = srcWorkchain
message.destWorkchain = destWorkchain
message.srcAddr = srcAddr
message.destAddr = destAddr
message.value = ng2g(grams)
message.body = body
message.comment = comment
message.ihr_fee = ng2g(ihr_fee)
message.fwd_fee = ng2g(fwd_fee)
#message.storage_ph = storage_ph
#message.credit_ph = credit_ph
#message.compute_ph = compute_ph
history.append(message)
#end for
return history
#end define
def GetMessagesFromTransaction(self, data):
result = list()
for key, item in data.items():
if ("inbound message" in key or
"outbound message" in key):
result.append(item)
#end for
result.reverse()
return result
#end define
def GetBody(self, buff):
if buff is None:
return
#end if
body = ""
arr = buff.split('\n')
for item in arr:
if "x{" not in item:
continue
buff = parse(item, '{', '}')
buff = buff.replace('_', '')
if len(buff)%2 == 1:
buff = "0" + buff
body += buff
#end for
return body
#end define
def GetBodyFromDict(self, buff):
if buff is None:
return
#end if
body = ""
for item in buff:
if "x{" not in item:
continue
buff = parse(item, '{', '}')
buff = buff.replace('_', '')
if len(buff)%2 == 1:
buff = "0" + buff
body += buff
#end for
if body == "":
body = None
return body
#end define
def GetComment(self, body):
if body is None:
return
#end if
start = body[:8]
data = body[8:]
result = None
if start == "00000000":
buff = bytes.fromhex(data)
try:
result = buff.decode("utf-8")
except: pass
return result
#end define
def GetDomainAddr(self, domainName):
cmd = "dnsresolve {domainName} -1".format(domainName=domainName)
result = self.liteClient.Run(cmd)
if "not found" in result:
raise Exception("GetDomainAddr error: domain \"{domainName}\" not found".format(domainName=domainName))
resolver = parse(result, "next resolver", '\n')
buff = resolver.replace(' ', '')
buffList = buff.split('=')
fullHexAddr = buffList[0]
addr = buffList[1]
return addr
#end define
def GetDomainEndTime(self, domainName):
local.add_log("start GetDomainEndTime function", "debug")
buff = domainName.split('.')
subdomain = buff.pop(0)
dnsDomain = ".".join(buff)
dnsAddr = self.GetDomainAddr(dnsDomain)
cmd = "runmethodfull {addr} getexpiration \"{subdomain}\"".format(addr=dnsAddr, subdomain=subdomain)
result = self.liteClient.Run(cmd)
result = parse(result, "result:", '\n')
result = parse(result, "[", "]")
result = result.replace(' ', '')
result = int(result)
return result
#end define
def GetDomainAdnlAddr(self, domainName):
local.add_log("start GetDomainAdnlAddr function", "debug")
cmd = "dnsresolve {domainName} 1".format(domainName=domainName)
result = self.liteClient.Run(cmd)
lines = result.split('\n')
for line in lines:
if "adnl address" in line:
adnlAddr = parse(line, "=", "\n")
adnlAddr = adnlAddr.replace(' ', '')
adnlAddr = adnlAddr
return adnlAddr
#end define
def GetLocalWallet(self, walletName, version=None, subwallet=None):
local.add_log("start GetLocalWallet function", "debug")
if walletName is None:
return None
walletPath = self.walletsDir + walletName
if version and "h" in version:
wallet = self.GetHighWalletFromFile(walletPath, subwallet, version)
else:
wallet = self.GetWalletFromFile(walletPath, version)
return wallet
#end define
def GetWalletFromFile(self, filePath, version):
local.add_log("start GetWalletFromFile function", "debug")
# Check input args
if (".addr" in filePath):
filePath = filePath.replace(".addr", '')
if (".pk" in filePath):
filePath = filePath.replace(".pk", '')
if os.path.isfile(filePath + ".pk") == False:
raise Exception("GetWalletFromFile error: Private key not found: " + filePath)
#end if
# Create wallet object
walletName = filePath[filePath.rfind('/')+1:]
wallet = Wallet(walletName, filePath, version)
self.AddrFile2Object(wallet)
self.WalletVersion2Wallet(wallet)
return wallet
#end define
def GetHighWalletFromFile(self, filePath, subwallet, version):
local.add_log("start GetHighWalletFromFile function", "debug")
# Check input args
if (".addr" in filePath):
filePath = filePath.replace(".addr", '')
if (".pk" in filePath):
filePath = filePath.replace(".pk", '')
if os.path.isfile(filePath + ".pk") == False:
raise Exception("GetHighWalletFromFile error: Private key not found: " + filePath)
#end if
# Create wallet object
walletName = filePath[filePath.rfind('/')+1:]
wallet = Wallet(walletName, filePath, version)
wallet.subwallet = subwallet
wallet.addrFilePath = f"{filePath}{subwallet}.addr"
wallet.bocFilePath = f"{filePath}{subwallet}-query.boc"
self.AddrFile2Object(wallet)
self.WalletVersion2Wallet(wallet)
return wallet
#end define
def AddrFile2Object(self, object):
file = open(object.addrFilePath, "rb")
data = file.read()
object.addr = data[:32].hex()
object.workchain = struct.unpack("i", data[32:])[0]
object.addrFull = f"{object.workchain}:{object.addr}"
object.addrB64 = self.AddrFull2AddrB64(object.addrFull)
object.addrB64_init = self.AddrFull2AddrB64(object.addrFull, bounceable=False)
#end define
def WalletVersion2Wallet(self, wallet):
local.add_log("start WalletVersion2Wallet function", "debug")
if wallet.version is not None:
return
walletsVersionList = self.GetWalletsVersionList()
account = self.GetAccount(wallet.addrB64)
version = walletsVersionList.get(wallet.addrB64)
if version is None:
version = self.GetWalletVersionFromHash(account.codeHash)
if version is None:
local.add_log("Wallet version not found: " + wallet.addrB64, "warning")
return
#end if
self.SetWalletVersion(wallet.addrB64, version)
wallet.version = version
#end define
def SetWalletVersion(self, addrB64, version):
walletsVersionList = self.GetWalletsVersionList()
walletsVersionList[addrB64] = version
local.save()
#end define
def GetWalletVersionFromHash(self, inputHash):
local.add_log("start GetWalletVersionFromHash function", "debug")
arr = dict()
arr["v1r1"] = "d670136510daff4fee1889b8872c4c1e89872ffa1fe58a23a5f5d99cef8edf32"
arr["v1r2"] = "2705a31a7ac162295c8aed0761cc6e031ab65521dd7b4a14631099e02de99e18"
arr["v1r3"] = "c3b9bb03936742cfbb9dcdd3a5e1f3204837f613ef141f273952aa41235d289e"
arr["v2r1"] = "fa44386e2c445f1edf64702e893e78c3f9a687a5a01397ad9e3994ee3d0efdbf"
arr["v2r2"] = "d5e63eff6fa268d612c0cf5b343c6674b7312c58dfd9ffa1b536f2014a919164"
arr["v3r1"] = "4505c335cb60f221e58448c71595bb6d7c980c01a798b392ebb53d86cb6061dc"
arr["v3r2"] = "8a6d73bdd8704894f17d8c76ce6139034b8a51b1802907ca36283417798a219b"
arr["v4"] = "7ae380664c513769eaa5c94f9cd5767356e3f7676163baab66a4b73d5edab0e5"
arr["hv1"] = "fc8e48ed7f9654ba76757f52cc6031b2214c02fab9e429ffa0340f5575f9f29c"
for version, hash in arr.items():
if hash == inputHash:
return version
#end for
#end define
def GetWalletsVersionList(self):
bname = "walletsVersionList"
walletsVersionList = local.db.get(bname)
if walletsVersionList is None:
walletsVersionList = dict()
local.db[bname] = walletsVersionList
return walletsVersionList
#end define
def GetFullConfigAddr(self):
# Get buffer
bname = "fullConfigAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
#end if
local.add_log("start GetFullConfigAddr function", "debug")
result = self.liteClient.Run("getconfig 0")
configAddr_hex = self.GetVarFromWorkerOutput(result, "config_addr:x")
fullConfigAddr = "-1:{configAddr_hex}".format(configAddr_hex=configAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullConfigAddr)
return fullConfigAddr
#end define
def GetFullElectorAddr(self):
# Get buffer
bname = "fullElectorAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
#end if
# Get data
local.add_log("start GetFullElectorAddr function", "debug")
result = self.liteClient.Run("getconfig 1")
electorAddr_hex = self.GetVarFromWorkerOutput(result, "elector_addr:x")
fullElectorAddr = "-1:{electorAddr_hex}".format(electorAddr_hex=electorAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullElectorAddr)
return fullElectorAddr
#end define
def GetFullMinterAddr(self):
# Get buffer
bname = "fullMinterAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
#end if
local.add_log("start GetFullMinterAddr function", "debug")
result = self.liteClient.Run("getconfig 2")
minterAddr_hex = self.GetVarFromWorkerOutput(result, "minter_addr:x")
fullMinterAddr = "-1:{minterAddr_hex}".format(minterAddr_hex=minterAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullMinterAddr)
return fullMinterAddr
#end define
def GetFullDnsRootAddr(self):
# Get buffer
bname = "fullDnsRootAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
#end if
local.add_log("start GetFullDnsRootAddr function", "debug")
result = self.liteClient.Run("getconfig 4")
dnsRootAddr_hex = self.GetVarFromWorkerOutput(result, "dns_root_addr:x")
fullDnsRootAddr = "-1:{dnsRootAddr_hex}".format(dnsRootAddr_hex=dnsRootAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullDnsRootAddr)
return fullDnsRootAddr
#end define
def GetActiveElectionId(self, fullElectorAddr):
# Get buffer
bname = "activeElectionId"
buff = self.GetFunctionBuffer(bname)
if buff:
return buff
#end if
local.add_log("start GetActiveElectionId function", "debug")
cmd = "runmethodfull {fullElectorAddr} active_election_id".format(fullElectorAddr=fullElectorAddr)
result = self.liteClient.Run(cmd)
activeElectionId = self.GetVarFromWorkerOutput(result, "result")
activeElectionId = activeElectionId.replace(' ', '')
activeElectionId = parse(activeElectionId, '[', ']')
activeElectionId = int(activeElectionId)
# Set buffer
self.SetFunctionBuffer(bname, activeElectionId)
return activeElectionId
#end define
def GetValidatorsElectedFor(self):
local.add_log("start GetValidatorsElectedFor function", "debug")
config15 = self.GetConfig15()
return config15["validatorsElectedFor"]
#end define
def GetMinStake(self):
local.add_log("start GetMinStake function", "debug")
config17 = self.GetConfig17()
return config17["minStake"]
#end define
def GetRootWorkchainEnabledTime(self):
local.add_log("start GetRootWorkchainEnabledTime function", "debug")
config12 = self.GetConfig(12)
enabledTime = config12["workchains"]["root"]["node"]["value"]["enabled_since"]
return enabledTime
#end define
def GetTotalValidators(self):
local.add_log("start GetTotalValidators function", "debug")
config34 = self.GetConfig34()
result = config34["totalValidators"]
return result
#end define
def GetLastBlock(self):
block = None
cmd = "last"
result = self.liteClient.Run(cmd)
lines = result.split('\n')
for line in lines:
if "latest masterchain block" in line:
buff = line.split(' ')
block = Block(buff[7])
break
return block
#end define
def GetInitBlock_new(self):
#block = self.GetLastBlock()
#cmd = f"gethead {block}"
#result = self.liteClient.Run(cmd)
#seqno = parse(result, "prev_key_block_seqno=", '\n')
statesDir = "/var/ton-work/db/archive/states"
os.chdir(statesDir)
files = filter(os.path.isfile, os.listdir(statesDir))
files = [os.path.join(statesDir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
for fileName in files:
buff = fileName.split('_')
seqno = int(buff[1])
workchain = int(buff[2])
if workchain != -1:
continue
shardchain = int(buff[3])
data = self.GetBlockHead(workchain, shardchain, seqno)
return data
#end define
def GetInitBlock(self):
block = self.GetLastBlock()
cmd = f"gethead {block}"
result = self.liteClient.Run(cmd)
seqno = parse(result, "prev_key_block_seqno=", '\n')
data = self.GetBlockHead(-1, 8000000000000000, seqno)
return data
#end define
def GetBlockHead(self, workchain, shardchain, seqno):
block = self.GetBlock(workchain, shardchain, seqno)
data = dict()
data["seqno"] = block.seqno
data["rootHash"] = block.rootHash
data["fileHash"] = block.fileHash
return data
#end define
def GetBlock(self, workchain, shardchain, seqno):
cmd = "byseqno {workchain}:{shardchain} {seqno}"
cmd = cmd.format(workchain=workchain, shardchain=shardchain, seqno=seqno)
result = self.liteClient.Run(cmd)
block_str = parse(result, "block header of ", ' ')
block = Block(block_str)
return block
#end define
def GetTransactions(self, block):
transactions = list()
cmd = "listblocktrans {block} 999999".format(block=block)
result = self.liteClient.Run(cmd)
lines = result.split('\n')
for line in lines:
if "transaction #" in line:
buff = line.split(' ')
trans_id = buff[1]
trans_id = trans_id.replace('#', '')
trans_id = trans_id.replace(':', '')
trans_addr = buff[3]
trans_lt = buff[5]
trans_hash = buff[7]
trans = Trans(block, trans_addr, trans_lt, trans_hash)
transactions.append(trans)
return transactions
#end define
def GetTrans(self, trans):
addr = f"{trans.block.workchain}:{trans.addr}"
messageList = list()
cmd = f"dumptrans {trans.block} {addr} {trans.lt}"
result = self.liteClient.Run(cmd)
data = self.Result2Dict(result)
for key, item in data.items():
if "transaction is" not in key:
continue
description = self.GetKeyFromDict(item, "description")
type = self.GetVar(description, "trans_")
time = self.GetVarFromDict(item, "time")
#outmsg = self.GetVarFromDict(item, "outmsg_cnt")
total_fees = self.GetVarFromDict(item, "total_fees.grams.value")
messages = self.GetMessagesFromTransaction(item)
transData = dict()
transData["type"] = type
transData["trans"] = trans
transData["time"] = time
#transData["outmsg"] = outmsg