-
Notifications
You must be signed in to change notification settings - Fork 2k
/
did_wallet.py
1482 lines (1378 loc) · 62.2 KB
/
did_wallet.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
from __future__ import annotations
import dataclasses
import json
import logging
import re
import time
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Set, Tuple, cast
from chia_rs import AugSchemeMPL, G1Element, G2Element
from chia.protocols.wallet_protocol import CoinState
from chia.server.ws_connection import WSChiaConnection
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.types.coin_spend import CoinSpend, make_spend
from chia.types.signing_mode import CHIP_0002_SIGN_MESSAGE_PREFIX, SigningMode
from chia.types.spend_bundle import SpendBundle
from chia.util.ints import uint16, uint32, uint64, uint128
from chia.wallet.conditions import (
AssertCoinAnnouncement,
Condition,
ConditionValidTimes,
CreateCoinAnnouncement,
parse_timelock_info,
)
from chia.wallet.derivation_record import DerivationRecord
from chia.wallet.did_wallet import did_wallet_puzzles
from chia.wallet.did_wallet.did_info import DIDCoinData, DIDInfo
from chia.wallet.did_wallet.did_wallet_puzzles import match_did_puzzle, uncurry_innerpuz
from chia.wallet.lineage_proof import LineageProof
from chia.wallet.payment import Payment
from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import (
DEFAULT_HIDDEN_PUZZLE_HASH,
calculate_synthetic_secret_key,
puzzle_for_pk,
puzzle_hash_for_pk,
)
from chia.wallet.singleton import (
SINGLETON_LAUNCHER_PUZZLE,
create_singleton_puzzle,
create_singleton_puzzle_hash,
get_inner_puzzle_from_singleton,
)
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.uncurried_puzzle import uncurry_puzzle
from chia.wallet.util.compute_memos import compute_memos
from chia.wallet.util.curry_and_treehash import NIL_TREEHASH, shatree_int, shatree_pair
from chia.wallet.util.transaction_type import TransactionType
from chia.wallet.util.tx_config import DEFAULT_TX_CONFIG, CoinSelectionConfig, TXConfig
from chia.wallet.util.wallet_sync_utils import fetch_coin_spend, fetch_coin_spend_for_coin_state
from chia.wallet.util.wallet_types import WalletType
from chia.wallet.wallet import Wallet
from chia.wallet.wallet_coin_record import WalletCoinRecord
from chia.wallet.wallet_info import WalletInfo
from chia.wallet.wallet_protocol import WalletProtocol
class DIDWallet:
if TYPE_CHECKING:
if TYPE_CHECKING:
_protocol_check: ClassVar[WalletProtocol[DIDCoinData]] = cast("DIDWallet", None)
wallet_state_manager: Any
log: logging.Logger
wallet_info: WalletInfo
did_info: DIDInfo
standard_wallet: Wallet
base_puzzle_program: Optional[bytes]
base_inner_puzzle_hash: Optional[bytes32]
wallet_id: int
@staticmethod
async def create_new_did_wallet(
wallet_state_manager: Any,
wallet: Wallet,
amount: uint64,
backups_ids: List[bytes32] = [],
num_of_backup_ids_needed: uint64 = None,
metadata: Dict[str, str] = {},
name: Optional[str] = None,
fee: uint64 = uint64(0),
):
"""
Create a brand new DID wallet
This must be called under the wallet state manager lock
:param wallet_state_manager: Wallet state manager
:param wallet: Standard wallet
:param amount: Amount of the DID coin
:param backups_ids: A list of DIDs used for recovery this DID
:param num_of_backup_ids_needed: Needs how many recovery DIDs at least
:param metadata: Metadata saved in the DID
:param name: Wallet name
:param fee: transaction fee
:return: DID wallet
"""
self = DIDWallet()
self.wallet_state_manager = wallet_state_manager
if name is None:
name = self.generate_wallet_name()
self.base_puzzle_program = None
self.base_inner_puzzle_hash = None
self.standard_wallet = wallet
self.log = logging.getLogger(name if name else __name__)
std_wallet_id = self.standard_wallet.wallet_id
bal = await wallet_state_manager.get_confirmed_balance_for_wallet(std_wallet_id)
if amount > bal:
raise ValueError("Not enough balance")
if amount & 1 == 0:
raise ValueError("DID amount must be odd number")
if num_of_backup_ids_needed is None:
num_of_backup_ids_needed = uint64(len(backups_ids))
if num_of_backup_ids_needed > len(backups_ids):
raise ValueError("Cannot require more IDs than are known.")
self.did_info = DIDInfo(
origin_coin=None,
backup_ids=backups_ids,
num_of_backup_ids_needed=num_of_backup_ids_needed,
parent_info=[],
current_inner=None,
temp_coin=None,
temp_puzhash=None,
temp_pubkey=None,
sent_recovery_transaction=False,
metadata=json.dumps(metadata),
)
info_as_string = json.dumps(self.did_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name=name, wallet_type=WalletType.DECENTRALIZED_ID.value, data=info_as_string
)
self.wallet_id = self.wallet_info.id
std_wallet_id = self.standard_wallet.wallet_id
bal = await wallet_state_manager.get_confirmed_balance_for_wallet(std_wallet_id)
if amount > bal:
raise ValueError("Not enough balance")
try:
txs = await self.generate_new_decentralised_id(amount, DEFAULT_TX_CONFIG, fee)
except Exception:
await wallet_state_manager.user_store.delete_wallet(self.id())
raise
await self.wallet_state_manager.add_pending_transactions(txs)
await self.wallet_state_manager.add_new_wallet(self)
return self
@staticmethod
async def create_new_did_wallet_from_recovery(
wallet_state_manager: Any,
wallet: Wallet,
backup_data: str,
name: Optional[str] = None,
):
"""
Create a DID wallet from a backup file
:param wallet_state_manager: Wallet state manager
:param wallet: Standard wallet
:param backup_data: A serialized backup data
:param name: Wallet name
:return: DID wallet
"""
self = DIDWallet()
self.wallet_state_manager = wallet_state_manager
if name is None:
name = self.generate_wallet_name()
self.base_puzzle_program = None
self.base_inner_puzzle_hash = None
self.standard_wallet = wallet
self.log = logging.getLogger(name if name else __name__)
self.log.info("Creating DID wallet from recovery file ...")
# load backup will also set our DIDInfo
self.did_info = DIDWallet.deserialize_backup_data(backup_data)
self.check_existed_did()
info_as_string = json.dumps(self.did_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name=name, wallet_type=WalletType.DECENTRALIZED_ID.value, data=info_as_string
)
await self.wallet_state_manager.add_new_wallet(self)
await self.save_info(self.did_info)
await self.wallet_state_manager.update_wallet_puzzle_hashes(self.wallet_info.id)
await self.load_parent(self.did_info)
if self.wallet_info is None:
raise ValueError("Internal Error")
self.wallet_id = self.wallet_info.id
return self
@staticmethod
async def create_new_did_wallet_from_coin_spend(
wallet_state_manager: Any,
wallet: Wallet,
launch_coin: Coin,
inner_puzzle: Program,
coin_spend: CoinSpend,
name: Optional[str] = None,
):
"""
Create a DID wallet from a transfer
:param wallet_state_manager: Wallet state manager
:param wallet: Main wallet
:param launch_coin: The launch coin of the DID
:param inner_puzzle: DID inner puzzle
:param coin_spend: DID transfer spend
:param name: Wallet name
:return: DID wallet
"""
self = DIDWallet()
self.wallet_state_manager = wallet_state_manager
if name is None:
name = self.generate_wallet_name()
self.base_puzzle_program = None
self.base_inner_puzzle_hash = None
self.standard_wallet = wallet
self.log = logging.getLogger(name if name else __name__)
self.log.info(f"Creating DID wallet from a coin spend {launch_coin} ...")
# Create did info from the coin spend
args = did_wallet_puzzles.uncurry_innerpuz(inner_puzzle)
if args is None:
raise ValueError("Cannot uncurry the DID puzzle.")
_, recovery_list_hash, num_verification, _, metadata = args
full_solution: Program = Program.from_bytes(bytes(coin_spend.solution))
inner_solution: Program = full_solution.rest().rest().first()
recovery_list: List[bytes32] = []
backup_required: int = num_verification.as_int()
if recovery_list_hash != NIL_TREEHASH:
try:
for did in inner_solution.rest().rest().rest().rest().rest().as_python():
recovery_list.append(bytes32(did[0]))
except Exception:
self.log.warning(
f"DID {launch_coin.name().hex()} has a recovery list hash but missing a reveal,"
" you may need to reset the recovery info."
)
self.did_info = DIDInfo(
origin_coin=launch_coin,
backup_ids=recovery_list,
num_of_backup_ids_needed=uint64(backup_required),
parent_info=[],
current_inner=inner_puzzle,
temp_coin=None,
temp_puzhash=None,
temp_pubkey=None,
sent_recovery_transaction=False,
metadata=json.dumps(did_wallet_puzzles.did_program_to_metadata(metadata)),
)
self.check_existed_did()
info_as_string = json.dumps(self.did_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name=name, wallet_type=WalletType.DECENTRALIZED_ID.value, data=info_as_string
)
await self.wallet_state_manager.add_new_wallet(self)
await self.wallet_state_manager.update_wallet_puzzle_hashes(self.wallet_info.id)
await self.load_parent(self.did_info)
self.log.info(f"New DID wallet created {info_as_string}.")
if self.wallet_info is None:
raise ValueError("Internal Error")
self.wallet_id = self.wallet_info.id
return self
@staticmethod
async def create(
wallet_state_manager: Any,
wallet: Wallet,
wallet_info: WalletInfo,
name: str = None,
):
"""
Create a DID wallet based on the local database
:param wallet_state_manager: Wallet state manager
:param wallet: Standard wallet
:param wallet_info: Serialized WalletInfo
:param name: Wallet name
:return:
"""
self = DIDWallet()
self.log = logging.getLogger(name if name else __name__)
self.wallet_state_manager = wallet_state_manager
self.wallet_info = wallet_info
self.wallet_id = wallet_info.id
self.standard_wallet = wallet
self.wallet_info = wallet_info
self.did_info = DIDInfo.from_json_dict(json.loads(wallet_info.data))
self.base_puzzle_program = None
self.base_inner_puzzle_hash = None
return self
@classmethod
def type(cls) -> WalletType:
return WalletType.DECENTRALIZED_ID
def id(self) -> uint32:
return self.wallet_info.id
async def get_confirmed_balance(self, record_list=None) -> uint128:
if record_list is None:
record_list = await self.wallet_state_manager.coin_store.get_unspent_coins_for_wallet(self.id())
amount: uint128 = uint128(0)
for record in record_list:
parent = self.get_parent_for_coin(record.coin)
if parent is not None:
amount = uint128(amount + record.coin.amount)
self.log.info(f"Confirmed balance for did wallet is {amount}")
return uint128(amount)
async def get_pending_change_balance(self) -> uint64:
unconfirmed_tx = await self.wallet_state_manager.tx_store.get_unconfirmed_for_wallet(self.id())
addition_amount = 0
for record in unconfirmed_tx:
our_spend = False
for coin in record.removals:
if await self.wallet_state_manager.does_coin_belong_to_wallet(coin, self.id()):
our_spend = True
break
if our_spend is not True:
continue
for coin in record.additions:
if await self.wallet_state_manager.does_coin_belong_to_wallet(coin, self.id()):
addition_amount += coin.amount
return uint64(addition_amount)
async def get_unconfirmed_balance(self, record_list=None) -> uint128:
return await self.wallet_state_manager.get_unconfirmed_balance(self.id(), record_list)
async def select_coins(
self,
amount: uint64,
coin_selection_config: CoinSelectionConfig,
) -> Set[Coin]:
try:
return {await self.get_coin()}
except RuntimeError:
return set()
def _coin_is_first_singleton(self, coin: Coin) -> bool:
parent = self.get_parent_for_coin(coin)
if parent is None:
return False
assert self.did_info.origin_coin
return parent.parent_name == self.did_info.origin_coin.name()
# This will be used in the recovery case where we don't have the parent info already
# But it is also called whenever a Singleton coin from this wallet is spent
# We can improve this interface by passing in the CoinSpend, as well
# We need to change DID Wallet coin_added to expect p2 spends as well as recovery spends,
# or only call it in the recovery spend case
async def coin_added(self, coin: Coin, _: uint32, peer: WSChiaConnection, parent_coin_data: Optional[DIDCoinData]):
"""Notification from wallet state manager that wallet has been received."""
parent = self.get_parent_for_coin(coin)
if parent_coin_data is not None:
assert isinstance(parent_coin_data, DIDCoinData)
did_data: DIDCoinData = parent_coin_data
else:
parent_state: CoinState = (
await self.wallet_state_manager.wallet_node.get_coin_state(
coin_names=[coin.parent_coin_info], peer=peer
)
)[0]
coin_spend = await fetch_coin_spend_for_coin_state(parent_state, peer)
uncurried = uncurry_puzzle(coin_spend.puzzle_reveal.to_program())
did_curried_args = match_did_puzzle(uncurried.mod, uncurried.args)
assert did_curried_args is not None
p2_puzzle, recovery_list_hash, num_verification, singleton_struct, metadata = did_curried_args
did_data = DIDCoinData(
p2_puzzle=p2_puzzle,
recovery_list_hash=recovery_list_hash.atom,
num_verification=uint16(num_verification.as_int()),
singleton_struct=singleton_struct,
metadata=metadata,
inner_puzzle=get_inner_puzzle_from_singleton(coin_spend.puzzle_reveal),
coin_state=parent_state,
)
if parent is None:
# this is the first time we received it, check it's a DID coin
parent_innerpuz = did_data.inner_puzzle
if parent_innerpuz:
parent_info = LineageProof(
parent_name=did_data.coin_state.coin.parent_coin_info,
inner_puzzle_hash=parent_innerpuz.get_tree_hash(),
amount=uint64(did_data.coin_state.coin.amount),
)
await self.add_parent(coin.parent_coin_info, parent_info)
else:
self.log.warning("Parent coin is not a DID, skipping: %s -> %s", coin.name(), coin)
return
self.log.info(f"DID wallet has been notified that coin was added: {coin.name()}:{coin}")
inner_puzzle = await self.inner_puzzle_for_did_puzzle(coin.puzzle_hash)
# Check inner puzzle consistency
assert self.did_info.origin_coin is not None
# TODO: if not the first singleton, and solution mode == recovery
if not self._coin_is_first_singleton(coin):
full_puzzle = create_singleton_puzzle(inner_puzzle, self.did_info.origin_coin.name())
assert full_puzzle.get_tree_hash() == coin.puzzle_hash
if self.did_info.temp_coin is not None:
self.wallet_state_manager.state_changed("did_coin_added", self.wallet_info.id)
new_info = DIDInfo(
origin_coin=self.did_info.origin_coin,
backup_ids=self.did_info.backup_ids,
num_of_backup_ids_needed=self.did_info.num_of_backup_ids_needed,
parent_info=self.did_info.parent_info,
current_inner=inner_puzzle,
temp_coin=None,
temp_puzhash=None,
temp_pubkey=None,
sent_recovery_transaction=False,
metadata=json.dumps(did_wallet_puzzles.did_program_to_metadata(did_data.metadata)),
)
await self.save_info(new_info)
future_parent = LineageProof(
parent_name=coin.parent_coin_info,
inner_puzzle_hash=inner_puzzle.get_tree_hash(),
amount=uint64(coin.amount),
)
await self.add_parent(coin.name(), future_parent)
await self.wallet_state_manager.add_interested_coin_ids([coin.name()])
def create_backup(self) -> str:
"""
Create a serialized backup data for DIDInfo
:return: Serialized backup data
"""
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
output_str = f"{self.did_info.origin_coin.parent_coin_info.hex()}:"
output_str += f"{self.did_info.origin_coin.puzzle_hash.hex()}:"
output_str += f"{self.did_info.origin_coin.amount}:"
if len(self.did_info.backup_ids) > 0:
for did in self.did_info.backup_ids:
output_str = output_str + did.hex() + ","
output_str = output_str[:-1]
output_str += f":{bytes(self.did_info.current_inner).hex()}:{self.did_info.num_of_backup_ids_needed}"
output_str += f":{self.did_info.metadata}"
return output_str
async def load_parent(self, did_info: DIDInfo):
"""
Load the parent info when importing a DID
:param did_info: DID info
:return:
"""
# full_puz = did_wallet_puzzles.create_fullpuz(innerpuz, origin.name())
# All additions in this block here:
new_pubkey = (await self.wallet_state_manager.get_unused_derivation_record(self.wallet_info.id)).pubkey
new_puzhash = puzzle_for_pk(new_pubkey).get_tree_hash()
parent_info = None
assert did_info.origin_coin is not None
assert did_info.current_inner is not None
new_did_inner_puzhash = did_wallet_puzzles.get_inner_puzhash_by_p2(
p2_puzhash=new_puzhash,
recovery_list=did_info.backup_ids,
num_of_backup_ids_needed=did_info.num_of_backup_ids_needed,
launcher_id=did_info.origin_coin.name(),
metadata=did_wallet_puzzles.metadata_to_program(json.loads(self.did_info.metadata)),
)
wallet_node = self.wallet_state_manager.wallet_node
parent_coin: Coin = did_info.origin_coin
while True:
peer = wallet_node.get_full_node_peer()
children = await wallet_node.fetch_children(parent_coin.name(), peer)
if len(children) == 0:
break
children_state: CoinState = children[0]
child_coin = children_state.coin
future_parent = LineageProof(
parent_name=child_coin.parent_coin_info,
inner_puzzle_hash=did_info.current_inner.get_tree_hash(),
amount=uint64(child_coin.amount),
)
await self.add_parent(child_coin.name(), future_parent)
if children_state.spent_height != children_state.created_height:
did_info = DIDInfo(
origin_coin=did_info.origin_coin,
backup_ids=did_info.backup_ids,
num_of_backup_ids_needed=did_info.num_of_backup_ids_needed,
parent_info=self.did_info.parent_info,
current_inner=did_info.current_inner,
temp_coin=child_coin,
temp_puzhash=new_did_inner_puzhash,
temp_pubkey=bytes(new_pubkey),
sent_recovery_transaction=did_info.sent_recovery_transaction,
metadata=did_info.metadata,
)
await self.save_info(did_info)
assert children_state.created_height
parent_spend = await fetch_coin_spend(uint32(children_state.created_height), parent_coin, peer)
assert parent_spend is not None
parent_innerpuz = get_inner_puzzle_from_singleton(parent_spend.puzzle_reveal)
assert parent_innerpuz is not None
parent_info = LineageProof(
parent_name=parent_coin.parent_coin_info,
inner_puzzle_hash=parent_innerpuz.get_tree_hash(),
amount=uint64(parent_coin.amount),
)
await self.add_parent(child_coin.parent_coin_info, parent_info)
parent_coin = child_coin
assert parent_info is not None
def puzzle_for_pk(self, pubkey: G1Element) -> Program:
if self.did_info.origin_coin is not None:
innerpuz = did_wallet_puzzles.create_innerpuz(
p2_puzzle_or_hash=puzzle_for_pk(pubkey),
recovery_list=self.did_info.backup_ids,
num_of_backup_ids_needed=self.did_info.num_of_backup_ids_needed,
launcher_id=self.did_info.origin_coin.name(),
metadata=did_wallet_puzzles.metadata_to_program(json.loads(self.did_info.metadata)),
)
return create_singleton_puzzle(innerpuz, self.did_info.origin_coin.name())
else:
innerpuz = Program.to((8, 0))
return create_singleton_puzzle(innerpuz, bytes32([0] * 32))
def puzzle_hash_for_pk(self, pubkey: G1Element) -> bytes32:
if self.did_info.origin_coin is None:
# TODO: this seem dumb. Why bother with this case? Is it ever used?
# inner puzzle: (8 . 0)
innerpuz_hash = shatree_pair(shatree_int(8), NIL_TREEHASH)
return create_singleton_puzzle_hash(innerpuz_hash, bytes32([0] * 32))
origin_coin_name = self.did_info.origin_coin.name()
innerpuz_hash = did_wallet_puzzles.get_inner_puzhash_by_p2(
p2_puzhash=puzzle_hash_for_pk(pubkey),
recovery_list=self.did_info.backup_ids,
num_of_backup_ids_needed=self.did_info.num_of_backup_ids_needed,
launcher_id=origin_coin_name,
metadata=did_wallet_puzzles.metadata_to_program(json.loads(self.did_info.metadata)),
)
return create_singleton_puzzle_hash(innerpuz_hash, origin_coin_name)
async def get_new_puzzle(self) -> Program:
return self.puzzle_for_pk(
(await self.wallet_state_manager.get_unused_derivation_record(self.wallet_info.id)).pubkey
)
def get_my_DID(self) -> str:
assert self.did_info.origin_coin is not None
core = self.did_info.origin_coin.name()
assert core is not None
return core.hex()
async def set_name(self, new_name: str):
import dataclasses
new_info = dataclasses.replace(self.wallet_info, name=new_name)
self.wallet_info = new_info
await self.wallet_state_manager.user_store.update_wallet(self.wallet_info)
def get_name(self):
return self.wallet_info.name
async def create_update_spend(
self, tx_config: TXConfig, fee: uint64 = uint64(0), extra_conditions: Tuple[Condition, ...] = tuple()
) -> List[TransactionRecord]:
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
coin = await self.get_coin()
new_inner_puzzle = await self.get_new_did_innerpuz()
uncurried = did_wallet_puzzles.uncurry_innerpuz(new_inner_puzzle)
assert uncurried is not None
p2_puzzle = uncurried[0]
# innerpuz solution is (mode, p2_solution)
p2_solution = self.standard_wallet.make_solution(
primaries=[
Payment(
puzzle_hash=new_inner_puzzle.get_tree_hash(),
amount=uint64(coin.amount),
memos=[p2_puzzle.get_tree_hash()],
)
],
conditions=(*extra_conditions, CreateCoinAnnouncement(coin.name())),
)
innersol: Program = Program.to([1, p2_solution])
# full solution is (corehash parent_info my_amount innerpuz_reveal solution)
innerpuz: Program = self.did_info.current_inner
full_puzzle: Program = create_singleton_puzzle(
innerpuz,
self.did_info.origin_coin.name(),
)
parent_info = self.get_parent_for_coin(coin)
assert parent_info is not None
fullsol = Program.to(
[
[
parent_info.parent_name,
parent_info.inner_puzzle_hash,
parent_info.amount,
],
coin.amount,
innersol,
]
)
# Create an additional spend to confirm the change on-chain
new_full_puzzle: Program = create_singleton_puzzle(
new_inner_puzzle,
self.did_info.origin_coin.name(),
)
new_full_sol = Program.to(
[
[
coin.parent_coin_info,
innerpuz.get_tree_hash(),
coin.amount,
],
coin.amount,
innersol,
]
)
new_coin = Coin(coin.name(), new_full_puzzle.get_tree_hash(), coin.amount)
list_of_coinspends = [
make_spend(coin, full_puzzle, fullsol),
make_spend(new_coin, new_full_puzzle, new_full_sol),
]
spend_bundle = SpendBundle(list_of_coinspends, G2Element())
if fee > 0:
coin_name = coin.name()
chia_tx = await self.standard_wallet.create_tandem_xch_tx(
fee,
tx_config,
extra_conditions=(AssertCoinAnnouncement(asserted_id=coin_name, asserted_msg=coin_name),),
)
else:
chia_tx = None
if chia_tx is not None and chia_tx.spend_bundle is not None:
spend_bundle = SpendBundle.aggregate([spend_bundle, chia_tx.spend_bundle])
chia_tx = dataclasses.replace(chia_tx, spend_bundle=None)
did_record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=await self.standard_wallet.get_puzzle_hash(False),
amount=uint64(coin.amount),
fee_amount=uint64(0),
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
wallet_id=self.wallet_info.id,
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=bytes32.secret(),
memos=list(compute_memos(spend_bundle).items()),
valid_times=parse_timelock_info(extra_conditions),
)
txs = [did_record]
if chia_tx is not None:
txs.append(chia_tx)
return txs
async def transfer_did(
self,
new_puzhash: bytes32,
fee: uint64,
with_recovery: bool,
tx_config: TXConfig,
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> List[TransactionRecord]:
"""
Transfer the current DID to another owner
:param new_puzhash: New owner's p2_puzzle
:param fee: Transaction fee
:param with_recovery: A boolean indicates if the recovery info will be sent through the blockchain
:return: Spend bundle
"""
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
coin = await self.get_coin()
backup_ids = []
backup_required = uint64(0)
if with_recovery:
backup_ids = self.did_info.backup_ids
backup_required = self.did_info.num_of_backup_ids_needed
new_did_puzhash = did_wallet_puzzles.get_inner_puzhash_by_p2(
p2_puzhash=new_puzhash,
recovery_list=backup_ids,
num_of_backup_ids_needed=backup_required,
launcher_id=self.did_info.origin_coin.name(),
metadata=did_wallet_puzzles.metadata_to_program(json.loads(self.did_info.metadata)),
)
p2_solution = self.standard_wallet.make_solution(
primaries=[Payment(new_did_puzhash, uint64(coin.amount), [new_puzhash])],
conditions=(*extra_conditions, CreateCoinAnnouncement(coin.name())),
)
# Need to include backup list reveal here, even we are don't recover
# innerpuz solution is
# (mode, p2_solution)
innersol: Program = Program.to([2, p2_solution])
if with_recovery:
innersol = Program.to([2, p2_solution, [], [], [], self.did_info.backup_ids])
# full solution is (corehash parent_info my_amount innerpuz_reveal solution)
full_puzzle: Program = create_singleton_puzzle(
self.did_info.current_inner,
self.did_info.origin_coin.name(),
)
parent_info = self.get_parent_for_coin(coin)
assert parent_info is not None
fullsol = Program.to(
[
[
parent_info.parent_name,
parent_info.inner_puzzle_hash,
parent_info.amount,
],
coin.amount,
innersol,
]
)
list_of_coinspends = [make_spend(coin, full_puzzle, fullsol)]
spend_bundle = SpendBundle(list_of_coinspends, G2Element())
if fee > 0:
coin_name = coin.name()
chia_tx = await self.standard_wallet.create_tandem_xch_tx(
fee,
tx_config,
extra_conditions=(AssertCoinAnnouncement(asserted_id=coin_name, asserted_msg=coin_name),),
)
else:
chia_tx = None
if chia_tx is not None and chia_tx.spend_bundle is not None:
spend_bundle = SpendBundle.aggregate([spend_bundle, chia_tx.spend_bundle])
chia_tx = dataclasses.replace(chia_tx, spend_bundle=None)
did_record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=await self.standard_wallet.get_puzzle_hash(False),
amount=uint64(coin.amount),
fee_amount=fee,
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
wallet_id=self.wallet_info.id,
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=spend_bundle.name(),
memos=list(compute_memos(spend_bundle).items()),
valid_times=parse_timelock_info(extra_conditions),
)
txs = [did_record]
if chia_tx is not None:
txs.append(chia_tx)
return txs
# The message spend can tests\wallet\rpc\test_wallet_rpc.py send messages and also change your innerpuz
async def create_message_spend(
self,
tx_config: TXConfig,
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> TransactionRecord:
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
coin = await self.get_coin()
innerpuz: Program = self.did_info.current_inner
# Quote message puzzle & solution
if tx_config.reuse_puzhash:
new_innerpuzzle_hash = innerpuz.get_tree_hash()
uncurried = did_wallet_puzzles.uncurry_innerpuz(innerpuz)
assert uncurried is not None
p2_ph = uncurried[0].get_tree_hash()
else:
p2_ph = await self.standard_wallet.get_puzzle_hash(new=True)
new_innerpuzzle_hash = did_wallet_puzzles.get_inner_puzhash_by_p2(
p2_puzhash=p2_ph,
recovery_list=self.did_info.backup_ids,
num_of_backup_ids_needed=self.did_info.num_of_backup_ids_needed,
launcher_id=self.did_info.origin_coin.name(),
metadata=did_wallet_puzzles.metadata_to_program(json.loads(self.did_info.metadata)),
)
p2_solution = self.standard_wallet.make_solution(
primaries=[Payment(puzzle_hash=new_innerpuzzle_hash, amount=uint64(coin.amount), memos=[p2_ph])],
conditions=extra_conditions,
)
# innerpuz solution is (mode p2_solution)
innersol: Program = Program.to([1, p2_solution])
# full solution is (corehash parent_info my_amount innerpuz_reveal solution)
full_puzzle: Program = create_singleton_puzzle(
innerpuz,
self.did_info.origin_coin.name(),
)
parent_info = self.get_parent_for_coin(coin)
assert parent_info is not None
fullsol = Program.to(
[
[
parent_info.parent_name,
parent_info.inner_puzzle_hash,
parent_info.amount,
],
coin.amount,
innersol,
]
)
list_of_coinspends = [make_spend(coin, full_puzzle, fullsol)]
unsigned_spend_bundle = SpendBundle(list_of_coinspends, G2Element())
return TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=p2_ph,
amount=uint64(coin.amount),
fee_amount=uint64(0),
confirmed=False,
sent=uint32(0),
spend_bundle=unsigned_spend_bundle,
additions=unsigned_spend_bundle.additions(),
removals=[coin],
wallet_id=self.id(),
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=unsigned_spend_bundle.name(),
memos=list(compute_memos(unsigned_spend_bundle).items()),
valid_times=parse_timelock_info(extra_conditions),
)
# This is used to cash out, or update the id_list
async def create_exit_spend(self, puzhash: bytes32, tx_config: TXConfig) -> List[TransactionRecord]:
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
coin = await self.get_coin()
message_puz = Program.to((1, [[51, puzhash, coin.amount - 1, [puzhash]], [51, 0x00, -113]]))
# innerpuz solution is (mode p2_solution)
innersol: Program = Program.to([1, [[], message_puz, []]])
# full solution is (corehash parent_info my_amount innerpuz_reveal solution)
innerpuz: Program = self.did_info.current_inner
full_puzzle: Program = create_singleton_puzzle(
innerpuz,
self.did_info.origin_coin.name(),
)
parent_info = self.get_parent_for_coin(coin)
assert parent_info is not None
fullsol = Program.to(
[
[
parent_info.parent_name,
parent_info.inner_puzzle_hash,
parent_info.amount,
],
coin.amount,
innersol,
]
)
list_of_coinspends = [make_spend(coin, full_puzzle, fullsol)]
spend_bundle = SpendBundle(list_of_coinspends, G2Element())
did_record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=await self.standard_wallet.get_puzzle_hash(False),
amount=uint64(coin.amount),
fee_amount=uint64(0),
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
wallet_id=self.wallet_info.id,
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=bytes32.secret(),
memos=list(compute_memos(spend_bundle).items()),
valid_times=ConditionValidTimes(),
)
return [did_record]
# Pushes a SpendBundle to create a message coin on the blockchain
# Returns a SpendBundle for the recoverer to spend the message coin
async def create_attestment(
self,
recovering_coin_name: bytes32,
newpuz: bytes32,
pubkey: G1Element,
tx_config: TXConfig,
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> Tuple[TransactionRecord, SpendBundle, str]:
"""
Create an attestment
TODO:
1. We should use/respect `tx_config` (reuse_puzhash and co)
2. We should take a fee as it's a requirement for every transaction function to do so
:param recovering_coin_name: Coin ID of the DID
:param newpuz: New puzzle hash
:param pubkey: New wallet pubkey
:return: (SpendBundle, attest string)
"""
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
coin = await self.get_coin()
message = did_wallet_puzzles.create_recovery_message_puzzle(recovering_coin_name, newpuz, pubkey)
innermessage = message.get_tree_hash()
innerpuz: Program = self.did_info.current_inner
uncurried = did_wallet_puzzles.uncurry_innerpuz(innerpuz)
assert uncurried is not None
p2_puzzle = uncurried[0]
# innerpuz solution is (mode, p2_solution)
p2_solution = self.standard_wallet.make_solution(
primaries=[
Payment(innerpuz.get_tree_hash(), uint64(coin.amount), [p2_puzzle.get_tree_hash()]),
Payment(innermessage, uint64(0)),
],
conditions=extra_conditions,
)
innersol = Program.to([1, p2_solution])
# full solution is (corehash parent_info my_amount innerpuz_reveal solution)
full_puzzle: Program = create_singleton_puzzle(
innerpuz,
self.did_info.origin_coin.name(),
)
parent_info = self.get_parent_for_coin(coin)
assert parent_info is not None
fullsol = Program.to(
[
[
parent_info.parent_name,
parent_info.inner_puzzle_hash,
parent_info.amount,
],
coin.amount,
innersol,
]
)
list_of_coinspends = [make_spend(coin, full_puzzle, fullsol)]
message_spend = did_wallet_puzzles.create_spend_for_message(coin.name(), recovering_coin_name, newpuz, pubkey)
message_spend_bundle = SpendBundle([message_spend], AugSchemeMPL.aggregate([]))
spend_bundle = SpendBundle(list_of_coinspends, G2Element())
did_record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=await self.standard_wallet.get_puzzle_hash(False),
amount=uint64(coin.amount),
fee_amount=uint64(0),
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
wallet_id=self.wallet_info.id,
sent_to=[],
trade_id=None,
type=uint32(TransactionType.INCOMING_TX.value),
name=bytes32.secret(),
memos=list(compute_memos(spend_bundle).items()),
valid_times=parse_timelock_info(extra_conditions),
)
attest_str: str = f"{self.get_my_DID()}:{bytes(message_spend_bundle).hex()}:{coin.parent_coin_info.hex()}:"
attest_str += f"{self.did_info.current_inner.get_tree_hash().hex()}:{coin.amount}"
return did_record, message_spend_bundle, attest_str
async def get_info_for_recovery(self) -> Optional[Tuple[bytes32, bytes32, uint64]]:
assert self.did_info.current_inner is not None
assert self.did_info.origin_coin is not None
try:
coin = await self.get_coin()
except RuntimeError:
return None
parent = coin.parent_coin_info
innerpuzhash = self.did_info.current_inner.get_tree_hash()
amount = uint64(coin.amount)
return (parent, innerpuzhash, amount)
async def load_attest_files_for_recovery_spend(self, attest_data: List[str]) -> Tuple[List, SpendBundle]:
spend_bundle_list = []
info_dict = {}
for attest in attest_data:
info = attest.split(":")
info_dict[info[0]] = [
bytes.fromhex(info[2]),
bytes.fromhex(info[3]),
uint64(info[4]),
]
new_sb = SpendBundle.from_bytes(bytes.fromhex(info[1]))
spend_bundle_list.append(new_sb)
# info_dict {0xidentity: "(0xparent_info 0xinnerpuz amount)"}