-
Notifications
You must be signed in to change notification settings - Fork 2k
/
dao_wallet.py
2125 lines (1953 loc) · 95.6 KB
/
dao_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 copy
import dataclasses
import json
import logging
import re
import time
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Set, Tuple, Union, cast
from chia_rs import AugSchemeMPL, G1Element, G2Element
from clvm.casts import int_from_bytes
from chia.full_node.full_node_api import FullNodeAPI
from chia.protocols.wallet_protocol import CoinState, RequestBlockHeader, RespondBlockHeader
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.condition_opcodes import ConditionOpcode
from chia.types.spend_bundle import SpendBundle
from chia.util.ints import uint32, uint64, uint128
from chia.wallet import singleton
from chia.wallet.cat_wallet.cat_utils import CAT_MOD, SpendableCAT, construct_cat_puzzle
from chia.wallet.cat_wallet.cat_utils import get_innerpuzzle_from_puzzle as get_innerpuzzle_from_cat_puzzle
from chia.wallet.cat_wallet.cat_utils import unsigned_spend_bundle_for_spendable_cats
from chia.wallet.cat_wallet.cat_wallet import CATWallet
from chia.wallet.cat_wallet.dao_cat_wallet import DAOCATWallet
from chia.wallet.coin_selection import select_coins
from chia.wallet.conditions import AssertCoinAnnouncement, Condition, parse_timelock_info
from chia.wallet.dao_wallet.dao_info import DAOInfo, DAORules, ProposalInfo, ProposalType
from chia.wallet.dao_wallet.dao_utils import (
DAO_FINISHED_STATE,
DAO_PROPOSAL_MOD,
DAO_TREASURY_MOD,
SINGLETON_LAUNCHER,
create_cat_launcher_for_singleton_id,
curry_cat_eve,
curry_singleton,
generate_cat_tail,
get_active_votes_from_lockup_puzzle,
get_asset_id_from_puzzle,
get_dao_rules_from_update_proposal,
get_finished_state_inner_puzzle,
get_finished_state_puzzle,
get_innerpuz_from_lockup_puzzle,
get_new_puzzle_from_proposal_solution,
get_new_puzzle_from_treasury_solution,
get_p2_singleton_puzhash,
get_p2_singleton_puzzle,
get_proposal_args,
get_proposal_puzzle,
get_proposal_timer_puzzle,
get_proposed_puzzle_reveal_from_solution,
get_treasury_puzzle,
get_treasury_rules_from_puzzle,
match_funding_puzzle,
uncurry_proposal,
uncurry_treasury,
)
from chia.wallet.lineage_proof import LineageProof
from chia.wallet.singleton import (
get_inner_puzzle_from_singleton,
get_most_recent_singleton_coin_from_coin_spend,
get_singleton_id_from_puzzle,
get_singleton_struct_for_id,
)
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.uncurried_puzzle import uncurry_puzzle
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
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
class DAOWallet:
"""
This is a wallet in the sense that it conforms to the interface needed by WalletStateManager.
It is not a user-facing wallet. A user cannot spend or receive XCH though a wallet of this type.
Wallets of type CAT and DAO_CAT are the user-facing wallets which hold the voting tokens a user
owns. The DAO Wallet is used for state-tracking of the Treasury Singleton and its associated
Proposals.
State change Spends (spends this user creates, either from DAOWallet or DAOCATWallet:
* Create a proposal
* Add more votes to a proposal
* Lock / Unlock voting tokens
* Collect finished state of a Proposal - spend to read the oracle result and Get our CAT coins back
* Anyone can send money to the Treasury, whether in possession of a voting CAT or not
Incoming spends we listen for:
* Update Treasury state if treasury is spent
* Hear about a finished proposal
* Hear about a new proposal -- check interest threshold (how many votes)
* Get Updated Proposal Data
"""
if TYPE_CHECKING:
from chia.wallet.wallet_protocol import WalletProtocol
_protocol_check: ClassVar[WalletProtocol[DAOInfo]] = cast("DAOWallet", None)
wallet_state_manager: Any
log: logging.Logger
wallet_info: WalletInfo
dao_info: DAOInfo
dao_rules: DAORules
standard_wallet: Wallet
wallet_id: uint32
@staticmethod
async def create_new_dao_and_wallet(
wallet_state_manager: Any,
wallet: Wallet,
amount_of_cats: uint64,
dao_rules: DAORules,
tx_config: TXConfig,
filter_amount: uint64 = uint64(1),
name: Optional[str] = None,
fee: uint64 = uint64(0),
fee_for_cat: uint64 = uint64(0),
) -> Tuple[DAOWallet, List[TransactionRecord]]:
"""
Create a brand new DAO wallet
This must be called under the wallet state manager lock
:param wallet_state_manager: Wallet state manager
:param wallet: Standard wallet
:param amount_of_cats: Initial amount of voting CATs
:param dao_rules: The rules which govern the DAO
:param filter_amount: Min votes to see proposal (user defined)
:param name: Wallet name
:param fee: transaction fee
:param fee_for_cat: transaction fee for creating the CATs
:return: DAO wallet
"""
self = DAOWallet()
self.wallet_state_manager = wallet_state_manager
if name is None:
name = self.generate_wallet_name()
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_of_cats > bal:
raise ValueError(f"Your balance of {bal} mojos is not enough to create {amount_of_cats} CATs")
self.dao_info = DAOInfo(
treasury_id=bytes32([0] * 32),
cat_wallet_id=uint32(0),
dao_cat_wallet_id=uint32(0),
proposals_list=[],
parent_info=[],
current_treasury_coin=None,
current_treasury_innerpuz=None,
singleton_block_height=uint32(0),
filter_below_vote_amount=filter_amount,
assets=[],
current_height=uint64(0),
)
self.dao_rules = dao_rules
info_as_string = json.dumps(self.dao_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name, WalletType.DAO.value, info_as_string
)
self.wallet_id = self.wallet_info.id
std_wallet_id = self.standard_wallet.wallet_id
try:
txs = await self.generate_new_dao(
amount_of_cats,
tx_config,
fee=fee,
fee_for_cat=fee_for_cat,
)
except Exception as e_info: # pragma: no cover
await wallet_state_manager.user_store.delete_wallet(self.id())
self.log.exception(f"Failed to create dao wallet: {e_info}")
raise
await self.wallet_state_manager.add_new_wallet(self)
# Now the dao wallet is created we can create the dao_cat wallet
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
cat_tail = cat_wallet.cat_info.limitations_program_hash
new_dao_cat_wallet = await DAOCATWallet.get_or_create_wallet_for_cat(
self.wallet_state_manager, self.standard_wallet, cat_tail.hex()
)
dao_cat_wallet_id = new_dao_cat_wallet.wallet_info.id
dao_info = dataclasses.replace(
self.dao_info, cat_wallet_id=cat_wallet.id(), dao_cat_wallet_id=dao_cat_wallet_id
)
await self.save_info(dao_info)
return self, txs
@staticmethod
async def create_new_dao_wallet_for_existing_dao(
wallet_state_manager: Any,
main_wallet: Wallet,
treasury_id: bytes32,
filter_amount: uint64 = uint64(1),
name: Optional[str] = None,
) -> DAOWallet:
"""
Create a DAO wallet for existing DAO
:param wallet_state_manager: Wallet state manager
:param main_wallet: Standard wallet
:param treasury_id: The singleton ID of the DAO treasury coin
:param filter_amount: Min votes to see proposal (user defined)
:param name: Wallet name
:return: DAO wallet
"""
self = DAOWallet()
self.wallet_state_manager = wallet_state_manager
if name is None:
name = self.generate_wallet_name()
self.standard_wallet = main_wallet
self.log = logging.getLogger(name if name else __name__)
self.log.info("Creating DAO wallet for existent DAO ...")
self.dao_info = DAOInfo(
treasury_id=treasury_id,
cat_wallet_id=uint32(0),
dao_cat_wallet_id=uint32(0),
proposals_list=[],
parent_info=[],
current_treasury_coin=None,
current_treasury_innerpuz=None,
singleton_block_height=uint32(0),
filter_below_vote_amount=filter_amount,
assets=[],
current_height=uint64(0),
)
info_as_string = json.dumps(self.dao_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name, WalletType.DAO.value, info_as_string
)
await self.wallet_state_manager.add_new_wallet(self)
await self.resync_treasury_state()
await self.save_info(self.dao_info)
self.wallet_id = self.wallet_info.id
# Now the dao wallet is created we can create the dao_cat wallet
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
cat_tail = cat_wallet.cat_info.limitations_program_hash
new_dao_cat_wallet = await DAOCATWallet.get_or_create_wallet_for_cat(
self.wallet_state_manager, self.standard_wallet, cat_tail.hex()
)
dao_cat_wallet_id = new_dao_cat_wallet.wallet_info.id
dao_info = dataclasses.replace(
self.dao_info, cat_wallet_id=cat_wallet.id(), dao_cat_wallet_id=dao_cat_wallet_id
)
await self.save_info(dao_info)
# add treasury id to interested puzzle hashes. This is hinted in funding coins so we can track them
funding_inner_hash = get_p2_singleton_puzhash(self.dao_info.treasury_id)
await self.wallet_state_manager.add_interested_puzzle_hashes(
[self.dao_info.treasury_id, funding_inner_hash], [self.id(), self.id()]
)
return self
@staticmethod
async def create(
wallet_state_manager: Any,
wallet: Wallet,
wallet_info: WalletInfo,
name: Optional[str] = None,
) -> DAOWallet:
"""
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 = DAOWallet()
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.dao_info = DAOInfo.from_json_dict(json.loads(wallet_info.data))
self.dao_rules = get_treasury_rules_from_puzzle(self.dao_info.current_treasury_innerpuz)
return self
@classmethod
def type(cls) -> WalletType:
return WalletType.DAO
def id(self) -> uint32:
return self.wallet_info.id
async def set_name(self, new_name: str) -> None:
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) -> str:
return self.wallet_info.name
async def match_hinted_coin(self, coin: Coin, hint: bytes32) -> bool:
raise NotImplementedError("Method not implemented for DAO Wallet") # pragma: no cover
def puzzle_hash_for_pk(self, pubkey: G1Element) -> bytes32:
raise NotImplementedError("puzzle_hash_for_pk is not available in DAO wallets") # pragma: no cover
async def get_new_p2_inner_hash(self) -> bytes32:
puzzle = await self.get_new_p2_inner_puzzle()
return puzzle.get_tree_hash()
async def get_new_p2_inner_puzzle(self) -> Program:
return await self.standard_wallet.get_new_puzzle()
def get_parent_for_coin(self, coin: Coin) -> Optional[LineageProof]:
parent_info = None
for name, ccparent in self.dao_info.parent_info:
if name == coin.parent_coin_info:
parent_info = ccparent
return parent_info
async def get_max_send_amount(self, records: Optional[Set[WalletCoinRecord]] = None) -> uint128:
return uint128(0) # pragma: no cover
async def get_spendable_balance(self, unspent_records: Optional[Set[WalletCoinRecord]] = None) -> uint128:
# No spendable or receivable value
return uint128(1)
async def get_confirmed_balance(self, record_list: Optional[Set[WalletCoinRecord]] = None) -> uint128:
# No spendable or receivable value
return uint128(1)
async def select_coins(
self,
amount: uint64,
coin_selection_config: CoinSelectionConfig,
) -> Set[Coin]:
"""
Returns a set of coins that can be used for generating a new transaction.
Note: Must be called under wallet state manager lock
There is no need for max/min coin amount or excluded amount because the dao treasury should
always be a single coin with amount 1
"""
spendable_amount: uint128 = await self.get_spendable_balance()
if amount > spendable_amount:
self.log.warning(f"Can't select {amount}, from spendable {spendable_amount} for wallet id {self.id()}")
return set()
spendable_coins: List[WalletCoinRecord] = list(
await self.wallet_state_manager.get_spendable_coins_for_wallet(self.wallet_info.id)
)
# Try to use coins from the store, if there isn't enough of "unused"
# coins use change coins that are not confirmed yet
unconfirmed_removals: Dict[bytes32, Coin] = await self.wallet_state_manager.unconfirmed_removals_for_wallet(
self.wallet_info.id
)
coins = await select_coins(
spendable_amount,
coin_selection_config,
spendable_coins,
unconfirmed_removals,
self.log,
uint128(amount),
)
assert sum(c.amount for c in coins) >= amount
return coins
async def get_pending_change_balance(self) -> uint64:
# No spendable or receivable value
return uint64(0)
async def get_unconfirmed_balance(self, record_list: Optional[Set[WalletCoinRecord]] = None) -> uint128:
# No spendable or receivable value
return uint128(1)
# if asset_id == None: then we get normal XCH
async def get_balance_by_asset_type(self, asset_id: Optional[bytes32] = None) -> uint128:
puzhash = get_p2_singleton_puzhash(self.dao_info.treasury_id, asset_id=asset_id)
records = await self.wallet_state_manager.coin_store.get_coin_records_by_puzzle_hash(puzhash)
return uint128(sum([cr.coin.amount for cr in records if not cr.spent]))
# if asset_id == None: then we get normal XCH
async def select_coins_for_asset_type(self, amount: uint64, asset_id: Optional[bytes32] = None) -> List[Coin]:
puzhash = get_p2_singleton_puzhash(self.dao_info.treasury_id, asset_id=asset_id)
records = await self.wallet_state_manager.coin_store.get_coin_records_by_puzzle_hash(puzhash)
# TODO: smarter coin selection algorithm
total = 0
coins = []
for record in records:
if not record.spent:
total += record.coin.amount
coins.append(record.coin)
if total >= amount:
break
if total < amount: # pragma: no cover
raise ValueError(f"Not enough of asset {asset_id}: {total} < {amount}")
return coins
async def coin_added(self, coin: Coin, height: uint32, peer: WSChiaConnection, coin_data: Optional[Any]) -> None:
"""
Notification from wallet state manager that a coin has been received.
This can be either a treasury coin update or funds added to the treasury
"""
self.log.info(f"DAOWallet.coin_added() called with the coin: {coin.name().hex()}:{coin}.")
wallet_node: Any = self.wallet_state_manager.wallet_node
peer = wallet_node.get_full_node_peer()
if peer is None: # pragma: no cover
raise ValueError("Could not find any peers to request puzzle and solution from")
try:
# Get the parent coin spend
cs = (await wallet_node.get_coin_state([coin.parent_coin_info], peer, height))[0]
parent_spend = await fetch_coin_spend(cs.spent_height, cs.coin, peer)
puzzle = Program.from_bytes(bytes(parent_spend.puzzle_reveal))
solution = Program.from_bytes(bytes(parent_spend.solution))
uncurried = uncurry_puzzle(puzzle)
matched_funding_puz = match_funding_puzzle(uncurried, solution, coin, [self.dao_info.treasury_id])
if matched_funding_puz:
# funding coin
xch_funds_puzhash = get_p2_singleton_puzhash(self.dao_info.treasury_id, asset_id=None)
if coin.puzzle_hash == xch_funds_puzhash:
asset_id = None
else:
asset_id = get_asset_id_from_puzzle(parent_spend.puzzle_reveal.to_program())
# to prevent fake p2_singletons being added
assert coin.puzzle_hash == get_p2_singleton_puzhash(self.dao_info.treasury_id, asset_id=asset_id)
if asset_id not in self.dao_info.assets:
new_asset_list = self.dao_info.assets.copy()
new_asset_list.append(asset_id)
dao_info = dataclasses.replace(self.dao_info, assets=new_asset_list)
await self.save_info(dao_info)
await self.wallet_state_manager.add_interested_puzzle_hashes([coin.puzzle_hash], [self.id()])
self.log.info(f"DAO funding coin added: {coin.name().hex()}:{coin}. Asset ID: {asset_id}")
except Exception as e: # pragma: no cover
self.log.exception(f"Error occurred during dao wallet coin addition: {e}")
return
def get_cat_tail_hash(self) -> bytes32:
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
return cat_wallet.cat_info.limitations_program_hash
async def adjust_filter_level(self, new_filter_level: uint64) -> None:
dao_info = dataclasses.replace(self.dao_info, filter_below_vote_amount=new_filter_level)
await self.save_info(dao_info)
async def clear_finished_proposals_from_memory(self) -> None:
dao_cat_wallet: DAOCATWallet = self.wallet_state_manager.wallets[self.dao_info.dao_cat_wallet_id]
new_list = [
prop_info
for prop_info in self.dao_info.proposals_list
if not prop_info.closed
or prop_info.closed is None
or any(prop_info.proposal_id in lci.active_votes for lci in dao_cat_wallet.dao_cat_info.locked_coins)
]
dao_info = dataclasses.replace(self.dao_info, proposals_list=new_list)
await self.save_info(dao_info)
return
async def resync_treasury_state(self) -> None:
"""
This is called during create_new_dao_wallet_for_existing_dao.
When we want to sync to an existing DAO, we provide the treasury coins singleton ID, and then trace all
the child coins until we reach the current DAO treasury coin. We use the puzzle reveal and solution to
get the current state of the DAO, and to work out what the tail of the DAO CAT token is.
This also captures all the proposals that have been created and their state.
"""
parent_coin_id: bytes32 = self.dao_info.treasury_id
wallet_node: Any = self.wallet_state_manager.wallet_node
peer: WSChiaConnection = wallet_node.get_full_node_peer()
if peer is None: # pragma: no cover
raise ValueError("Could not find any peers to request puzzle and solution from")
parent_coin = None
parent_parent_coin = None
while True:
children = await wallet_node.fetch_children(parent_coin_id, peer)
if len(children) == 0:
break
children_state_list: List[CoinState] = [child for child in children if child.coin.amount % 2 == 1]
# ensure children_state_list has only one odd amount coin (the treasury)
if (len(children_state_list) == 0) or (len(children_state_list) > 1): # pragma: no cover
raise RuntimeError("Could not retrieve child_state")
children_state = children_state_list[0]
assert children_state is not None
child_coin = children_state.coin
if parent_coin is not None:
parent_parent_coin = parent_coin
parent_coin = child_coin
parent_coin_id = child_coin.name()
if parent_parent_coin is None: # pragma: no cover
raise RuntimeError("could not get parent_parent_coin of %s", children)
# ensure the child coin is unspent to prevent untrusted nodes sending false coin states
assert children_state.spent_height is None
# get lineage proof of parent spend, and also current innerpuz
assert children_state.created_height
parent_spend = await fetch_coin_spend(children_state.created_height, parent_parent_coin, peer)
assert parent_spend is not None
parent_inner_puz = get_inner_puzzle_from_singleton(parent_spend.puzzle_reveal)
if parent_inner_puz is None: # pragma: no cover
raise ValueError("get_innerpuzzle_from_puzzle failed")
if parent_spend.puzzle_reveal.get_tree_hash() == child_coin.puzzle_hash:
current_inner_puz = parent_inner_puz
else: # pragma: no cover
# extract the treasury solution from the full singleton solution
inner_solution = parent_spend.solution.to_program().rest().rest().first()
# reconstruct the treasury puzzle
current_inner_puz = get_new_puzzle_from_treasury_solution(parent_inner_puz, inner_solution)
# set the treasury rules
self.dao_rules = get_treasury_rules_from_puzzle(current_inner_puz)
current_lineage_proof = LineageProof(
parent_parent_coin.parent_coin_info, parent_inner_puz.get_tree_hash(), parent_parent_coin.amount
)
await self.add_parent(parent_parent_coin.name(), current_lineage_proof)
# Hack to find the cat tail hash from the memo of the genesis spend
launcher_state = await wallet_node.get_coin_state([self.dao_info.treasury_id], peer)
genesis_coin_id = launcher_state[0].coin.parent_coin_info
genesis_state = await wallet_node.get_coin_state([genesis_coin_id], peer)
genesis_spend = await fetch_coin_spend(genesis_state[0].spent_height, genesis_state[0].coin, peer)
cat_tail_hash = None
conds = genesis_spend.solution.to_program().at("rfr").as_iter()
for cond in conds:
if (cond.first().as_atom() == ConditionOpcode.CREATE_COIN) and (
int_from_bytes(cond.at("rrf").as_atom()) == 1
):
cat_tail_hash = bytes32(cond.at("rrrff").as_atom())
cat_origin_id = bytes32(cond.at("rrrfrf").as_atom())
# Calculate the CAT tail from the memo data. If someone tries to use a fake tail hash in
# the memo field, it won't match with the DAO's actual treasury ID.
cat_tail = generate_cat_tail(cat_origin_id, self.dao_info.treasury_id)
break
assert cat_tail_hash
assert cat_tail.get_tree_hash() == cat_tail_hash
cat_wallet: Optional[CATWallet] = None
# Get or create a cat wallet
for wallet_id in self.wallet_state_manager.wallets:
wallet = self.wallet_state_manager.wallets[wallet_id]
if wallet.type() == WalletType.CAT: # pragma: no cover
assert isinstance(wallet, CATWallet)
if wallet.cat_info.limitations_program_hash == cat_tail_hash:
cat_wallet = wallet
break
else:
# Didn't find a cat wallet, so create one
cat_wallet = await CATWallet.get_or_create_wallet_for_cat(
self.wallet_state_manager, self.standard_wallet, cat_tail_hash.hex()
)
assert cat_wallet is not None
await cat_wallet.set_tail_program(bytes(cat_tail).hex())
cat_wallet_id = cat_wallet.wallet_info.id
dao_info = dataclasses.replace(
self.dao_info,
cat_wallet_id=uint32(cat_wallet_id),
dao_cat_wallet_id=uint32(0),
current_treasury_coin=child_coin,
current_treasury_innerpuz=current_inner_puz,
)
await self.save_info(dao_info)
future_parent = LineageProof(
child_coin.parent_coin_info,
dao_info.current_treasury_innerpuz.get_tree_hash(),
uint64(child_coin.amount),
)
await self.add_parent(child_coin.name(), future_parent)
assert self.dao_info.parent_info is not None
# get existing xch funds for treasury
xch_funds_puzhash = get_p2_singleton_puzhash(self.dao_info.treasury_id, asset_id=None)
await self.wallet_state_manager.add_interested_puzzle_hashes([xch_funds_puzhash], [self.id()])
await self.wallet_state_manager.add_interested_puzzle_hashes([self.dao_info.treasury_id], [self.id()])
await self.wallet_state_manager.add_interested_puzzle_hashes(
[self.dao_info.current_treasury_coin.puzzle_hash], [self.id()]
)
# Resync the wallet from when the treasury was created to get the existing funds
# TODO: Maybe split this out as an option for users since it may be slow?
if not wallet_node.is_trusted(peer):
# Untrusted nodes won't automatically send us the history of all the treasury and proposal coins,
# so we have to request them via sync_from_untrusted_close_to_peak
request = RequestBlockHeader(children_state.created_height)
response: Optional[RespondBlockHeader] = await peer.call_api(FullNodeAPI.request_block_header, request)
await wallet_node.sync_from_untrusted_close_to_peak(response.header_block, peer)
return
async def generate_new_dao(
self,
amount_of_cats_to_create: Optional[uint64],
tx_config: TXConfig,
cat_tail_hash: Optional[bytes32] = None,
fee: uint64 = uint64(0),
fee_for_cat: uint64 = uint64(0),
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> List[TransactionRecord]:
"""
Create a new DAO treasury using the dao_rules object. This does the first spend to create the launcher
and eve coins.
The eve spend has to be completed in a separate tx using 'submit_eve_spend' once the number of blocks required
by dao_rules.oracle_spend_delay has passed.
This must be called under the wallet state manager lock
"""
if amount_of_cats_to_create is not None and amount_of_cats_to_create < 0: # pragma: no cover
raise ValueError("amount_of_cats must be >= 0, or None")
if (
amount_of_cats_to_create is None or amount_of_cats_to_create == 0
) and cat_tail_hash is None: # pragma: no cover
raise ValueError("amount_of_cats must be > 0 or cat_tail_hash must be specified")
if (
amount_of_cats_to_create is not None and amount_of_cats_to_create > 0 and cat_tail_hash is not None
): # pragma: no cover
raise ValueError("cannot create voting cats and use existing cat_tail_hash")
if self.dao_rules.pass_percentage > 10000 or self.dao_rules.pass_percentage < 0: # pragma: no cover
raise ValueError("proposal pass percentage must be between 0 and 10000")
if amount_of_cats_to_create is not None and amount_of_cats_to_create > 0:
coins = await self.standard_wallet.select_coins(
uint64(amount_of_cats_to_create + fee + 1),
tx_config.coin_selection_config,
)
else: # pragma: no cover
coins = await self.standard_wallet.select_coins(uint64(fee + 1), tx_config.coin_selection_config)
if coins is None: # pragma: no cover
return None
# origin is normal coin which creates launcher coin
origin = coins.copy().pop()
genesis_launcher_puz = SINGLETON_LAUNCHER
# launcher coin contains singleton launcher, launcher coin ID == singleton_id == treasury_id
launcher_coin = Coin(origin.name(), genesis_launcher_puz.get_tree_hash(), uint64(1))
if cat_tail_hash is None:
assert amount_of_cats_to_create is not None
different_coins = await self.standard_wallet.select_coins(
uint64(amount_of_cats_to_create + fee_for_cat),
coin_selection_config=tx_config.coin_selection_config.override(
excluded_coin_ids=[*tx_config.coin_selection_config.excluded_coin_ids, origin.name()]
),
)
cat_origin = different_coins.copy().pop()
assert origin.name() != cat_origin.name()
cat_tail = generate_cat_tail(cat_origin.name(), launcher_coin.name())
cat_tail_hash = cat_tail.get_tree_hash()
assert cat_tail_hash is not None
dao_info: DAOInfo = DAOInfo(
launcher_coin.name(),
self.dao_info.cat_wallet_id,
self.dao_info.dao_cat_wallet_id,
self.dao_info.proposals_list,
self.dao_info.parent_info,
None,
None,
uint32(0),
self.dao_info.filter_below_vote_amount,
self.dao_info.assets,
self.dao_info.current_height,
)
await self.save_info(dao_info)
new_cat_wallet = None
# This will also mint the coins
if amount_of_cats_to_create is not None and different_coins is not None:
cat_tail_info = {
"identifier": "genesis_by_id_or_singleton",
"treasury_id": launcher_coin.name(),
"coins": different_coins,
}
new_cat_wallet, _ = await CATWallet.create_new_cat_wallet(
self.wallet_state_manager,
self.standard_wallet,
cat_tail_info,
amount_of_cats_to_create,
DEFAULT_TX_CONFIG,
fee=fee_for_cat,
)
assert new_cat_wallet is not None
else: # pragma: no cover
for wallet in self.wallet_state_manager.wallets:
if self.wallet_state_manager.wallets[wallet].type() == WalletType.CAT:
if self.wallet_state_manager.wallets[wallet].cat_info.limitations_program_hash == cat_tail_hash:
new_cat_wallet = self.wallet_state_manager.wallets[wallet]
assert new_cat_wallet is not None
cat_wallet_id = new_cat_wallet.wallet_info.id
assert cat_tail_hash == new_cat_wallet.cat_info.limitations_program_hash
await new_cat_wallet.set_tail_program(bytes(cat_tail).hex())
dao_info = DAOInfo(
self.dao_info.treasury_id,
cat_wallet_id,
self.dao_info.dao_cat_wallet_id,
self.dao_info.proposals_list,
self.dao_info.parent_info,
None,
None,
uint32(0),
self.dao_info.filter_below_vote_amount,
self.dao_info.assets,
self.dao_info.current_height,
)
await self.save_info(dao_info)
dao_treasury_puzzle = get_treasury_puzzle(self.dao_rules, launcher_coin.name(), cat_tail_hash)
full_treasury_puzzle = curry_singleton(launcher_coin.name(), dao_treasury_puzzle)
full_treasury_puzzle_hash = full_treasury_puzzle.get_tree_hash()
announcement_message = Program.to([full_treasury_puzzle_hash, 1, bytes(0x80)]).get_tree_hash()
tx_records: List[TransactionRecord] = await self.standard_wallet.generate_signed_transaction(
uint64(1),
genesis_launcher_puz.get_tree_hash(),
tx_config,
fee,
origin_id=origin.name(),
coins=set(coins),
memos=[new_cat_wallet.cat_info.limitations_program_hash, cat_origin.name()],
extra_conditions=(
AssertCoinAnnouncement(asserted_id=launcher_coin.name(), asserted_msg=announcement_message),
),
)
tx_record: TransactionRecord = tx_records[0]
genesis_launcher_solution = Program.to([full_treasury_puzzle_hash, 1, bytes(0x80)])
launcher_cs = make_spend(launcher_coin, genesis_launcher_puz, genesis_launcher_solution)
launcher_sb = SpendBundle([launcher_cs], AugSchemeMPL.aggregate([]))
launcher_proof = LineageProof(
bytes32(launcher_coin.parent_coin_info),
None,
uint64(launcher_coin.amount),
)
await self.add_parent(launcher_coin.name(), launcher_proof)
assert tx_record.spend_bundle is not None
eve_coin = Coin(launcher_coin.name(), full_treasury_puzzle_hash, uint64(1))
dao_info = DAOInfo(
launcher_coin.name(),
cat_wallet_id,
self.dao_info.dao_cat_wallet_id,
self.dao_info.proposals_list,
self.dao_info.parent_info,
eve_coin,
dao_treasury_puzzle,
self.dao_info.singleton_block_height,
self.dao_info.filter_below_vote_amount,
self.dao_info.assets,
self.dao_info.current_height,
)
await self.save_info(dao_info)
eve_spend = await self.generate_treasury_eve_spend(dao_treasury_puzzle, eve_coin)
full_spend = SpendBundle.aggregate([tx_record.spend_bundle, launcher_sb, eve_spend])
treasury_record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=dao_treasury_puzzle.get_tree_hash(),
amount=uint64(1),
fee_amount=fee,
confirmed=False,
sent=uint32(10),
spend_bundle=full_spend,
additions=full_spend.additions(),
removals=full_spend.removals(),
wallet_id=self.id(),
sent_to=[],
trade_id=None,
type=uint32(TransactionType.INCOMING_TX.value),
name=full_spend.name(),
memos=[],
valid_times=parse_timelock_info(extra_conditions),
)
regular_record = dataclasses.replace(tx_record, spend_bundle=None)
funding_inner_puzhash = get_p2_singleton_puzhash(self.dao_info.treasury_id)
await self.wallet_state_manager.add_interested_puzzle_hashes([funding_inner_puzhash], [self.id()])
await self.wallet_state_manager.add_interested_puzzle_hashes([launcher_coin.name()], [self.id()])
await self.wallet_state_manager.add_interested_coin_ids([launcher_coin.name()], [self.wallet_id])
await self.wallet_state_manager.add_interested_coin_ids([eve_coin.name()], [self.wallet_id])
return [treasury_record, regular_record]
async def generate_treasury_eve_spend(
self, inner_puz: Program, eve_coin: Coin, fee: uint64 = uint64(0)
) -> SpendBundle:
"""
Create the eve spend of the treasury
This can only be completed after a number of blocks > oracle_spend_delay have been farmed
"""
if self.dao_info.current_treasury_innerpuz is None: # pragma: no cover
raise ValueError("generate_treasury_eve_spend called with nil self.dao_info.current_treasury_innerpuz")
full_treasury_puzzle = curry_singleton(self.dao_info.treasury_id, inner_puz)
launcher_id, launcher_proof = self.dao_info.parent_info[0]
assert launcher_proof
assert inner_puz
inner_sol = Program.to([0, 0, 0, 0, get_singleton_struct_for_id(launcher_id)])
fullsol = Program.to(
[
launcher_proof.to_program(),
eve_coin.amount,
inner_sol,
]
)
eve_coin_spend = make_spend(eve_coin, full_treasury_puzzle, fullsol)
eve_spend_bundle = SpendBundle([eve_coin_spend], G2Element())
next_proof = LineageProof(
eve_coin.parent_coin_info,
inner_puz.get_tree_hash(),
uint64(eve_coin.amount),
)
next_coin = Coin(eve_coin.name(), eve_coin.puzzle_hash, eve_coin.amount)
await self.add_parent(eve_coin.name(), next_proof)
await self.wallet_state_manager.add_interested_coin_ids([next_coin.name()], [self.wallet_id])
dao_info = dataclasses.replace(self.dao_info, current_treasury_coin=next_coin)
await self.save_info(dao_info)
return eve_spend_bundle
async def generate_new_proposal(
self,
proposed_puzzle: Program,
tx_config: TXConfig,
vote_amount: Optional[uint64] = None,
fee: uint64 = uint64(0),
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> List[TransactionRecord]:
dao_rules = get_treasury_rules_from_puzzle(self.dao_info.current_treasury_innerpuz)
coins = await self.standard_wallet.select_coins(
uint64(fee + dao_rules.proposal_minimum_amount),
tx_config.coin_selection_config,
)
if coins is None: # pragma: no cover
return None
# origin is normal coin which creates launcher coin
origin = coins.copy().pop()
genesis_launcher_puz = SINGLETON_LAUNCHER
# launcher coin contains singleton launcher, launcher coin ID == singleton_id == treasury_id
launcher_coin = Coin(origin.name(), genesis_launcher_puz.get_tree_hash(), dao_rules.proposal_minimum_amount)
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
if vote_amount is None: # pragma: no cover
dao_cat_wallet = self.wallet_state_manager.get_wallet(
id=self.dao_info.dao_cat_wallet_id, required_type=DAOCATWallet
)
vote_amount = await dao_cat_wallet.get_votable_balance(include_free_cats=False)
assert vote_amount is not None
cat_tail_hash = cat_wallet.cat_info.limitations_program_hash
assert cat_tail_hash
dao_proposal_puzzle = get_proposal_puzzle(
proposal_id=launcher_coin.name(),
cat_tail_hash=cat_tail_hash,
treasury_id=self.dao_info.treasury_id,
votes_sum=uint64(0),
total_votes=uint64(0),
proposed_puzzle_hash=proposed_puzzle.get_tree_hash(),
)
full_proposal_puzzle = curry_singleton(launcher_coin.name(), dao_proposal_puzzle)
full_proposal_puzzle_hash = full_proposal_puzzle.get_tree_hash()
announcement_message = Program.to(
[full_proposal_puzzle_hash, dao_rules.proposal_minimum_amount, bytes(0x80)]
).get_tree_hash()
tx_records: List[TransactionRecord] = await self.standard_wallet.generate_signed_transaction(
uint64(dao_rules.proposal_minimum_amount),
genesis_launcher_puz.get_tree_hash(),
tx_config,
fee,
origin_id=origin.name(),
coins=coins,
extra_conditions=(
AssertCoinAnnouncement(asserted_id=launcher_coin.name(), asserted_msg=announcement_message),
),
)
tx_record: TransactionRecord = tx_records[0]
genesis_launcher_solution = Program.to(
[full_proposal_puzzle_hash, dao_rules.proposal_minimum_amount, bytes(0x80)]
)
launcher_cs = make_spend(launcher_coin, genesis_launcher_puz, genesis_launcher_solution)
launcher_sb = SpendBundle([launcher_cs], AugSchemeMPL.aggregate([]))
eve_coin = Coin(launcher_coin.name(), full_proposal_puzzle_hash, dao_rules.proposal_minimum_amount)
future_parent = LineageProof(
eve_coin.parent_coin_info,
dao_proposal_puzzle.get_tree_hash(),
uint64(eve_coin.amount),
)
eve_parent = LineageProof(
bytes32(launcher_coin.parent_coin_info),
bytes32(launcher_coin.puzzle_hash),
uint64(launcher_coin.amount),
)
await self.add_parent(bytes32(eve_coin.parent_coin_info), eve_parent)
await self.add_parent(eve_coin.name(), future_parent)
eve_spend = await self.generate_proposal_eve_spend(
eve_coin=eve_coin,
full_proposal_puzzle=full_proposal_puzzle,
dao_proposal_puzzle=dao_proposal_puzzle,
proposed_puzzle_reveal=proposed_puzzle,
launcher_coin=launcher_coin,
vote_amount=vote_amount,
)
assert tx_record
assert tx_record.spend_bundle is not None
full_spend = SpendBundle.aggregate([tx_record.spend_bundle, eve_spend, launcher_sb])
record = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=full_proposal_puzzle.get_tree_hash(),
amount=uint64(dao_rules.proposal_minimum_amount),
fee_amount=fee,
confirmed=False,
sent=uint32(10),
spend_bundle=full_spend,
additions=full_spend.additions(),
removals=full_spend.removals(),
wallet_id=self.id(),
sent_to=[],
trade_id=None,
type=uint32(TransactionType.INCOMING_TX.value),
name=full_spend.name(),
memos=[],
valid_times=parse_timelock_info(extra_conditions),
)
return [record]
async def generate_proposal_eve_spend(
self,
*,
eve_coin: Coin,
full_proposal_puzzle: Program,
dao_proposal_puzzle: Program,
proposed_puzzle_reveal: Program,
launcher_coin: Coin,
vote_amount: uint64,
) -> SpendBundle:
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
cat_tail = cat_wallet.cat_info.limitations_program_hash
dao_cat_wallet = await DAOCATWallet.get_or_create_wallet_for_cat(
self.wallet_state_manager, self.standard_wallet, cat_tail.hex()
)
assert dao_cat_wallet is not None
dao_cat_spend = await dao_cat_wallet.create_vote_spend(
vote_amount, launcher_coin.name(), True, proposal_puzzle=dao_proposal_puzzle
)
vote_amounts = []
vote_coins = []
previous_votes = []
lockup_inner_puzhashes = []
for spend in dao_cat_spend.coin_spends:
spend_vote_amount = Program.from_bytes(bytes(spend.solution)).at("frrrrrrf").as_int()
vote_amounts.append(spend_vote_amount)
vote_coins.append(spend.coin.name())
previous_votes.append(
get_active_votes_from_lockup_puzzle(
get_innerpuzzle_from_cat_puzzle(Program.from_bytes(bytes(spend.puzzle_reveal)))
)
)
lockup_inner_puz = get_innerpuz_from_lockup_puzzle(
get_innerpuzzle_from_cat_puzzle(Program.from_bytes(bytes(spend.puzzle_reveal)))
)
assert isinstance(lockup_inner_puz, Program)
lockup_inner_puzhashes.append(lockup_inner_puz.get_tree_hash())
inner_sol = Program.to(
[
vote_amounts,
1,
vote_coins,