forked from wormhole-foundation/wormhole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadmin.py
1626 lines (1337 loc) · 67.9 KB
/
admin.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
# python3 -m pip install pycryptodomex uvarint pyteal web3 coincurve
import os
from os.path import exists
from time import time, sleep
from eth_abi import encode_single, encode_abi
from typing import List, Tuple, Dict, Any, Optional, Union
from base64 import b64decode
import base64
import random
import time
import hashlib
import uuid
import sys
import json
import uvarint
from local_blob import LocalBlob
from wormhole_core import getCoreContracts
from TmplSig import TmplSig
import argparse
from gentest import GenTest
from algosdk.v2client.algod import AlgodClient
from algosdk.kmd import KMDClient
from algosdk import account, mnemonic, abi
from algosdk.encoding import decode_address, encode_address
from algosdk.future import transaction
from pyteal import compileTeal, Mode, Expr
from pyteal import *
from algosdk.logic import get_application_address
from vaa_verify import get_vaa_verify
from Cryptodome.Hash import keccak
from algosdk.future.transaction import LogicSig
from token_bridge import get_token_bridge
from test_contract import get_test_app
from algosdk.v2client import indexer
import pprint
max_keys = 15
max_bytes_per_key = 127
bits_per_byte = 8
bits_per_key = max_bytes_per_key * bits_per_byte
max_bytes = max_bytes_per_key * max_keys
max_bits = bits_per_byte * max_bytes
class Account:
"""Represents a private key and address for an Algorand account"""
def __init__(self, privateKey: str) -> None:
self.sk = privateKey
self.addr = account.address_from_private_key(privateKey)
print (privateKey)
print (" " + self.getMnemonic())
print (" " + self.addr)
def getAddress(self) -> str:
return self.addr
def getPrivateKey(self) -> str:
return self.sk
def getMnemonic(self) -> str:
return mnemonic.from_private_key(self.sk)
@classmethod
def FromMnemonic(cls, m: str) -> "Account":
return cls(mnemonic.to_private_key(m))
class PendingTxnResponse:
def __init__(self, response: Dict[str, Any]) -> None:
self.poolError: str = response["pool-error"]
self.txn: Dict[str, Any] = response["txn"]
self.applicationIndex: Optional[int] = response.get("application-index")
self.assetIndex: Optional[int] = response.get("asset-index")
self.closeRewards: Optional[int] = response.get("close-rewards")
self.closingAmount: Optional[int] = response.get("closing-amount")
self.confirmedRound: Optional[int] = response.get("confirmed-round")
self.globalStateDelta: Optional[Any] = response.get("global-state-delta")
self.localStateDelta: Optional[Any] = response.get("local-state-delta")
self.receiverRewards: Optional[int] = response.get("receiver-rewards")
self.senderRewards: Optional[int] = response.get("sender-rewards")
self.innerTxns: List[Any] = response.get("inner-txns", [])
self.logs: List[bytes] = [b64decode(l) for l in response.get("logs", [])]
class PortalCore:
def __init__(self) -> None:
self.gt = None
self.foundation = None
self.devnet = False
self.ALGOD_ADDRESS = "http://localhost:4001"
self.ALGOD_TOKEN = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
self.FUNDING_AMOUNT = 100_000_000_000
self.KMD_ADDRESS = "http://localhost:4002"
self.KMD_TOKEN = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
self.KMD_WALLET_NAME = "unencrypted-default-wallet"
self.KMD_WALLET_PASSWORD = ""
self.INDEXER_TOKEN = "a" * 64
self.INDEXER_ADDRESS = 'http://localhost:8980'
self.INDEXER_ROUND = 0
self.NOTE_PREFIX = 'publishMessage'.encode()
self.myindexer = None
self.seed_amt = int(1002000) # The black magic in this number...
self.cache = {}
self.asset_cache = {}
self.kmdAccounts : Optional[List[Account]] = None
self.accountList : List[Account] = []
self.zeroPadBytes = "00"*32
self.tsig = TmplSig("sig")
def init(self, args) -> None:
self.args = args
self.ALGOD_ADDRESS = args.algod_address
self.ALGOD_TOKEN = args.algod_token
self.KMD_ADDRESS = args.kmd_address
self.KMD_TOKEN = args.kmd_token
self.KMD_WALLET_NAME = args.kmd_name
self.KMD_WALLET_PASSWORD = args.kmd_password
self.TARGET_ACCOUNT = args.mnemonic
self.coreid = args.coreid
self.tokenid = args.tokenid
if exists(self.args.env):
if self.gt == None:
self.gt = GenTest(False)
with open(self.args.env, encoding = 'utf-8') as f:
for line in f:
e = line.rstrip('\n').split("=")
if "INIT_SIGNERS_CSV" in e[0]:
self.gt.guardianKeys = e[1].split(",")
print("guardianKeys=" + str(self.gt.guardianKeys))
if "INIT_SIGNERS_KEYS_CSV" in e[0]:
self.gt.guardianPrivKeys = e[1].split(",")
print("guardianPrivKeys=" + str(self.gt.guardianPrivKeys))
def waitForTransaction(
self, client: AlgodClient, txID: str, timeout: int = 10
) -> PendingTxnResponse:
lastStatus = client.status()
lastRound = lastStatus["last-round"]
startRound = lastRound
while lastRound < startRound + timeout:
pending_txn = client.pending_transaction_info(txID)
if pending_txn.get("confirmed-round", 0) > 0:
return PendingTxnResponse(pending_txn)
if pending_txn["pool-error"]:
raise Exception("Pool error: {}".format(pending_txn["pool-error"]))
lastStatus = client.status_after_block(lastRound + 1)
lastRound += 1
raise Exception(
"Transaction {} not confirmed after {} rounds".format(txID, timeout)
)
def getKmdClient(self) -> KMDClient:
return KMDClient(self.KMD_TOKEN, self.KMD_ADDRESS)
def getGenesisAccounts(self) -> List[Account]:
if self.kmdAccounts is None:
kmd = self.getKmdClient()
wallets = kmd.list_wallets()
walletID = None
for wallet in wallets:
if wallet["name"] == self.KMD_WALLET_NAME:
walletID = wallet["id"]
break
if walletID is None:
raise Exception("Wallet not found: {}".format(self.KMD_WALLET_NAME))
walletHandle = kmd.init_wallet_handle(walletID, self.KMD_WALLET_PASSWORD)
try:
addresses = kmd.list_keys(walletHandle)
privateKeys = [
kmd.export_key(walletHandle, self.KMD_WALLET_PASSWORD, addr)
for addr in addresses
]
self.kmdAccounts = [Account(sk) for sk in privateKeys]
finally:
kmd.release_wallet_handle(walletHandle)
return self.kmdAccounts
def _fundFromGenesis(self, accountList, fundingAmt, client):
genesisAccounts = self.getGenesisAccounts()
suggestedParams = client.suggested_params()
txns: List[transaction.Transaction] = []
for i, a in enumerate(accountList):
fundingAccount = genesisAccounts[i % len(genesisAccounts)]
txns.append(
transaction.PaymentTxn(
sender=fundingAccount.getAddress(),
receiver=a.getAddress(),
amt=fundingAmt,
sp=suggestedParams,
)
)
txns = transaction.assign_group_id(txns)
signedTxns = [
txn.sign(genesisAccounts[i % len(genesisAccounts)].getPrivateKey())
for i, txn in enumerate(txns)
]
client.send_transactions(signedTxns)
self.waitForTransaction(client, signedTxns[0].get_txid())
def getTemporaryAccount(self, client: AlgodClient) -> Account:
if len(self.accountList) == 0:
sks = [account.generate_account()[0] for i in range(3)]
self.accountList = [Account(sk) for sk in sks]
self._fundFromGenesis(self.accountList, self.FUNDING_AMOUNT, client)
return self.accountList.pop()
def fundDevAccounts(self, client: AlgodClient):
devAcctsMnemonics = [
"provide warfare better filter glory civil help jacket alpha penalty van fiber code upgrade web more curve sauce merit bike satoshi blame orphan absorb modify",
"album neglect very nasty input trick annual arctic spray task candy unfold letter drill glove sword flock omit dial rather session mesh slow abandon slab",
"blue spring teach silent cheap grace desk crack agree leave tray lady chair reopen midnight lottery glove congress lounge arrow fine junior mirror above purchase",
"front rifle urge write push dynamic oil vital section blast protect suffer shoulder base address teach sight trap trial august mechanic border leaf absorb attract",
"fat pet option agree father glue range ancient curtain pottery search raven club save crane sting gift seven butter decline image toward kidney above balance"
]
accountList = []
accountFunding = 400000000000000 # 400M algos
for mnemo in devAcctsMnemonics:
acc = Account.FromMnemonic(mnemo)
print('Funding dev account {} with {} uALGOs'.format(acc.addr, accountFunding))
accountList.append(acc)
self._fundFromGenesis(accountList, accountFunding, client)
def getAlgodClient(self) -> AlgodClient:
return AlgodClient(self.ALGOD_TOKEN, self.ALGOD_ADDRESS)
def getBalances(self, client: AlgodClient, account: str) -> Dict[int, int]:
balances: Dict[int, int] = dict()
accountInfo = client.account_info(account)
# set key 0 to Algo balance
balances[0] = accountInfo["amount"]
assets: List[Dict[str, Any]] = accountInfo.get("assets", [])
for assetHolding in assets:
assetID = assetHolding["asset-id"]
amount = assetHolding["amount"]
balances[assetID] = amount
return balances
def fullyCompileContract(self, client: AlgodClient, contract: Expr) -> bytes:
teal = compileTeal(contract, mode=Mode.Application, version=6)
response = client.compile(teal)
return response
# helper function that formats global state for printing
def format_state(self, state):
formatted = {}
for item in state:
key = item['key']
value = item['value']
formatted_key = base64.b64decode(key).decode('utf-8')
if value['type'] == 1:
# byte string
if formatted_key == 'voted':
formatted_value = base64.b64decode(value['bytes']).decode('utf-8')
else:
formatted_value = value['bytes']
formatted[formatted_key] = formatted_value
else:
# integer
formatted[formatted_key] = value['uint']
return formatted
# helper function to read app global state
def read_global_state(self, client, addr, app_id):
results = self.client.application_info(app_id)
return self.format_state(results['params']['global-state'])
def read_state(self, client, addr, app_id):
results = client.account_info(addr)
apps_created = results['created-apps']
for app in apps_created:
if app['id'] == app_id:
return app
return {}
def encoder(self, type, val):
if type == 'uint8':
return encode_single(type, val).hex()[62:64]
if type == 'uint16':
return encode_single(type, val).hex()[60:64]
if type == 'uint32':
return encode_single(type, val).hex()[56:64]
if type == 'uint64':
return encode_single(type, val).hex()[64-(16):64]
if type == 'uint128':
return encode_single(type, val).hex()[64-(32):64]
if type == 'uint256' or type == 'bytes32':
return encode_single(type, val).hex()[64-(64):64]
raise Exception("invalid type")
def devnetUpgradeVAA(self):
v = self.genUpgradePayload()
print("core payload: " + str(v[0]))
print("token payload: " + str(v[1]))
if self.gt == None:
self.gt = GenTest(False)
emitter = bytes.fromhex(self.zeroPadBytes[0:(31*2)] + "04")
guardianSet = self.getGovSet()
print("guardianSet: " + str(guardianSet))
nonce = int(random.random() * 20000)
ret = [
self.gt.createSignedVAA(guardianSet, self.gt.guardianPrivKeys, int(time.time()), nonce, 1, emitter, int(random.random() * 20000), 32, 8, v[0]),
self.gt.createSignedVAA(guardianSet, self.gt.guardianPrivKeys, int(time.time()), nonce, 1, emitter, int(random.random() * 20000), 32, 8, v[1]),
]
# pprint.pprint(self.parseVAA(bytes.fromhex(ret[0])))
# pprint.pprint(self.parseVAA(bytes.fromhex(ret[1])))
return ret
def getMessageFee(self):
s = self.client.application_info(self.coreid)["params"]["global-state"]
k = base64.b64encode(b"MessageFee").decode('utf-8')
for x in s:
if x["key"] == k:
return x["value"]["uint"]
return -1
def getGovSet(self):
s = self.client.application_info(self.coreid)["params"]["global-state"]
k = base64.b64encode(b"currentGuardianSetIndex").decode('utf-8')
for x in s:
if x["key"] == k:
return x["value"]["uint"]
return -1
def genUpgradePayload(self):
approval1, clear1 = getCoreContracts(False, self.args.core_approve, self.args.core_clear, self.client, seed_amt=self.seed_amt, tmpl_sig=self.tsig, devMode = self.devnet or self.args.testnet)
approval2, clear2 = get_token_bridge(False, self.args.token_approve, self.args.token_clear, self.client, seed_amt=self.seed_amt, tmpl_sig=self.tsig, devMode = self.devnet or self.args.testnet)
return self.genUpgradePayloadBody(approval1, approval2)
def genUpgradePayloadBody(self, approval1, approval2):
b = self.zeroPadBytes[0:(28*2)]
b += self.encoder("uint8", ord("C"))
b += self.encoder("uint8", ord("o"))
b += self.encoder("uint8", ord("r"))
b += self.encoder("uint8", ord("e"))
b += self.encoder("uint8", 1)
b += self.encoder("uint16", 8)
b += decode_address(approval1["hash"]).hex()
print("core hash: " + decode_address(approval1["hash"]).hex())
ret = [b]
b = self.zeroPadBytes[0:((32 -11)*2)]
b += self.encoder("uint8", ord("T"))
b += self.encoder("uint8", ord("o"))
b += self.encoder("uint8", ord("k"))
b += self.encoder("uint8", ord("e"))
b += self.encoder("uint8", ord("n"))
b += self.encoder("uint8", ord("B"))
b += self.encoder("uint8", ord("r"))
b += self.encoder("uint8", ord("i"))
b += self.encoder("uint8", ord("d"))
b += self.encoder("uint8", ord("g"))
b += self.encoder("uint8", ord("e"))
b += self.encoder("uint8", 2) # action
b += self.encoder("uint16", 8) # target chain
b += decode_address(approval2["hash"]).hex()
print("token hash: " + decode_address(approval2["hash"]).hex())
ret.append(b)
return ret
def createPortalCoreApp(
self,
client: AlgodClient,
sender: Account,
) -> int:
approval, clear = getCoreContracts(False, self.args.core_approve, self.args.core_clear, client, seed_amt=self.seed_amt, tmpl_sig=self.tsig, devMode = self.devnet or self.args.testnet)
globalSchema = transaction.StateSchema(num_uints=8, num_byte_slices=40)
localSchema = transaction.StateSchema(num_uints=0, num_byte_slices=16)
app_args = [ ]
txn = transaction.ApplicationCreateTxn(
sender=sender.getAddress(),
on_complete=transaction.OnComplete.NoOpOC,
approval_program=b64decode(approval["result"]),
clear_program=b64decode(clear["result"]),
global_schema=globalSchema,
local_schema=localSchema,
extra_pages = 1,
app_args=app_args,
sp=client.suggested_params(),
)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
response = self.waitForTransaction(client, signedTxn.get_txid())
assert response.applicationIndex is not None and response.applicationIndex > 0
# Lets give it a bit of money so that it is not a "ghost" account
txn = transaction.PaymentTxn(sender = sender.getAddress(), sp = client.suggested_params(), receiver = get_application_address(response.applicationIndex), amt = 100000)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
return response.applicationIndex
def createTokenBridgeApp(
self,
client: AlgodClient,
sender: Account,
) -> int:
approval, clear = get_token_bridge(False, self.args.token_approve, self.args.token_clear, client, seed_amt=self.seed_amt, tmpl_sig=self.tsig, devMode = self.devnet or self.args.testnet)
if len(b64decode(approval["result"])) > 4060:
print("token bridge contract is too large... This might prevent updates later")
globalSchema = transaction.StateSchema(num_uints=4, num_byte_slices=30)
localSchema = transaction.StateSchema(num_uints=0, num_byte_slices=16)
app_args = [self.coreid, decode_address(get_application_address(self.coreid))]
txn = transaction.ApplicationCreateTxn(
sender=sender.getAddress(),
on_complete=transaction.OnComplete.NoOpOC,
approval_program=b64decode(approval["result"]),
clear_program=b64decode(clear["result"]),
global_schema=globalSchema,
local_schema=localSchema,
app_args=app_args,
extra_pages = 2,
sp=client.suggested_params(),
)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
response = self.waitForTransaction(client, signedTxn.get_txid())
#pprint.pprint(response.__dict__)
assert response.applicationIndex is not None and response.applicationIndex > 0
# Lets give it a bit of money so that it is not a "ghost" account
txn = transaction.PaymentTxn(sender = sender.getAddress(), sp = client.suggested_params(), receiver = get_application_address(response.applicationIndex), amt = 100000)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
return response.applicationIndex
def createTestApp(
self,
client: AlgodClient,
sender: Account,
) -> int:
approval, clear = get_test_app(client)
globalSchema = transaction.StateSchema(num_uints=4, num_byte_slices=30)
localSchema = transaction.StateSchema(num_uints=0, num_byte_slices=16)
txn = transaction.ApplicationCreateTxn(
sender=sender.getAddress(),
on_complete=transaction.OnComplete.NoOpOC,
approval_program=b64decode(approval["result"]),
clear_program=b64decode(clear["result"]),
global_schema=globalSchema,
local_schema=localSchema,
sp=client.suggested_params(),
)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
response = self.waitForTransaction(client, signedTxn.get_txid())
assert response.applicationIndex is not None and response.applicationIndex > 0
# Lets give it a bit of money so that it is not a "ghost" account
txn = transaction.PaymentTxn(sender = sender.getAddress(), sp = client.suggested_params(), receiver = get_application_address(response.applicationIndex), amt = 100000)
signedTxn = txn.sign(sender.getPrivateKey())
client.send_transaction(signedTxn)
return response.applicationIndex
def account_exists(self, client, app_id, addr):
try:
ai = client.account_info(addr)
if "apps-local-state" not in ai:
return False
for app in ai["apps-local-state"]:
if app["id"] == app_id:
return True
except:
print("Failed to find account {}".format(addr))
return False
def optin(self, client, sender, app_id, idx, emitter, doCreate=True):
aa = decode_address(get_application_address(app_id)).hex()
lsa = self.tsig.populate(
{
"TMPL_APP_ID": app_id,
"TMPL_APP_ADDRESS": aa,
"TMPL_ADDR_IDX": idx,
"TMPL_EMITTER_ID": emitter,
}
)
sig_addr = lsa.address()
if sig_addr not in self.cache and not self.account_exists(client, app_id, sig_addr):
if doCreate:
# pprint.pprint(("Creating", app_id, idx, emitter, sig_addr))
# Create it
sp = client.suggested_params()
seed_txn = transaction.PaymentTxn(sender = sender.getAddress(),
sp = sp,
receiver = sig_addr,
amt = self.seed_amt)
seed_txn.fee = seed_txn.fee * 2
optin_txn = transaction.ApplicationOptInTxn(sig_addr, sp, app_id, rekey_to=get_application_address(app_id))
optin_txn.fee = 0
transaction.assign_group_id([seed_txn, optin_txn])
signed_seed = seed_txn.sign(sender.getPrivateKey())
signed_optin = transaction.LogicSigTransaction(optin_txn, lsa)
client.send_transactions([signed_seed, signed_optin])
self.waitForTransaction(client, signed_optin.get_txid())
self.cache[sig_addr] = True
return sig_addr
def parseSeqFromLog(self, txn):
return int.from_bytes(b64decode(txn.innerTxns[0]["logs"][0]), "big")
def getCreator(self, client, sender, asset_id):
return client.asset_info(asset_id)["params"]["creator"]
def sendTxn(self, client, sender, txns, doWait):
transaction.assign_group_id(txns)
grp = []
pk = sender.getPrivateKey()
for t in txns:
grp.append(t.sign(pk))
client.send_transactions(grp)
if doWait:
return self.waitForTransaction(client, grp[-1].get_txid())
else:
return grp[-1].get_txid()
def bootGuardians(self, vaa, client, sender, coreid):
p = self.parseVAA(vaa)
if "NewGuardianSetIndex" not in p:
raise Exception("invalid guardian VAA")
seq_addr = self.optin(client, sender, coreid, int(p["sequence"] / max_bits), p["chainRaw"].hex() + p["emitter"].hex())
guardian_addr = self.optin(client, sender, coreid, p["index"], b"guardian".hex())
newguardian_addr = self.optin(client, sender, coreid, p["NewGuardianSetIndex"], b"guardian".hex())
# wormhole is not a cheap protocol... we need to buy ourselves
# some extra CPU cycles by having an early txn do nothing.
# This leaves cycles over for later txn's in the same group
sp = client.suggested_params()
txns = [
transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"nop", b"0"],
sp=sp
),
transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"nop", b"1"],
sp=sp
),
transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"init", vaa, decode_address(self.vaa_verify["hash"])],
accounts=[seq_addr, guardian_addr, newguardian_addr],
sp=sp
),
transaction.PaymentTxn(
sender=sender.getAddress(),
receiver=self.vaa_verify["hash"],
amt=100000,
sp=sp
)
]
return self.sendTxn(client, sender, txns, True)
def decodeLocalState(self, client, sender, appid, addr):
app_state = None
ai = client.account_info(addr)
for app in ai["apps-local-state"]:
if app["id"] == appid:
app_state = app["key-value"]
ret = b''
if None != app_state:
vals = {}
e = bytes.fromhex("00"*127)
for kv in app_state:
k = base64.b64decode(kv["key"])
if k == "meta":
continue
key = int.from_bytes(k, "big")
v = base64.b64decode(kv["value"]["bytes"])
if v != e:
vals[key] = v
for k in sorted(vals.keys()):
ret = ret + vals[k]
return ret
# There is no client side duplicate suppression, error checking, or validity
# checking. We need to be able to detect all failure cases in
# the contract itself and we want to use this to drive the failure test
# cases
def simpleVAA(self, vaa, client, sender, appid):
p = {"version": int.from_bytes(vaa[0:1], "big"), "index": int.from_bytes(vaa[1:5], "big"), "siglen": int.from_bytes(vaa[5:6], "big")}
ret["signatures"] = vaa[6:(ret["siglen"] * 66) + 6]
ret["sigs"] = []
for i in range(ret["siglen"]):
ret["sigs"].append(vaa[(6 + (i * 66)):(6 + (i * 66)) + 66].hex())
off = (ret["siglen"] * 66) + 6
ret["digest"] = vaa[off:] # This is what is actually signed...
ret["timestamp"] = int.from_bytes(vaa[off:(off + 4)], "big")
off += 4
ret["nonce"] = int.from_bytes(vaa[off:(off + 4)], "big")
off += 4
ret["chainRaw"] = vaa[off:(off + 2)]
ret["chain"] = int.from_bytes(vaa[off:(off + 2)], "big")
off += 2
ret["emitter"] = vaa[off:(off + 32)]
off += 32
ret["sequence"] = int.from_bytes(vaa[off:(off + 8)], "big")
off += 8
ret["consistency"] = int.from_bytes(vaa[off:(off + 1)], "big")
off += 1
seq_addr = self.optin(client, sender, appid, int(p["sequence"] / max_bits), p["chainRaw"].hex() + p["emitter"].hex())
# And then the signatures to help us verify the vaa_s
guardian_addr = self.optin(client, sender, self.coreid, p["index"], b"guardian".hex())
accts = [seq_addr, guardian_addr]
keys = self.decodeLocalState(client, sender, self.coreid, guardian_addr)
sp = client.suggested_params()
txns = []
# Right now there is not really a good way to estimate the fees,
# in production, on a conjested network, how much verifying
# the signatures is going to cost.
# So, what we do instead
# is we top off the verifier back up to 2A so effectively we
# are paying for the previous persons overrage which on a
# unconjested network should be zero
pmt = 3000
bal = self.getBalances(client, self.vaa_verify["hash"])
if ((200000 - bal[0]) >= pmt):
pmt = 200000 - bal[0]
#print("Sending %d algo to cover fees" % (pmt))
txns.append(
transaction.PaymentTxn(
sender = sender.getAddress(),
sp = sp,
receiver = self.vaa_verify["hash"],
amt = pmt
)
)
# How many signatures can we process in a single txn... we can do 9!
bsize = (9*66)
blocks = int(len(p["signatures"]) / bsize) + 1
# We don't pass the entire payload in but instead just pass it pre digested. This gets around size
# limitations with lsigs AND reduces the cost of the entire operation on a conjested network by reducing the
# bytes passed into the transaction
digest = keccak.new(digest_bits=256).update(keccak.new(digest_bits=256).update(p["digest"]).digest()).digest()
for i in range(blocks):
# Which signatures will we be verifying in this block
sigs = p["signatures"][(i * bsize):]
if (len(sigs) > bsize):
sigs = sigs[:bsize]
# keys
kset = b''
# Grab the key associated the signature
for q in range(int(len(sigs) / 66)):
# Which guardian is this signature associated with
g = sigs[q * 66]
key = keys[((g * 20) + 1) : (((g + 1) * 20) + 1)]
kset = kset + key
txns.append(transaction.ApplicationCallTxn(
sender=self.vaa_verify["hash"],
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"verifySigs", sigs, kset, digest],
accounts=accts,
sp=sp
))
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"verifyVAA", vaa],
accounts=accts,
sp=sp
))
return txns
def signVAA(self, client, sender, txns):
transaction.assign_group_id(txns)
grp = []
pk = sender.getPrivateKey()
for t in txns:
if ("app_args" in t.__dict__ and len(t.app_args) > 0 and t.app_args[0] == b"verifySigs"):
grp.append(transaction.LogicSigTransaction(t, self.vaa_verify["lsig"]))
else:
grp.append(t.sign(pk))
client.send_transactions(grp)
ret = []
for x in grp:
response = self.waitForTransaction(client, x.get_txid())
if "logs" in response.__dict__ and len(response.__dict__["logs"]) > 0:
ret.append(response.__dict__["logs"])
return ret
def check_bits_set(self, client, app_id, addr, seq):
bits_set = {}
app_state = None
ai = client.account_info(addr)
for app in ai["apps-local-state"]:
if app["id"] == app_id:
app_state = app["key-value"]
if app_state == None:
return False
start = int(seq / max_bits) * max_bits
s = int((seq - start) / bits_per_key)
b = int(((seq - start) - (s * bits_per_key)) / 8)
k = base64.b64encode(s.to_bytes(1, "big")).decode('utf-8')
for kv in app_state:
if kv["key"] != k:
continue
v = base64.b64decode(kv["value"]["bytes"])
bt = 1 << (seq%8)
return ((v[b] & bt) != 0)
return False
def submitVAA(self, vaa, client, sender, appid):
# A lot of our logic here depends on parseVAA and knowing what the payload is..
p = self.parseVAA(vaa)
#pprint.pprint(p)
seq_addr = self.optin(client, sender, appid, int(p["sequence"] / max_bits), p["chainRaw"].hex() + p["emitter"].hex())
# assert self.check_bits_set(client, appid, seq_addr, p["sequence"]) == False
# And then the signatures to help us verify the vaa_s
guardian_addr = self.optin(client, sender, self.coreid, p["index"], b"guardian".hex())
accts = [seq_addr, guardian_addr]
# If this happens to be setting up a new guardian set, we probably need it as well...
if p["Meta"] == "CoreGovernance" and p["action"] == 2:
newguardian_addr = self.optin(client, sender, self.coreid, p["NewGuardianSetIndex"], b"guardian".hex())
accts.append(newguardian_addr)
# When we attest for a new token, we need some place to store the info... later we will need to
# mirror the other way as well
if p["Meta"] == "TokenBridge Attest" or p["Meta"] == "TokenBridge Transfer" or p["Meta"] == "TokenBridge Transfer With Payload":
if p["FromChain"] != 8:
chain_addr = self.optin(client, sender, self.tokenid, p["FromChain"], p["Contract"])
else:
asset_id = int.from_bytes(bytes.fromhex(p["Contract"]), "big")
chain_addr = self.optin(client, sender, self.tokenid, asset_id, b"native".hex())
accts.append(chain_addr)
keys = self.decodeLocalState(client, sender, self.coreid, guardian_addr)
print("keys: " + keys.hex())
sp = client.suggested_params()
txns = []
# How many signatures can we process in a single txn... we can do 9!
bsize = (9*66)
# audit: this was incorrectly adding an extra, empty block when the amount
# of signatures was a multiple of 9. fixed.
blocks = int(len(p["signatures"]) / bsize) + int(vaa[5] % 9 != 0)
# We don't pass the entire payload in but instead just pass it pre digested. This gets around size
# limitations with lsigs AND reduces the cost of the entire operation on a conjested network by reducing the
# bytes passed into the transaction
digest = keccak.new(digest_bits=256).update(keccak.new(digest_bits=256).update(p["digest"]).digest()).digest()
for i in range(blocks):
# Which signatures will we be verifying in this block
sigs = p["signatures"][(i * bsize):]
if (len(sigs) > bsize):
sigs = sigs[:bsize]
# keys
kset = b''
# Grab the key associated the signature
for q in range(int(len(sigs) / 66)):
# Which guardian is this signature associated with
g = sigs[q * 66]
key = keys[((g * 20) + 1) : (((g + 1) * 20) + 1)]
kset = kset + key
txns.append(transaction.ApplicationCallTxn(
sender=self.vaa_verify["hash"],
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"verifySigs", sigs, kset, digest],
accounts=accts,
sp=sp
))
txns[-1].fee = 0
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"verifyVAA", vaa],
accounts=accts,
sp=sp
))
txns[-1].fee = txns[-1].fee * (1 + blocks)
if p["Meta"] == "CoreGovernance":
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"governance", vaa],
accounts=accts,
sp=sp
))
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.coreid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"nop", 5],
sp=sp
))
if p["Meta"] == "TokenBridge RegisterChain" or p["Meta"] == "TokenBridge UpgradeContract":
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.tokenid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"governance", vaa],
accounts=accts,
foreign_apps = [self.coreid],
sp=sp
))
if p["Meta"] == "TokenBridge Attest":
# if we DO decode it, we can do a sanity check... of
# course, the hacker might NOT decode it so we have to
# handle both cases...
asset = (self.decodeLocalState(client, sender, self.tokenid, chain_addr))
foreign_assets = []
if (len(asset) > 8):
foreign_assets.append(int.from_bytes(asset[0:8], "big"))
txns.append(
transaction.PaymentTxn(
sender = sender.getAddress(),
sp = sp,
receiver = chain_addr,
amt = 100000
)
)
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.tokenid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"nop", 1],
sp=sp
))
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.tokenid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"nop", 2],
sp=sp
))
txns.append(transaction.ApplicationCallTxn(
sender=sender.getAddress(),
index=self.tokenid,
on_complete=transaction.OnComplete.NoOpOC,
app_args=[b"receiveAttest", vaa],
accounts=accts,
foreign_assets = foreign_assets,
sp=sp
))
txns[-1].fee = txns[-1].fee * 2
if p["Meta"] == "TokenBridge Transfer" or p["Meta"] == "TokenBridge Transfer With Payload":
foreign_assets = []
a = 0
if p["FromChain"] != 8:
asset = (self.decodeLocalState(client, sender, self.tokenid, chain_addr))
if (len(asset) > 8):
a = int.from_bytes(asset[0:8], "big")
else:
a = int.from_bytes(bytes.fromhex(p["Contract"]), "big")
# The receiver needs to be optin in to receive the coins... Yeah, the relayer pays for this
aid = 0
if p["ToChain"] == 8 and p["Type"] == 3:
aid = int.from_bytes(bytes.fromhex(p["ToAddress"]), "big")
addr = get_application_address(aid)