-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathmytoncore.py
More file actions
2806 lines (2489 loc) · 102 KB
/
Copy pathmytoncore.py
File metadata and controls
2806 lines (2489 loc) · 102 KB
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
from __future__ import annotations
import os
import base64
import time
import json
import hashlib
import struct
import typing
from dataclasses import asdict
from typing import Union, Any
import psutil
import subprocess
import requests
from fastcrc import crc16
from modules import MODES
from mytoncore.stats_collector import StatsCollector
from mytoncore.utils import (
b642hex,
xhex2hex,
ng2g,
get_package_resource_path,
raw_addr_to_b64,
nano_ton_to_ton,
dec2hex
)
from mytoncore.output import (
get_cell_body,
lc_result_to_list,
tlb_to_json,
get_var_from_text,
get_var_from_dict,
get_int_from_dict,
get_item_from_dict,
get_key_from_dict, get_var_from_worker_output,
)
from mytoncore.clients import Fift, LiteClient, ValidatorConsole
from mytoncore.models import (
Config,
Paths,
ValidatorConfigExt,
Wallet,
Account,
Block,
Transaction,
Message,
Pool,
Config15,
ElectionsParticipant,
Config17,
CacheResult,
BlockHead,
WorkchainConfig,
)
from mypylib.mypylib import (
parse,
get_timestamp,
Dict, int2ip, MyPyClass,
parse_int_forced
)
from mytoncore.vm_stack import parse_result_stack, parse_remote_result_stack
class MyTonCore:
def __init__(self, local: MyPyClass):
self.local: MyPyClass = local
self.nodeName: str = ""
self.cache: dict[str, CacheResult] = {}
self.walletsDir = self.local.my_work_dir + "wallets/"
self.contractsDir = self.local.my_work_dir + "contracts/"
self.poolsDir = self.local.my_work_dir + "pools/"
self.tempDir = self.local.my_temp_dir
os.makedirs(self.walletsDir, exist_ok=True)
os.makedirs(self.contractsDir, exist_ok=True)
os.makedirs(self.poolsDir, exist_ok=True)
self._lite_client: LiteClient | None = None
self._validator_console: ValidatorConsole | None = None
self._fift: Fift | None = None
mconfig_path = self.local.db_path
backup_path = mconfig_path + ".backup"
if self.local.db.get("liteClient") is None or self.local.db.get("fift") is None:
self.restore_db_file(mconfig_path, backup_path)
else:
self.check_db_backup(backup_path)
self.apply_db_settings()
def apply_db_settings(self):
lite_client_config = self.local.db.get("liteClient")
fift_config = self.local.db.get("fift")
vc_config = self.local.db.get("validatorConsole")
self.nodeName = self.local.db.get("nodeName")
if self.nodeName is None:
self.nodeName=""
else:
self.nodeName = self.nodeName + "_"
if lite_client_config is not None:
ls_pubkey_path = None
ls_addr = None
ls_config = lite_client_config.get("liteServer")
if ls_config is not None:
ls_pubkey_path = ls_config["pubkeyPath"]
ls_addr = f"{ls_config['ip']}:{ls_config['port']}"
self._lite_client = LiteClient(
self.local,
lite_client_config["appPath"],
lite_client_config["configPath"],
ls_pubkey_path,
ls_addr,
self.GetValidatorStatus
)
if vc_config is not None:
self._validator_console = ValidatorConsole(
self.local, vc_config["appPath"], vc_config["privKeyPath"], vc_config["pubKeyPath"], vc_config["addr"]
)
if fift_config is not None:
self._fift = Fift(self.local, fift_config["appPath"], fift_config["libsPath"], fift_config["smartcontsPath"])
@property
def liteClient(self) -> LiteClient:
if self._lite_client is None:
raise RuntimeError("LiteClient is not initialized")
return self._lite_client
@property
def validatorConsole(self) -> ValidatorConsole:
if self._validator_console is None:
raise RuntimeError("ValidatorConsole is not initialized")
return self._validator_console
@property
def fift(self) -> Fift:
if self._fift is None:
raise RuntimeError("Fift is not initialized")
return self._fift
def restore_db_file(self, mconfig_path: str, backup_path: str):
self.local.add_log(f"Restoring db file {mconfig_path} from backup {backup_path}", "warning")
print(f"self.local.db: {self.local.db}")
if os.path.isfile(backup_path):
self.local.add_log("Restoring the configuration file", "info")
args = ["cp", backup_path, mconfig_path]
subprocess.run(args)
self.local.load_db(mconfig_path)
else:
self.local.add_log("Backup file not found", "error")
def check_db_backup(self, backup_path: str):
if not os.path.isfile(backup_path) or time.time() - os.path.getmtime(backup_path) > 3600:
self.local.try_function(self.create_self_db_backup)
def create_self_db_backup(self):
self.local.add_log("Create backup config file", "info")
mconfig_path = self.local.db_path
backup_path = mconfig_path + ".backup"
backup_tmp_path = backup_path + '.tmp'
subprocess.run(["cp", mconfig_path, backup_tmp_path])
try:
with open(backup_tmp_path, "r") as file:
json.load(file)
os.rename(backup_tmp_path, backup_path) # atomic opetation
except Exception:
self.local.add_log("Could not update backup, backup_tmp file is broken", "warning")
os.remove(backup_tmp_path)
def get_paths(self) -> Paths:
paths = self.local.db.get("paths")
if paths is None:
return Paths()
return Paths.from_dict(paths)
def run_get_method(self, addr: str, method: str) -> list[str]:
cmd = f"runmethodfull {addr} {method}"
result = self.liteClient.run(cmd)
return parse_result_stack(result)
def run_get_method_local(self, addr: str, method: str, params: list | None = None) -> list[str]:
cmd = f"runmethod {addr} {method}"
if params:
cmd += " " + " ".join(map(str, params))
result = self.liteClient.run_local(cmd)
return parse_remote_result_stack(result)
def get_seqno(self, wallet: Wallet) -> int:
seqno = int(self.run_get_method(wallet.addrB64, "seqno")[0])
wallet.seqno = seqno
self.local.add_log(f"got seqno {seqno} for {wallet.addrB64}", "debug")
return seqno
def GetAccount(self, inputAddr: str):
#self.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 = get_var_from_worker_output(result, "storage")
if storage is None:
return account
balance = get_var_from_worker_output(storage, "balance")
grams = get_var_from_worker_output(balance, "grams")
value = get_var_from_worker_output(grams, "value")
state = get_var_from_worker_output(storage, "state")
code_buff = get_var_from_worker_output(state, "code")
code = get_var_from_worker_output(code_buff, "value")
code_hash = None
if code is not None:
code = get_cell_body(code.split('\n'))
code_bytes = bytes.fromhex(code)
code_hash = hashlib.sha256(code_bytes).hexdigest()
status = parse(state, "account_", '\n')
if status is not None:
account.status = status
if value is not None:
account.balance = nano_ton_to_ton(int(value))
account.lt = parse(result, "lt = ", ' ')
account.hash = parse(result, "hash = ", '\n')
account.codeHash = code_hash
return account
def GetAccountHistory(self, account, limit) -> list[Message]:
self.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
def LastTransDump(self, addr, lt, transHash, count=10):
history: list[Message] = list()
cmd = f"lasttransdump {addr} {lt} {transHash} {count}"
result = self.liteClient.run(cmd)
data = self.Result2Dict(result)
prevTrans = get_key_from_dict(data, "previous transaction")
prevTransLt = get_var_from_text(prevTrans, "lt")
prevTransHash = get_var_from_text(prevTrans, "hash")
for key, item in data.items():
if "transaction #" not in key:
continue
block_str = parse(key, "from block ", ' ')
if block_str is None:
raise ValueError(f'Invalid transaction block: {key}')
description = get_key_from_dict(item, "description")
type = get_var_from_text(description, "trans_")
time = get_int_from_dict(item, "time")
#outmsg = get_int_from_dict(item, "outmsg_cnt")
total_fees = get_int_from_dict(item, "total_fees.grams.value")
messages = self.GetMessagesFromTransaction(item)
tr = Transaction(block=Block.from_str(block_str), type=type, time=time, total_fees=ng2g(total_fees))
history += self.parse_messages(messages, tr)
return history, prevTransLt, prevTransHash
def parse_messages(self, messages: list[dict[str, Any]], tr: Transaction) -> list[Message]:
history = list()
for data in messages:
src_addr, dest_addr = None, None
src_workchain = get_int_from_dict(data, "message.info.src.workchain_id")
address = get_var_from_dict(data, "message.info.src.address")
if address is not None:
src_addr = xhex2hex(address)
dest_workchain = get_int_from_dict(data, "message.info.dest.workchain_id")
address = get_var_from_dict(data, "message.info.dest.address")
if address is not None:
dest_addr = xhex2hex(address)
grams = get_int_from_dict(data, "message.info.value.grams.value")
message = get_item_from_dict(data, "message")
body = get_item_from_dict(message, "body")
value = get_item_from_dict(body, "value")
body = None
if value is not None:
body = get_cell_body(value) or None
message = Message(
transaction=tr,
src_workchain=src_workchain,
dest_workchain=dest_workchain,
src_addr=src_addr,
dest_addr=dest_addr,
value=ng2g(grams),
body=body,
)
history.append(message)
return history
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)
result.reverse()
return result
def GetLocalWallet(self, wallet_name: str, version=None, subwallet=None) -> Wallet:
walletPath = self.walletsDir + wallet_name
if version and "h" in version:
wallet = self.GetHighWalletFromFile(walletPath, subwallet, version)
else:
wallet = self.GetWalletFromFile(walletPath, version)
return wallet
def GetWalletFromFile(self, filePath, version):
# Check input args
if (".addr" in filePath):
filePath = filePath.replace(".addr", '')
if (".pk" in filePath):
filePath = filePath.replace(".pk", '')
if not os.path.isfile(filePath + ".pk"):
raise Exception("GetWalletFromFile error: Private key not found: " + filePath)
# Create wallet object
walletName = filePath[filePath.rfind('/')+1:]
wallet = Wallet.from_file(walletName, filePath, version)
self.WalletVersion2Wallet(wallet)
return wallet
def GetHighWalletFromFile(self, filePath, subwallet, version):
# Check input args
if (".addr" in filePath):
filePath = filePath.replace(".addr", '')
if (".pk" in filePath):
filePath = filePath.replace(".pk", '')
if not os.path.isfile(filePath + ".pk"):
raise Exception("GetHighWalletFromFile error: Private key not found: " + filePath)
# Create wallet object
walletName = filePath[filePath.rfind('/')+1:]
wallet = Wallet.from_file(walletName, filePath, version, subwallet)
self.WalletVersion2Wallet(wallet)
return wallet
def WalletVersion2Wallet(self, wallet):
if wallet.version is not None:
return
walletsVersionList = self.GetWalletsVersionList()
version = walletsVersionList.get(wallet.addrB64)
if version is None:
account = self.GetAccount(wallet.addrB64)
version = self.GetVersionFromCodeHash(account.codeHash)
self.SetWalletVersion(wallet.addrB64, version)
if version is None:
self.local.add_log("Wallet version not found: " + wallet.addrB64, "warning")
return
wallet.version = version
def SetWalletVersion(self, addrB64, version):
walletsVersionList = self.GetWalletsVersionList()
walletsVersionList[addrB64] = version
self.local.save()
def GetVersionFromCodeHash(self, inputHash):
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"
arr["pool"] = "399838da9489139680e90fd237382e96ba771fdf6ea27eb7d513965b355038b4"
arr["spool"] = "fc2ae44bcaedfa357d0091769aabbac824e1c28f14cc180c0b52a57d83d29054"
arr["spool_r2"] = "42bea8fea43bf803c652411976eb2981b9bdb10da84eb788a63ea7a01f2a044d"
arr["liquid_pool_r1"] = "82bc5760719c34395f80df76c42dc5d287f08f6562c643601ebed6944302dcc2"
arr["liquid_pool_r2"] = "95abec0a66ac63b0fbcf28466eb8240ddcd88f97300691511d9c9975d5521e4a"
arr["liquid_pool_r3"] = "22a023bc75b649ff2b5b183cd0d34cd413e6e27ee6d6ad0787f75ad39787ed4e"
arr["liquid_pool_r4"] = "77282b45fd7cfc72ca68fe97af33ad10078730ceaf55e20534c9526c48d602d2"
arr["controller_r1"] = "0949cf92963dd27bb1e6bf76487807f20409131b6110acbc18b7fbb90280ccf0"
arr["controller_r2"] = "01118b9553151fb9bc81704a4b3e0fc7b899871a527d44435a51574806863e2c"
arr["controller_r3"] = "e4d8ce8ff7b4b60c76b135eb8702ce3c86dc133fcee7d19c7aa18f71d9d91438"
arr["controller_r4"] = "dec125a4850c4ba24668d84252b04c6ad40abf5c9d413a429b56bfff09ea25d4"
for version, hash in arr.items():
if hash == inputHash:
return version
def GetWalletsVersionList(self):
bname = "walletsVersionList"
walletsVersionList = self.local.db.get(bname)
if walletsVersionList is None:
walletsVersionList = dict()
self.local.db[bname] = walletsVersionList
return walletsVersionList
def GetFullConfigAddr(self):
# Get buffer
bname = "fullConfigAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
result = self.liteClient.run("getconfig 0")
configAddr_hex = get_var_from_worker_output(result, "config_addr:x")
fullConfigAddr = "-1:{configAddr_hex}".format(configAddr_hex=configAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullConfigAddr)
return fullConfigAddr
def GetFullElectorAddr(self):
# Get buffer
bname = "fullElectorAddr"
buff = self.GetFunctionBuffer(bname, timeout=60)
if buff:
return buff
# Get data
result = self.liteClient.run("getconfig 1")
electorAddr_hex = get_var_from_worker_output(result, "elector_addr:x")
fullElectorAddr = "-1:{electorAddr_hex}".format(electorAddr_hex=electorAddr_hex)
# Set buffer
self.SetFunctionBuffer(bname, fullElectorAddr)
return fullElectorAddr
def GetActiveElectionId(self, full_elector_addr: str) -> int:
cmd = "runmethodfull {fullElectorAddr} active_election_id".format(fullElectorAddr=full_elector_addr)
result = self.liteClient.run(cmd)
activeElectionId = get_var_from_worker_output(result, "result")
if activeElectionId is None:
raise ValueError(f"result is not found: {result}")
activeElectionId = activeElectionId.replace(' ', '')
activeElectionId = parse(activeElectionId, '[', ']')
if activeElectionId is None:
raise ValueError(f"election id is not found: {result}")
activeElectionId = int(activeElectionId)
return activeElectionId
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.from_str(buff[7])
break
return block
def GetInitBlock(self) -> BlockHead:
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
def GetBlockHead(self, workchain, shardchain, seqno) -> BlockHead:
block = self.GetBlock(workchain, shardchain, seqno)
data: BlockHead = {"seqno": block.seqno, "rootHash": block.rootHash, "fileHash": block.fileHash}
return data
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 ", ' ')
if block_str is None:
raise ValueError(f"block is not found: {result}")
block = Block.from_str(block_str)
return block
def GetShards(self, block=None):
shards = list()
if block:
cmd = "allshards {block}".format(block=block)
else:
cmd = "allshards"
result = self.liteClient.run(cmd)
lines = result.split('\n')
for line in lines:
if "shard #" in line:
buff = line.split(' ')
shard_id = buff[1]
shard_id = shard_id.replace('#', '')
shard_block = Block.from_str(buff[3])
shard = {"id": shard_id, "block": shard_block}
shards.append(shard)
return shards
def GetShardsNumber(self, block=None):
shards = self.GetShards(block)
shardsNum = len(shards)
return shardsNum
def parse_stats_from_vc(self, output: str, result: dict):
for line in output.split('\n'):
if len(line.split('\t\t\t')) == 2:
name, value = line.split('\t\t\t') # https://github.com/ton-blockchain/ton/blob/master/validator-engine-console/validator-engine-console-query.cpp#L648
if name not in result:
result[name] = value
def GetValidatorStatus(self, no_cache: bool = False) -> Dict:
# Get buffer
bname = "validator_status"
buff = self.GetFunctionBuffer(bname)
if buff and not no_cache:
return buff
self.local.add_log("start GetValidatorStatus function", "debug")
status = Dict()
result = None
try:
# Parse
status.is_working = True
result = self.validatorConsole.run("getstats")
status.unixtime = parse_int_forced(result, "unixtime", '\n')
status.masterchainblocktime = parse_int_forced(result, "masterchainblocktime", '\n')
status.stateserializermasterchainseqno = parse_int_forced(result, "stateserializermasterchainseqno", '\n')
status.shardclientmasterchainseqno = parse_int_forced(result, "shardclientmasterchainseqno", '\n')
buff = parse(result, "masterchainblock", '\n')
status.masterchainblock = self.GVS_GetItemFromBuff(buff)
buff = parse(result, "gcmasterchainblock", '\n')
status.gcmasterchainblock = self.GVS_GetItemFromBuff(buff)
buff = parse(result, "keymasterchainblock", '\n')
status.keymasterchainblock = self.GVS_GetItemFromBuff(buff)
buff = parse(result, "rotatemasterchainblock", '\n')
status.rotatemasterchainblock = self.GVS_GetItemFromBuff(buff)
# Calculate
status.masterchain_out_of_sync = status.unixtime - status.masterchainblocktime
status.shardchain_out_of_sync = status.masterchainblock - status.shardclientmasterchainseqno
status.masterchain_out_of_ser = status.masterchainblock - status.stateserializermasterchainseqno
status.out_of_sync = status.masterchain_out_of_sync if status.masterchain_out_of_sync > status.shardchain_out_of_sync else status.shardchain_out_of_sync
status.out_of_ser = status.masterchain_out_of_ser
status.last_deleted_mc_state = parse_int_forced(result, "last_deleted_mc_state", '\n')
state_serializer_enabled = parse(result, "stateserializerenabled", '\n')
if state_serializer_enabled is not None:
status.stateserializerenabled = state_serializer_enabled.strip() == "true"
self.local.try_function(self.parse_stats_from_vc, args=[result, status])
if 'active_validator_groups' in status:
groups = status.active_validator_groups.split() # master:1 shard:2
status.validator_groups_master = int(groups[0].split(':')[1])
status.validator_groups_shard = int(groups[1].split(':')[1])
except Exception as ex:
self.local.add_log(f"GetValidatorStatus warning: {ex}", "warning")
status.is_working = False
if result is not None:
self.local.try_function(self.parse_stats_from_vc, args=[result, status])
status.initial_sync = status.get("process.initial_sync")
# old vars
status.outOfSync = status.out_of_sync
status.isWorking = status.is_working
# Set buffer
self.SetFunctionBuffer(bname, status)
return status
def GVS_GetItemFromBuff(self, buff):
buffList = buff.split(':')
buff2 = buffList[0]
buff2 = buff2.replace(' ', '')
buff2 = buff2.replace('(', '')
buff2 = buff2.replace(')', '')
buffList2 = buff2.split(',')
item = buffList2[2]
item = int(item)
return item
_Nested = typing.Dict[str, Union[str, int, "_Nested"]]
def get_config(self, config_id: int) -> _Nested:
bname = "config" + str(config_id)
buff = self.GetFunctionBuffer(bname, timeout=10)
if buff:
return buff
cmd = f"getconfig {config_id}"
result = self.liteClient.run(cmd)
text = result[result.find("ConfigParam"):]
data = tlb_to_json(text)
self.SetFunctionBuffer(bname, data)
return data
def get_basechain_config(self) -> WorkchainConfig:
result = self.liteClient.run("getconfig 12")
return WorkchainConfig.from_str(result)
def get_root_workchain_enabled_time(self) -> int:
enabled_time = self.get_basechain_config().enabled_since
return enabled_time
def get_config_15(self) -> Config15:
result = self.liteClient.run("getconfig 15")
return Config15.from_str(result)
def get_config_17(self) -> Config17:
result = self.liteClient.run("getconfig 17")
return Config17.from_str(result)
def get_config_32(self) -> Config:
bname = "typed_config32"
buff = self.GetFunctionBuffer(bname, timeout=10)
if buff:
return buff
result = self.liteClient.run("getconfig 32")
config32 = Config.from_str(result)
self.SetFunctionBuffer(bname, config32)
return config32
def get_config_34(self, no_cache: bool = False) -> Config:
bname = "typed_config34"
buff = self.GetFunctionBuffer(bname, timeout=10)
if buff and not no_cache:
return buff
result = self.liteClient.run("getconfig 34")
config34 = Config.from_str(result)
self.SetFunctionBuffer(bname, config34)
return config34
def get_config_36(self) -> Config | None:
result = self.liteClient.run("getconfig 36")
if 'ConfigParam(36) = (null)' in result:
return None
return Config.from_str(result)
def CreateNewKey(self):
self.local.add_log("start CreateNewKey function", "debug")
result = self.validatorConsole.run("newkey")
key = parse(result, "created new key ", '\n')
if key is None:
raise Exception(f"Failed to get new ket: {result}")
return key
def GetPubKeyBase64(self, key: str):
self.local.add_log("start GetPubKeyBase64 function", "debug")
result = self.validatorConsole.run("exportpub " + key)
validatorPubkey_b64 = parse(result, "got public key: ", '\n')
if validatorPubkey_b64 is None:
raise Exception(f"Failed to get public key: {result}")
return validatorPubkey_b64
def get_clean_pubkey_hex(self, key: str):
validator_pubkey_b64 = self.GetPubKeyBase64(key)
return b642hex(validator_pubkey_b64)[8:].upper() # skip magic prefix
def AddKeyToValidator(self, key, startWorkTime, endWorkTime):
self.local.add_log("start AddKeyToValidator function", "debug")
output = False
cmd = "addpermkey {key} {startWorkTime} {endWorkTime}".format(key=key, startWorkTime=startWorkTime, endWorkTime=endWorkTime)
result = self.validatorConsole.run(cmd)
if ("success" in result):
output = True
return output
def AddKeyToTemp(self, key: str, endWorkTime: int):
self.local.add_log("start AddKeyToTemp function", "debug")
output = False
result = self.validatorConsole.run("addtempkey {key} {key} {endWorkTime}".format(key=key, endWorkTime=endWorkTime))
if ("success" in result):
output = True
return output
def add_adnl_addr(self, adnl_addr: str, category: int = 0) -> bool:
self.local.add_log(f"adding {adnl_addr} adnl addr category {category}", "debug")
result = self.validatorConsole.run(f"addadnl {adnl_addr} {category}")
return "success" in result
def update_adnl_category(self, adnl_addr: str, category: int) -> bool:
res = self.add_adnl_addr(adnl_addr=adnl_addr, category=category)
if res:
self.local.add_log(f"Changed category for {adnl_addr} ADNL address in validator config", "info")
return True
else:
self.local.add_log(f"Failed to change category for {adnl_addr} ADNL address in validator config", "error")
return False
def GetAdnlAddr(self) -> str | None:
adnlAddr = self.local.db.get("adnlAddr")
return adnlAddr
def AttachAdnlAddrToValidator(self, adnlAddr, key, endWorkTime):
self.local.add_log("start AttachAdnlAddrToValidator function", "debug")
output = False
result = self.validatorConsole.run("addvalidatoraddr {key} {adnlAddr} {endWorkTime}".format(adnlAddr=adnlAddr, key=key, endWorkTime=endWorkTime))
if ("success" in result):
output = True
return output
def CreateConfigProposalRequest(self, offerHash, validatorIndex):
self.local.add_log("start CreateConfigProposalRequest function", "debug")
fileName = self.tempDir + self.nodeName + "proposal_validator-to-sign.req"
args = ["config-proposal-vote-req.fif", "-i", validatorIndex, offerHash, fileName]
result = self.fift.run(args)
fileName = parse(result, "Saved to file ", '\n')
resultList = result.split('\n')
i = 0
start_index = 0
for item in resultList:
if "Creating a request to vote for configuration proposal" in item:
start_index = i
i += 1
var1 = resultList[start_index + 1]
return var1
def CreateComplaintRequest(self, electionId, complaintHash, validatorIndex):
self.local.add_log("start CreateComplaintRequest function", "debug")
fileName = self.tempDir + "complaint_validator-to-sign.req"
args = ["complaint-vote-req.fif", validatorIndex, electionId, complaintHash, fileName]
result = self.fift.run(args)
fileName = parse(result, "Saved to file ", '\n')
resultList = result.split('\n')
i = 0
start_index = 0
for item in resultList:
if "Creating a request to vote for complaint" in item:
start_index = i
i += 1
var1 = resultList[start_index + 1]
return var1
def remove_proofs_from_complaint(self, input_file_name: str):
self.local.add_log("start remove_proofs_from_complaint function", "debug")
output_file_name = self.tempDir + "complaint-new.boc"
with get_package_resource_path('mytoncore', 'complaints/remove-proofs-v2.fif') as fift_script:
args = [fift_script, input_file_name, output_file_name]
self.fift.run(args)
return output_file_name
def PrepareComplaint(self, electionId, inputFileName):
self.local.add_log("start PrepareComplaint function", "debug")
fileName = self.tempDir + "complaint-msg-body.boc"
args = ["envelope-complaint.fif", electionId, inputFileName, fileName]
result = self.fift.run(args)
fileName = parse(result, "Saved to file ", ')')
return fileName
def CreateElectionRequest(self, addrB64, startWorkTime, adnlAddr, maxFactor):
self.local.add_log("start CreateElectionRequest function", "debug")
fileName = self.tempDir + self.nodeName + str(startWorkTime) + "_validator-to-sign.bin"
args = ["validator-elect-req.fif", addrB64, startWorkTime, maxFactor, adnlAddr, fileName]
result = self.fift.run(args)
fileName = parse(result, "Saved to file ", '\n')
resultList = result.split('\n')
i = 0
start_index = 0
for item in resultList:
if "Creating a request to participate in validator elections" in item:
start_index = i
i += 1
var1 = resultList[start_index + 1]
return var1
def GetValidatorSignature(self, validatorKey, var1):
self.local.add_log("start GetValidatorSignature function", "debug")
cmd = "sign {validatorKey} {var1}".format(validatorKey=validatorKey, var1=var1)
result = self.validatorConsole.run(cmd)
validatorSignature = parse(result, "got signature ", '\n')
return validatorSignature
def SignElectionRequestWithValidator(self, wallet, startWorkTime, adnlAddr, validatorPubkey_b64, validatorSignature, maxFactor):
self.local.add_log("start SignElectionRequestWithValidator function", "debug")
fileName = self.tempDir + self.nodeName + str(startWorkTime) + "_validator-query.boc"
args = ["validator-elect-signed.fif", wallet.addrB64, startWorkTime, maxFactor, adnlAddr, validatorPubkey_b64, validatorSignature, fileName]
result = self.fift.run(args)
pubkey = parse(result, "validator public key ", '\n')
fileName = parse(result, "Saved to file ", '\n')
return pubkey, fileName
def SignBocWithWallet(self, wallet: Wallet, boc_path, dest, coins, boc_mode: str = "--body"):
self.local.add_log("start SignBocWithWallet function", "debug")
flags = []
# Balance checking
account = self.GetAccount(wallet.addrB64)
self.check_account_balance(account, coins + 0.1)
# Bounceable checking
destAccount = self.GetAccount(dest)
bounceable = self.IsBounceableAddrB64(dest)
if not bounceable and destAccount.status == "active":
flags += ["--force-bounce"]
text = "Find non-bounceable flag, but destination account already active. Using bounceable flag"
self.local.add_log(text, "warning")
elif "-n" not in flags and bounceable and destAccount.status != "active":
raise Exception("Find bounceable flag, but destination account is not active. Use non-bounceable address or flag -n")
seqno = str(self.get_seqno(wallet))
result_file_path = self.tempDir + self.nodeName + wallet.name + "_wallet-query"
if "v1" in wallet.version:
fift_script = "wallet.fif"
args = [fift_script, wallet.path, dest, seqno, coins, boc_mode, boc_path, result_file_path]
elif "v2" in wallet.version:
fift_script = "wallet-v2.fif"
args = [fift_script, wallet.path, dest, seqno, coins, boc_mode, boc_path, result_file_path]
elif "v3" in wallet.version:
if wallet.subwallet is None:
subwallet = str(698983191 + wallet.workchain) # 0x29A9A317 + workchain
else:
subwallet = str(wallet.subwallet)
fift_script = "wallet-v3.fif"
args = [fift_script, wallet.path, dest, subwallet, seqno, coins, boc_mode, boc_path, result_file_path]
else:
raise Exception(f"SignBocWithWallet error: Wallet version '{wallet.version}' is not supported")
if flags:
args += flags
result = self.fift.run(args)
result_file_path = parse(result, "Saved to file ", ")")
if not result_file_path:
raise Exception(f"Failed to get file with boc: {result}")
return result_file_path
def SendFile(self, file_path: str, wallet: Wallet | None = None, timeout: int = 30, remove: bool = True):
self.local.add_log("start SendFile function: " + file_path, "debug")
duplicateSendfile = self.local.db.get("duplicateSendfile", True)
telemetry = self.local.db.get("sendTelemetry", False)
duplicateApi = self.local.db.get("duplicateApi", telemetry)
if not os.path.isfile(file_path):
raise Exception("SendFile error: no such file '{filePath}'".format(filePath=file_path))
old_seqno = None
if wallet:
old_seqno = wallet.seqno
self.liteClient.run("sendfile " + file_path)
if duplicateSendfile:
try:
self.liteClient.run("sendfile " + file_path, use_local=False)
self.liteClient.run("sendfile " + file_path, use_local=False)
except Exception:
pass
if duplicateApi:
try:
self.send_boc_toncenter(file_path)
except Exception as e:
self.local.add_log(f'Failed to send file {file_path} to toncenter: {e}', 'warning')
if timeout and wallet and old_seqno is not None:
self.WaitTransaction(wallet, old_seqno, timeout)
if remove:
try:
os.remove(file_path)
except Exception as e:
self.local.add_log(f'Failed to remove file {file_path}: {e}', 'warning')
def send_boc_toncenter(self, file_path: str):
self.local.add_log('Start send_boc_toncenter function: ' + file_path, 'debug')
with open(file_path, "rb") as f:
boc = f.read()
boc_b64 = base64.b64encode(boc).decode("utf-8")
data = {"boc": boc_b64}
network_name = self.GetNetworkName()
if network_name == 'testnet':
default_url = 'https://testnet.toncenter.com/api/v2/sendBoc'
elif network_name == 'mainnet':
default_url = 'https://toncenter.com/api/v2/sendBoc'
else:
default_url = None
url = self.local.db.get("duplicateApiUrl", default_url)
if url is None:
return False
result = requests.post(url=url, json=data, timeout=3)
if result.status_code != 200:
self.local.add_log(f'Failed to send boc to toncenter: {result.content}', 'info')
return False
self.local.add_log('Sent boc to toncenter', 'info')
return True
def WaitTransaction(self, wallet: Wallet, old_seqno: int, timeout: int = 30):
self.local.add_log("start WaitTransaction function", "debug")
timesleep = 3
steps = timeout // timesleep
for i in range(steps):
time.sleep(timesleep)
try:
seqno = self.get_seqno(wallet)
except Exception:
self.local.add_log("WaitTransaction error: Can't get seqno", "warning")
continue
if seqno != old_seqno:
self.local.add_log("WaitTransaction success", "info")
return
raise Exception("WaitTransaction error: time out")
def get_returned_stake(self, full_elector_addr: str, input_addr: str) -> float:
workchain, addr = self.ParseInputAddr(input_addr)
cmd = f"runmethodfull {full_elector_addr} compute_returned_stake 0x{addr}"
result = self.liteClient.run(cmd)
stack = lc_result_to_list(result)
if not isinstance(stack[0], int):
raise TypeError(f'Got incorrect type: {stack}')
returned_stake = nano_ton_to_ton(stack[0])
return returned_stake
def ProcessRecoverStake(self):
self.local.add_log("start ProcessRecoverStake function", "debug")
resultFilePath = self.tempDir + self.nodeName + "recover-query"
args = ["recover-stake.fif", resultFilePath]
result = self.fift.run(args)
resultFilePath = parse(result, "Saved to file ", '\n')
return resultFilePath
def GetStake(self, account: Account):
stake = self.local.db.get("stake")
usePool = self.using_pool()
useController = self.using_liquid_staking()
stakePercent = self.local.db.get("stakePercent", 100)
stake_no_split = self.local.db.get("stakeNoSplit", False)
vconfig = self.GetValidatorConfig()
config17 = self.get_config_17()
is_single_nominator = self.is_account_single_nominator(account)
if stake is None and usePool and not is_single_nominator:
stake = account.balance - 20
if stake is None and useController:
stake = account.balance - 50
if stake is None:
sp = stakePercent / 100
if sp > 1 or sp < 0:
self.local.add_log("Wrong stakePercent value. Using default stake.", "warning")
stakePercent = 100
sp = 1
if len(vconfig.validators) == 0 and not stake_no_split:
stake = int(account.balance*sp/2)
if stake < config17.min_stake: # not enough funds to divide them by 2
stake = int(account.balance*sp)
else:
stake = int(account.balance*sp)
if stakePercent == 100:
stake -= 20
if stake is None:
raise Exception("Failed to get stake")
# Check if we have enough coins
if stake > config17.max_stake:
text = "Stake is greater than the maximum value. Will be used the maximum stake."
self.local.add_log(text, "warning")
stake = config17.max_stake
if config17.min_stake > stake:
text = "Stake less than the minimum stake. Minimum stake: {minStake}".format(minStake=config17.min_stake)
# self.local.add_log(text, "error")
raise Exception(text)
if stake > account.balance:
text = "Don't have enough coins. stake: {stake}, account balance: {balance}".format(stake=stake, balance=account.balance)
# self.local.add_log(text, "error")
raise Exception(text)
return stake
def GetMaxFactor(self):
# Either use defined maxFactor, or set maximal allowed by config17
maxFactor = self.local.db.get("maxFactor")
if maxFactor is None:
config17 = self.get_config_17()
maxFactor = config17.max_stake_factor / 65536
maxFactor = round(maxFactor, 1)
return maxFactor
def GetValidatorWallet(self):
wallet_name = self.local.db.get("validatorWalletName")
if wallet_name is None:
raise Exception("Validator wallet not configured: validatorWalletName not set")
wallet = self.GetLocalWallet(wallet_name)
return wallet
def ElectionEntry(self):
usePool = self.using_pool()
useController = self.using_liquid_staking()
wallet = self.GetValidatorWallet()
if wallet is None:
raise Exception("Validator wallet not found")
addrB64 = wallet.addrB64
self.local.add_log("start ElectionEntry function", "debug")
# Check if validator is not synchronized
validatorStatus = self.GetValidatorStatus()
validatorOutOfSync = validatorStatus.get("outOfSync")
if validatorOutOfSync > 60:
self.local.add_log("Validator is not synchronized", "error")
return
# Get startWorkTime and endWorkTime
fullElectorAddr = self.GetFullElectorAddr()
startWorkTime = self.GetActiveElectionId(fullElectorAddr)
# Check if elections started
if (startWorkTime == 0):
self.local.add_log("Elections have not yet begun", "info")
return
# Get ADNL address
adnl_addr = self.GetAdnlAddr()
if adnl_addr is None: