chia-sdk-driver 0.33.0

Driver code for interacting with standard puzzles on the Chia blockchain.
Documentation
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
use chia_bls::PublicKey;
use chia_protocol::{Bytes32, Coin};
use chia_puzzle_types::{
    CoinProof, LineageProof, Memos,
    cat::{CatSolution, EverythingWithSignatureTailArgs, GenesisByCoinIdTailArgs},
};
use chia_sdk_types::{
    Condition, Conditions,
    conditions::{CreateCoin, RunCatTail},
    puzzles::RevocationSolution,
    run_puzzle,
};
use clvm_traits::FromClvm;
use clvm_utils::ToTreeHash;
use clvmr::{Allocator, NodePtr};

use crate::{CatLayer, DriverError, Layer, Puzzle, RevocationLayer, Spend, SpendContext};

mod cat_info;
mod cat_spend;
mod single_cat_spend;

pub use cat_info::*;
pub use cat_spend::*;
pub use single_cat_spend::*;

/// Contains all information needed to spend the outer puzzles of CAT coins.
/// The [`CatInfo`] is used to construct the puzzle, but the [`LineageProof`] is needed for the solution.
///
/// The only thing missing to create a valid coin spend is the inner puzzle and solution.
/// However, this is handled separately to provide as much flexibility as possible.
///
/// This type should contain all of the information you need to store in a database for later.
/// As long as you can figure out what puzzle the p2 puzzle hash corresponds to and spend it,
/// you have enough information to spend the CAT coin.
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cat {
    /// The coin that this [`Cat`] represents. Its puzzle hash should match the [`CatInfo::puzzle_hash`].
    pub coin: Coin,

    /// The lineage proof is needed by the CAT puzzle to prove that this coin is a legitimate CAT.
    /// It's typically obtained by looking up and parsing the parent coin.
    ///
    /// This can get a bit tedious, so a helper method [`Cat::parse_children`] is provided to parse
    /// the child [`Cat`] objects from the parent (once you have looked up its information on-chain).
    ///
    /// Note that while the lineage proof is needed for most coins, it is optional if you are
    /// issuing more of the CAT by running its TAIL program.
    pub lineage_proof: Option<LineageProof>,

    /// The information needed to construct the outer puzzle of a CAT. See [`CatInfo`] for more details.
    pub info: CatInfo,
}

impl Cat {
    pub fn new(coin: Coin, lineage_proof: Option<LineageProof>, info: CatInfo) -> Self {
        Self {
            coin,
            lineage_proof,
            info,
        }
    }

    pub fn issue_with_coin(
        ctx: &mut SpendContext,
        parent_coin_id: Bytes32,
        amount: u64,
        extra_conditions: Conditions,
    ) -> Result<(Conditions, Vec<Cat>), DriverError> {
        let tail = ctx.curry(GenesisByCoinIdTailArgs::new(parent_coin_id))?;

        Self::issue(
            ctx,
            parent_coin_id,
            None,
            amount,
            RunCatTail::new(tail, NodePtr::NIL),
            extra_conditions,
        )
    }

    pub fn issue_with_key(
        ctx: &mut SpendContext,
        parent_coin_id: Bytes32,
        public_key: PublicKey,
        amount: u64,
        extra_conditions: Conditions,
    ) -> Result<(Conditions, Vec<Cat>), DriverError> {
        let tail = ctx.curry(EverythingWithSignatureTailArgs::new(public_key))?;

        Self::issue(
            ctx,
            parent_coin_id,
            None,
            amount,
            RunCatTail::new(tail, NodePtr::NIL),
            extra_conditions,
        )
    }

    pub fn issue_revocable_with_coin(
        ctx: &mut SpendContext,
        parent_coin_id: Bytes32,
        hidden_puzzle_hash: Bytes32,
        amount: u64,
        extra_conditions: Conditions,
    ) -> Result<(Conditions, Vec<Cat>), DriverError> {
        let tail = ctx.curry(GenesisByCoinIdTailArgs::new(parent_coin_id))?;

        Self::issue(
            ctx,
            parent_coin_id,
            Some(hidden_puzzle_hash),
            amount,
            RunCatTail::new(tail, NodePtr::NIL),
            extra_conditions,
        )
    }

    pub fn issue_revocable_with_key(
        ctx: &mut SpendContext,
        parent_coin_id: Bytes32,
        public_key: PublicKey,
        hidden_puzzle_hash: Bytes32,
        amount: u64,
        extra_conditions: Conditions,
    ) -> Result<(Conditions, Vec<Cat>), DriverError> {
        let tail = ctx.curry(EverythingWithSignatureTailArgs::new(public_key))?;

        Self::issue(
            ctx,
            parent_coin_id,
            Some(hidden_puzzle_hash),
            amount,
            RunCatTail::new(tail, NodePtr::NIL),
            extra_conditions,
        )
    }

    pub fn issue(
        ctx: &mut SpendContext,
        parent_coin_id: Bytes32,
        hidden_puzzle_hash: Option<Bytes32>,
        amount: u64,
        run_tail: RunCatTail<NodePtr, NodePtr>,
        conditions: Conditions,
    ) -> Result<(Conditions, Vec<Cat>), DriverError> {
        let delegated_spend = ctx.delegated_spend(conditions.with(run_tail))?;
        let eve_info = CatInfo::new(
            ctx.tree_hash(run_tail.program).into(),
            hidden_puzzle_hash,
            ctx.tree_hash(delegated_spend.puzzle).into(),
        );

        let eve = Cat::new(
            Coin::new(parent_coin_id, eve_info.puzzle_hash().into(), amount),
            None,
            eve_info,
        );

        let children = Cat::spend_all(ctx, &[CatSpend::new(eve, delegated_spend)])?;

        Ok((
            Conditions::new().create_coin(eve.coin.puzzle_hash, eve.coin.amount, Memos::None),
            children,
        ))
    }

    /// Constructs a [`CoinSpend`](chia_protocol::CoinSpend) for each [`CatSpend`] in the list.
    /// The spends are added to the [`SpendContext`] (in order) for convenience.
    ///
    /// All of the ring announcements and proofs required by the CAT puzzle are calculated automatically.
    /// This requires running the inner spends to get the conditions, so any errors will be propagated.
    ///
    /// It's important not to spend CATs with different asset IDs at the same time, since they are not
    /// compatible.
    ///
    /// Additionally, you should group all CAT spends done in the same transaction together
    /// so that the value of one coin can be freely used in the output of another. If you spend them
    /// separately, there will be multiple announcement rings and a non-zero delta will be calculated.
    pub fn spend_all(
        ctx: &mut SpendContext,
        cat_spends: &[CatSpend],
    ) -> Result<Vec<Cat>, DriverError> {
        let len = cat_spends.len();

        let mut total_delta = 0;
        let mut prev_subtotals = Vec::new();
        let mut run_tail_index = None;
        let mut children = Vec::new();

        for (index, &item) in cat_spends.iter().enumerate() {
            let output = ctx.run(item.spend.puzzle, item.spend.solution)?;
            let conditions: Vec<Condition> = ctx.extract(output)?;

            // If this is the first TAIL reveal, we're going to keep track of it
            if run_tail_index.is_none() && conditions.iter().any(Condition::is_run_cat_tail) {
                run_tail_index = Some(index);
            }

            let create_coins: Vec<CreateCoin<NodePtr>> = conditions
                .into_iter()
                .filter_map(Condition::into_create_coin)
                .collect();

            // Calculate the delta of inputs and outputs
            let delta = create_coins
                .iter()
                .fold(i128::from(item.cat.coin.amount), |delta, create_coin| {
                    delta - i128::from(create_coin.amount)
                });

            // Add the previous subtotal for this coin
            prev_subtotals.push(total_delta);

            // Add the delta to the total
            total_delta += delta;

            for create_coin in create_coins {
                children.push(
                    item.cat
                        .child_from_p2_create_coin(ctx, create_coin, item.hidden),
                );
            }
        }

        // If the TAIL was revealed, we need to adjust the subsequent previous subtotals to account for the extra delta
        if let Some(tail_index) = run_tail_index {
            let tail_adjustment = -total_delta;

            prev_subtotals
                .iter_mut()
                .skip(tail_index + 1)
                .for_each(|subtotal| {
                    *subtotal += tail_adjustment;
                });
        }

        for (index, item) in cat_spends.iter().enumerate() {
            // Find information of neighboring coins on the ring.
            let prev = &cat_spends[if index == 0 { len - 1 } else { index - 1 }];
            let next = &cat_spends[if index == len - 1 { 0 } else { index + 1 }];

            let next_inner_puzzle_hash = next.cat.info.inner_puzzle_hash();

            item.cat.spend(
                ctx,
                SingleCatSpend {
                    p2_spend: item.spend,
                    prev_coin_id: prev.cat.coin.coin_id(),
                    next_coin_proof: CoinProof {
                        parent_coin_info: next.cat.coin.parent_coin_info,
                        inner_puzzle_hash: next_inner_puzzle_hash.into(),
                        amount: next.cat.coin.amount,
                    },
                    prev_subtotal: prev_subtotals[index].try_into()?,
                    // If the TAIL was revealed, we need to add the extra delta needed to net the spend to zero
                    extra_delta: if run_tail_index.is_some_and(|i| i == index) {
                        -total_delta.try_into()?
                    } else {
                        0
                    },
                    revoke: item.hidden,
                },
            )?;
        }

        Ok(children)
    }

    /// Spends this CAT coin with the provided solution parameters. Other parameters are inferred from
    /// the [`Cat`] instance.
    ///
    /// This is useful if you have already calculated the conditions and want to spend the coin directly.
    /// However, it's more common to use [`Cat::spend_all`] which handles the details of calculating the
    /// solution (including ring announcements) for multiple CATs and spending them all at once.
    pub fn spend(&self, ctx: &mut SpendContext, info: SingleCatSpend) -> Result<(), DriverError> {
        let mut spend = info.p2_spend;

        if let Some(hidden_puzzle_hash) = self.info.hidden_puzzle_hash {
            spend = RevocationLayer::new(hidden_puzzle_hash, self.info.p2_puzzle_hash)
                .construct_spend(
                    ctx,
                    RevocationSolution::new(info.revoke, spend.puzzle, spend.solution),
                )?;
        }

        spend = CatLayer::new(self.info.asset_id, spend.puzzle).construct_spend(
            ctx,
            CatSolution {
                lineage_proof: self.lineage_proof,
                inner_puzzle_solution: spend.solution,
                prev_coin_id: info.prev_coin_id,
                this_coin_info: self.coin,
                next_coin_proof: info.next_coin_proof,
                extra_delta: info.extra_delta,
                prev_subtotal: info.prev_subtotal,
            },
        )?;

        ctx.spend(self.coin, spend)?;

        Ok(())
    }

    /// Creates a [`LineageProof`] for which would be valid for any children created by this [`Cat`].
    pub fn child_lineage_proof(&self) -> LineageProof {
        LineageProof {
            parent_parent_coin_info: self.coin.parent_coin_info,
            parent_inner_puzzle_hash: self.info.inner_puzzle_hash().into(),
            parent_amount: self.coin.amount,
        }
    }

    /// Creates a new [`Cat`] that represents a child of this one.
    /// The child will have the same revocation layer (or lack thereof) as the current [`Cat`].
    ///
    /// If you need to construct a child without the revocation layer, use [`Cat::unrevocable_child`].
    pub fn child(&self, p2_puzzle_hash: Bytes32, amount: u64) -> Self {
        self.child_with(
            CatInfo {
                p2_puzzle_hash,
                ..self.info
            },
            amount,
        )
    }

    /// Creates a new [`Cat`] that represents a child of this one.
    /// The child will not have a revocation layer.
    ///
    /// If you need to construct a child with the same revocation layer, use [`Cat::child`].
    pub fn unrevocable_child(&self, p2_puzzle_hash: Bytes32, amount: u64) -> Self {
        self.child_with(
            CatInfo {
                p2_puzzle_hash,
                hidden_puzzle_hash: None,
                ..self.info
            },
            amount,
        )
    }

    /// Creates a new [`Cat`] that represents a child of this one.
    ///
    /// You can specify the [`CatInfo`] to use for the child manually.
    /// In most cases, you will want to use [`Cat::child`] or [`Cat::unrevocable_child`] instead.
    pub fn child_with(&self, info: CatInfo, amount: u64) -> Self {
        Self {
            coin: Coin::new(self.coin.coin_id(), info.puzzle_hash().into(), amount),
            lineage_proof: Some(self.child_lineage_proof()),
            info,
        }
    }

    /// Parses a [`Cat`] and its p2 spend from a coin spend by extracting the [`CatLayer`] and [`RevocationLayer`] if present.
    ///
    /// If the puzzle is not a CAT, this will return [`None`] instead of an error.
    /// However, if the puzzle should have been a CAT but had a parsing error, this will return an error.
    pub fn parse(
        allocator: &Allocator,
        coin: Coin,
        puzzle: Puzzle,
        solution: NodePtr,
    ) -> Result<Option<(Self, Puzzle, NodePtr)>, DriverError> {
        let Some(cat_layer) = CatLayer::<Puzzle>::parse_puzzle(allocator, puzzle)? else {
            return Ok(None);
        };
        let cat_solution = CatLayer::<Puzzle>::parse_solution(allocator, solution)?;

        if let Some(revocation_layer) =
            RevocationLayer::parse_puzzle(allocator, cat_layer.inner_puzzle)?
        {
            let revocation_solution =
                RevocationLayer::parse_solution(allocator, cat_solution.inner_puzzle_solution)?;

            let info = Self::new(
                coin,
                cat_solution.lineage_proof,
                CatInfo::new(
                    cat_layer.asset_id,
                    Some(revocation_layer.hidden_puzzle_hash),
                    revocation_layer.inner_puzzle_hash,
                ),
            );

            Ok(Some((
                info,
                Puzzle::parse(allocator, revocation_solution.puzzle),
                revocation_solution.solution,
            )))
        } else {
            let info = Self::new(
                coin,
                cat_solution.lineage_proof,
                CatInfo::new(
                    cat_layer.asset_id,
                    None,
                    cat_layer.inner_puzzle.curried_puzzle_hash().into(),
                ),
            );

            Ok(Some((
                info,
                cat_layer.inner_puzzle,
                cat_solution.inner_puzzle_solution,
            )))
        }
    }

    /// Parses the children of a [`Cat`] from the parent coin spend.
    ///
    /// This can be used to construct a valid spendable [`Cat`] for a hinted coin.
    /// You simply need to look up the parent coin's spend, parse the children, and
    /// find the one that matches the hinted coin.
    ///
    /// There is special handling for the revocation layer.
    /// See [`Cat::child_from_p2_create_coin`] for more details.
    pub fn parse_children(
        allocator: &mut Allocator,
        parent_coin: Coin,
        parent_puzzle: Puzzle,
        parent_solution: NodePtr,
    ) -> Result<Option<Vec<Self>>, DriverError> {
        let Some(parent_layer) = CatLayer::<Puzzle>::parse_puzzle(allocator, parent_puzzle)? else {
            return Ok(None);
        };
        let parent_solution = CatLayer::<Puzzle>::parse_solution(allocator, parent_solution)?;

        let mut hidden_puzzle_hash = None;
        let mut p2_puzzle_hash = parent_layer.inner_puzzle.curried_puzzle_hash().into();
        let mut inner_spend = Spend::new(
            parent_layer.inner_puzzle.ptr(),
            parent_solution.inner_puzzle_solution,
        );
        let mut revoke = false;

        if let Some(revocation_layer) =
            RevocationLayer::parse_puzzle(allocator, parent_layer.inner_puzzle)?
        {
            hidden_puzzle_hash = Some(revocation_layer.hidden_puzzle_hash);
            p2_puzzle_hash = revocation_layer.inner_puzzle_hash;

            let revocation_solution =
                RevocationLayer::parse_solution(allocator, parent_solution.inner_puzzle_solution)?;

            inner_spend = Spend::new(revocation_solution.puzzle, revocation_solution.solution);
            revoke = revocation_solution.hidden;
        }

        let cat = Cat::new(
            parent_coin,
            parent_solution.lineage_proof,
            CatInfo::new(parent_layer.asset_id, hidden_puzzle_hash, p2_puzzle_hash),
        );

        let output = run_puzzle(allocator, inner_spend.puzzle, inner_spend.solution)?;
        let conditions = Vec::<Condition>::from_clvm(allocator, output)?;

        let outputs = conditions
            .into_iter()
            .filter_map(Condition::into_create_coin)
            .map(|create_coin| cat.child_from_p2_create_coin(allocator, create_coin, revoke))
            .collect();

        Ok(Some(outputs))
    }

    /// Creates a new [`Cat`] that reflects the create coin condition in the p2 spend's conditions.
    ///
    /// There is special handling for the revocation layer:
    /// 1. If there is no revocation layer for the parent, the child will not have one either.
    /// 2. If the parent was not revoked, the child will have the same revocation layer.
    /// 3. If the parent was revoked, the child will not have a revocation layer.
    /// 4. If the parent was revoked, and the child was hinted (and wrapped with the revocation layer), it will detect it.
    pub fn child_from_p2_create_coin(
        &self,
        allocator: &Allocator,
        create_coin: CreateCoin<NodePtr>,
        revoke: bool,
    ) -> Self {
        // Child with the same hidden puzzle hash as the parent
        let child = self.child(create_coin.puzzle_hash, create_coin.amount);

        // If the parent is not revocable, we don't need to add a revocation layer
        let Some(hidden_puzzle_hash) = self.info.hidden_puzzle_hash else {
            return child;
        };

        // If we're not doing a revocation spend, we know it's wrapped in the same revocation layer
        if !revoke {
            return child;
        }

        // Child without a hidden puzzle hash but with the create coin puzzle hash as the p2 puzzle hash
        let unrevocable_child = self.unrevocable_child(create_coin.puzzle_hash, create_coin.amount);

        // If the hint is missing, just assume the child doesn't have a hidden puzzle hash
        let Memos::Some(memos) = create_coin.memos else {
            return unrevocable_child;
        };

        let Some((hint, _)) = <(Bytes32, NodePtr)>::from_clvm(allocator, memos).ok() else {
            return unrevocable_child;
        };

        // If the hint wrapped in the revocation layer of the parent matches the create coin's puzzle hash,
        // then we know that the hint is the p2 puzzle hash and the child has the same revocation layer as the parent
        if create_coin.puzzle_hash
            == RevocationLayer::new(hidden_puzzle_hash, hint)
                .tree_hash()
                .into()
        {
            return self.child(hint, create_coin.amount);
        }

        // Otherwise, we can't determine whether there is a revocation layer or not, so we will just assume it's unrevocable
        // In practice, this should never happen while parsing a coin which is still spendable (not an ephemeral spend)
        // If it does, a new hinting mechanism should be introduced in the future to accommodate this, but for now this is the best we can do
        unrevocable_child
    }
}

#[cfg(test)]
mod tests {
    use std::slice;

    use chia_puzzle_types::cat::EverythingWithSignatureTailArgs;
    use chia_sdk_test::Simulator;
    use chia_sdk_types::{Mod, puzzles::RevocationArgs};
    use rstest::rstest;

    use crate::{SpendWithConditions, StandardLayer};

    use super::*;

    #[test]
    fn test_single_issuance_cat() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(1);
        let alice_p2 = StandardLayer::new(alice.pk);

        let memos = ctx.hint(alice.puzzle_hash)?;
        let (issue_cat, cats) = Cat::issue_with_coin(
            ctx,
            alice.coin.coin_id(),
            1,
            Conditions::new().create_coin(alice.puzzle_hash, 1, memos),
        )?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        sim.spend_coins(ctx.take(), &[alice.sk])?;

        let cat = cats[0];
        assert_eq!(cat.info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(
            cat.info.asset_id,
            GenesisByCoinIdTailArgs::curry_tree_hash(alice.coin.coin_id()).into()
        );
        assert!(sim.coin_state(cat.coin.coin_id()).is_some());

        Ok(())
    }

    #[test]
    fn test_multi_issuance_cat() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(1);
        let alice_p2 = StandardLayer::new(alice.pk);

        let memos = ctx.hint(alice.puzzle_hash)?;
        let (issue_cat, cats) = Cat::issue_with_key(
            ctx,
            alice.coin.coin_id(),
            alice.pk,
            1,
            Conditions::new().create_coin(alice.puzzle_hash, 1, memos),
        )?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;
        sim.spend_coins(ctx.take(), &[alice.sk])?;

        let cat = cats[0];
        assert_eq!(cat.info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(
            cat.info.asset_id,
            EverythingWithSignatureTailArgs::curry_tree_hash(alice.pk).into()
        );
        assert!(sim.coin_state(cat.coin.coin_id()).is_some());

        Ok(())
    }

    #[test]
    fn test_zero_cat_issuance() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(0);
        let alice_p2 = StandardLayer::new(alice.pk);

        let memos = ctx.hint(alice.puzzle_hash)?;
        let (issue_cat, cats) = Cat::issue_with_coin(
            ctx,
            alice.coin.coin_id(),
            0,
            Conditions::new().create_coin(alice.puzzle_hash, 0, memos),
        )?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        sim.spend_coins(ctx.take(), slice::from_ref(&alice.sk))?;

        let cat = cats[0];
        assert_eq!(cat.info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(
            cat.info.asset_id,
            GenesisByCoinIdTailArgs::curry_tree_hash(alice.coin.coin_id()).into()
        );
        assert!(sim.coin_state(cat.coin.coin_id()).is_some());

        let cat_spend = CatSpend::new(
            cat,
            alice_p2.spend_with_conditions(
                ctx,
                Conditions::new().create_coin(alice.puzzle_hash, 0, memos),
            )?,
        );
        Cat::spend_all(ctx, &[cat_spend])?;
        sim.spend_coins(ctx.take(), &[alice.sk])?;

        Ok(())
    }

    #[test]
    fn test_missing_cat_issuance_output() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(1);
        let alice_p2 = StandardLayer::new(alice.pk);

        let (issue_cat, _cats) =
            Cat::issue_with_coin(ctx, alice.coin.coin_id(), 1, Conditions::new())?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        assert_eq!(
            sim.spend_coins(ctx.take(), &[alice.sk])
                .unwrap_err()
                .to_string(),
            "Signer error: Eval error: clvm raise"
        );

        Ok(())
    }

    #[test]
    fn test_exceeded_cat_issuance_output() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(2);
        let alice_p2 = StandardLayer::new(alice.pk);

        let memos = ctx.hint(alice.puzzle_hash)?;
        let (issue_cat, _cats) = Cat::issue_with_coin(
            ctx,
            alice.coin.coin_id(),
            1,
            Conditions::new().create_coin(alice.puzzle_hash, 2, memos),
        )?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        assert_eq!(
            sim.spend_coins(ctx.take(), &[alice.sk])
                .unwrap_err()
                .to_string(),
            "Signer error: Eval error: clvm raise"
        );

        Ok(())
    }

    #[rstest]
    #[case(1)]
    #[case(2)]
    #[case(3)]
    #[case(10)]
    fn test_cat_spends(#[case] coins: usize) -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        // All of the amounts are different to prevent coin id collisions.
        let mut amounts = Vec::with_capacity(coins);

        for amount in 0..coins {
            amounts.push(amount as u64);
        }

        // Create the coin with the sum of all the amounts we need to issue.
        let sum = amounts.iter().sum::<u64>();

        let alice = sim.bls(sum);
        let alice_p2 = StandardLayer::new(alice.pk);

        // Issue the CAT coins with those amounts.
        let mut conditions = Conditions::new();

        let memos = ctx.hint(alice.puzzle_hash)?;
        for &amount in &amounts {
            conditions = conditions.create_coin(alice.puzzle_hash, amount, memos);
        }

        let (issue_cat, mut cats) =
            Cat::issue_with_coin(ctx, alice.coin.coin_id(), sum, conditions)?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        sim.spend_coins(ctx.take(), slice::from_ref(&alice.sk))?;

        // Spend the CAT coins a few times.
        for _ in 0..3 {
            let cat_spends: Vec<CatSpend> = cats
                .iter()
                .map(|cat| {
                    Ok(CatSpend::new(
                        *cat,
                        alice_p2.spend_with_conditions(
                            ctx,
                            Conditions::new().create_coin(
                                alice.puzzle_hash,
                                cat.coin.amount,
                                memos,
                            ),
                        )?,
                    ))
                })
                .collect::<anyhow::Result<_>>()?;

            cats = Cat::spend_all(ctx, &cat_spends)?;
            sim.spend_coins(ctx.take(), slice::from_ref(&alice.sk))?;
        }

        Ok(())
    }

    #[test]
    fn test_different_cat_p2_puzzles() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(2);
        let alice_p2 = StandardLayer::new(alice.pk);

        // This will just return the solution verbatim.
        let custom_p2 = ctx.alloc(&1)?;
        let custom_p2_puzzle_hash = ctx.tree_hash(custom_p2).into();

        let memos = ctx.hint(alice.puzzle_hash)?;
        let custom_memos = ctx.hint(custom_p2_puzzle_hash)?;
        let (issue_cat, cats) = Cat::issue_with_coin(
            ctx,
            alice.coin.coin_id(),
            2,
            Conditions::new()
                .create_coin(alice.puzzle_hash, 1, memos)
                .create_coin(custom_p2_puzzle_hash, 1, custom_memos),
        )?;
        alice_p2.spend(ctx, alice.coin, issue_cat)?;
        sim.spend_coins(ctx.take(), slice::from_ref(&alice.sk))?;

        let spends = [
            CatSpend::new(
                cats[0],
                alice_p2.spend_with_conditions(
                    ctx,
                    Conditions::new().create_coin(alice.puzzle_hash, 1, memos),
                )?,
            ),
            CatSpend::new(
                cats[1],
                Spend::new(
                    custom_p2,
                    ctx.alloc(&[CreateCoin::new(custom_p2_puzzle_hash, 1, custom_memos)])?,
                ),
            ),
        ];

        Cat::spend_all(ctx, &spends)?;
        sim.spend_coins(ctx.take(), &[alice.sk])?;

        Ok(())
    }

    #[test]
    fn test_cat_melt() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(10000);
        let alice_p2 = StandardLayer::new(alice.pk);
        let hint = ctx.hint(alice.puzzle_hash)?;

        let conditions = Conditions::new().create_coin(alice.puzzle_hash, 10000, hint);

        let (issue_cat, cats) =
            Cat::issue_with_key(ctx, alice.coin.coin_id(), alice.pk, 10000, conditions)?;

        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        let tail = ctx.curry(EverythingWithSignatureTailArgs::new(alice.pk))?;

        let cat_spend = CatSpend::new(
            cats[0],
            alice_p2.spend_with_conditions(
                ctx,
                Conditions::new()
                    .create_coin(alice.puzzle_hash, 7000, hint)
                    .run_cat_tail(tail, NodePtr::NIL),
            )?,
        );

        Cat::spend_all(ctx, &[cat_spend])?;

        sim.spend_coins(ctx.take(), &[alice.sk])?;

        Ok(())
    }

    #[rstest]
    fn test_cat_tail_reveal(
        #[values(0, 1, 2)] tail_index: usize,
        #[values(true, false)] melt: bool,
    ) -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let ctx = &mut SpendContext::new();

        let alice = sim.bls(15000);
        let alice_p2 = StandardLayer::new(alice.pk);
        let hint = ctx.hint(alice.puzzle_hash)?;

        let conditions = Conditions::new()
            .create_coin(alice.puzzle_hash, 3000, hint)
            .create_coin(alice.puzzle_hash, 6000, hint)
            .create_coin(alice.puzzle_hash, 1000, hint);

        let (issue_cat, cats) =
            Cat::issue_with_key(ctx, alice.coin.coin_id(), alice.pk, 10000, conditions)?;

        alice_p2.spend(ctx, alice.coin, issue_cat)?;

        let tail = ctx.curry(EverythingWithSignatureTailArgs::new(alice.pk))?;

        let cat_spends = cats
            .into_iter()
            .enumerate()
            .map(|(i, cat)| {
                let mut conditions = Conditions::new();

                // Add the TAIL reveal to the second spend, to ensure the order doesn't matter
                if i == tail_index {
                    conditions.push(RunCatTail::new(tail, NodePtr::NIL));

                    if !melt {
                        conditions.push(CreateCoin::new(alice.puzzle_hash, 15000, hint));
                    }
                }

                Ok(CatSpend::new(
                    cat,
                    alice_p2.spend_with_conditions(ctx, conditions)?,
                ))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        Cat::spend_all(ctx, &cat_spends)?;

        sim.spend_coins(ctx.take(), &[alice.sk])?;

        Ok(())
    }

    #[test]
    fn test_revocable_cat() -> anyhow::Result<()> {
        let mut sim = Simulator::new();
        let mut ctx = SpendContext::new();

        let alice = sim.bls(10);
        let alice_p2 = StandardLayer::new(alice.pk);

        let bob = sim.bls(0);
        let bob_p2 = StandardLayer::new(bob.pk);

        let asset_id = EverythingWithSignatureTailArgs::curry_tree_hash(alice.pk).into();
        let hint = ctx.hint(bob.puzzle_hash)?;

        let (issue_cat, cats) = Cat::issue_revocable_with_key(
            &mut ctx,
            alice.coin.coin_id(),
            alice.pk,
            alice.puzzle_hash,
            10,
            Conditions::new().create_coin(bob.puzzle_hash, 10, hint),
        )?;
        alice_p2.spend(&mut ctx, alice.coin, issue_cat)?;

        // Bob can spend the CAT because he owns it
        let cat_spend = CatSpend::new(
            cats[0],
            bob_p2.spend_with_conditions(
                &mut ctx,
                Conditions::new().create_coin(bob.puzzle_hash, 10, hint),
            )?,
        );
        let cats = Cat::spend_all(&mut ctx, &[cat_spend])?;

        // But Alice can also spend (revoke) it because she owns the revocation key
        let hint = ctx.hint(alice.puzzle_hash)?;

        let revocable_puzzle_hash = RevocationArgs::new(alice.puzzle_hash, alice.puzzle_hash)
            .curry_tree_hash()
            .into();

        let cat_spend = CatSpend::revoke(
            cats[0],
            alice_p2.spend_with_conditions(
                &mut ctx,
                Conditions::new()
                    .create_coin(alice.puzzle_hash, 5, hint)
                    .create_coin(revocable_puzzle_hash, 5, hint),
            )?,
        );

        let cats = Cat::spend_all(&mut ctx, &[cat_spend])?;

        // Validate the transaction
        sim.spend_coins(ctx.take(), &[alice.sk.clone(), bob.sk.clone()])?;

        // The first coin should exist and not be revocable
        assert_ne!(sim.coin_state(cats[0].coin.coin_id()), None);
        assert_eq!(cats[0].info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(cats[0].info.asset_id, asset_id);
        assert_eq!(cats[0].info.hidden_puzzle_hash, None);

        // The second coin should exist and be revocable
        assert_ne!(sim.coin_state(cats[1].coin.coin_id()), None);
        assert_eq!(cats[1].info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(cats[1].info.asset_id, asset_id);
        assert_eq!(cats[1].info.hidden_puzzle_hash, Some(alice.puzzle_hash));

        let lineage_proof = cats[0].lineage_proof;

        let parent_spend = sim.coin_spend(cats[0].coin.parent_coin_info).unwrap();
        let parent_puzzle = ctx.alloc(&parent_spend.puzzle_reveal)?;
        let parent_puzzle = Puzzle::parse(&ctx, parent_puzzle);
        let parent_solution = ctx.alloc(&parent_spend.solution)?;

        let cats =
            Cat::parse_children(&mut ctx, parent_spend.coin, parent_puzzle, parent_solution)?
                .unwrap();

        // The first coin should exist and not be revocable
        assert_ne!(sim.coin_state(cats[0].coin.coin_id()), None);
        assert_eq!(cats[0].info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(cats[0].info.asset_id, asset_id);
        assert_eq!(cats[0].info.hidden_puzzle_hash, None);

        // The second coin should exist and be revocable
        assert_ne!(sim.coin_state(cats[1].coin.coin_id()), None);
        assert_eq!(cats[1].info.p2_puzzle_hash, alice.puzzle_hash);
        assert_eq!(cats[1].info.asset_id, asset_id);
        assert_eq!(cats[1].info.hidden_puzzle_hash, Some(alice.puzzle_hash));

        assert_eq!(cats[0].lineage_proof, lineage_proof);

        let cat_spends = cats
            .into_iter()
            .map(|cat| {
                Ok(CatSpend::revoke(
                    cat,
                    alice_p2.spend_with_conditions(
                        &mut ctx,
                        Conditions::new().create_coin(alice.puzzle_hash, 5, hint),
                    )?,
                ))
            })
            .collect::<anyhow::Result<Vec<_>>>()?;

        _ = Cat::spend_all(&mut ctx, &cat_spends)?;

        // Validate the transaction
        sim.spend_coins(ctx.take(), &[alice.sk, bob.sk])?;

        Ok(())
    }
}