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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
use std::collections::HashSet;

use chia_protocol::{Bytes32, Coin, CoinSpend};
use chia_puzzle_types::{
    Memos,
    nft::NftMetadata,
    offer::{NotarizedPayment, SettlementPaymentsSolution},
};
use chia_puzzles::SETTLEMENT_PAYMENT_HASH;
use chia_sdk_types::{
    Condition, MessageFlags, MessageSide, Mod, announcement_id, conditions::CreateCoin,
    puzzles::SingletonMember, run_puzzle, tree_hash_notarized_payment,
};
use clvm_traits::{FromClvm, ToClvm};
use clvm_utils::TreeHash;
use clvmr::{Allocator, NodePtr};

use crate::{
    BURN_PUZZLE_HASH, Cat, ClawbackV2, DriverError, MetadataUpdate, Nft, Puzzle, Spend, UriKind,
    mips_puzzle_hash,
};

/// Information about a vault that must be provided in order to securely parse a transaction.
#[derive(Debug, Clone, Copy)]
pub struct VaultSpendReveal {
    /// The launcher id of the vault's singleton.
    /// This is used to calculate the p2 puzzle hash.
    pub launcher_id: Bytes32,
    /// The inner puzzle hash of the vault singleton.
    /// This is used to construct the puzzle hash we're signing for.
    pub custody_hash: TreeHash,
    /// The delegated puzzle we're signing and its solution.
    /// Its output is the non-custody related conditions that the vault spend will output.
    pub delegated_spend: Spend,
}

/// The purpose of this is to provide sufficient information to verify what is happening to a vault and its assets
/// as a result of a transaction at a glance. Information that is not verifiable should not be included or displayed.
/// We can still allow transactions which are not fully verifiable, but a conservative summary should be provided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VaultTransaction {
    /// If a new vault coin is created (i.e. the vault isn't melted), this will be set.
    /// It's the new inner puzzle hash of the vault singleton. If it's different, the custody configuration has changed.
    /// It can be validated against a [`MipsMemo`](crate::MipsMemo) so that you know what specifically is happening.
    pub new_custody_hash: Option<TreeHash>,
    /// Fungible asset payments that are relevant to the vault and can be verified to exist if the signature is used.
    pub payments: Vec<ParsedPayment>,
    /// NFT transfers that are relevant to the vault and can be verified to exist if the signature is used.
    pub nfts: Vec<ParsedNftTransfer>,
    /// Coins which were created as outputs of the vault singleton spend itself, for example to mint NFTs.
    pub drop_coins: Vec<DropCoin>,
    /// Total fees (different between input and output amounts) paid by coin spends authorized by the vault.
    /// If the transaction is signed, the fee is guaranteed to be at least this amount, unless it's not reserved.
    /// The reason to include unreserved fees is to make it clear that the XCH is leaving the vault due to this transaction.
    pub fee_paid: u64,
    /// Total fees (different between input and output amounts) paid by all coin spends in the transaction combined.
    /// Because the full coin spend list cannot be validated off-chain, this is not guaranteed to be accurate.
    pub total_fee: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedPayment {
    /// The direction in which the asset is being transferred.
    pub transfer_type: TransferType,
    /// The asset id, if applicable. This may be [`None`] for XCH, or [`Some`] for a CAT.
    pub asset_id: Option<Bytes32>,
    /// The revocation hidden puzzle hash (if the asset is a revocable CAT).
    pub hidden_puzzle_hash: Option<Bytes32>,
    /// The custody p2 puzzle hash that the payment is being sent to (analogous to a decoded XCH or TXCH address).
    pub p2_puzzle_hash: Bytes32,
    /// The coin that will be created as a result of this payment being confirmed on-chain.
    /// This includes the amount being paid to the p2 puzzle hash.
    pub coin: Coin,
    /// If applicable, the clawback information for the payment (including who can claw it back and for how long).
    pub clawback: Option<ClawbackV2>,
    /// The potentially human readable memo list after the hint and/or clawback memo is removed.
    pub memos: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedNftTransfer {
    /// The direction in which the NFT is being transferred.
    pub transfer_type: TransferType,
    /// The launcher id of the NFT.
    pub launcher_id: Bytes32,
    /// The custody p2 puzzle hash that the NFT is being sent to (analogous to a decoded XCH or TXCH address).
    pub p2_puzzle_hash: Bytes32,
    /// The latest NFT coin that is confirmed to be created as a result of this transaction.
    /// Unverifiable coin spends will be excluded.
    pub coin: Coin,
    /// If applicable, the clawback information for the NFT (including who can claw it back and for how long).
    pub clawback: Option<ClawbackV2>,
    /// The potentially human readable memo list after the hint and/or clawback memo is removed.
    pub memos: Vec<String>,
    /// URIs which are added to the NFT's metadata as part of coin spends which can be verified to exist.
    pub new_uris: Vec<MetadataUpdate>,
    /// The latest owner hash of the NFT from verified coin spends.
    pub latest_owner: Option<Bytes32>,
    /// Whether the NFT transfer includes unverifiable metadata updates.
    pub includes_unverifiable_updates: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferType {
    /// These are payments that are output from coin spends which have been authorized by the vault.
    /// Notably, this will not include payments that are being sent to the vault's p2 puzzle hash.
    /// Thus, this excludes change coins and payments that are received from taken offers.
    Sent,
    /// Instead of being [`TransferType::Sent`], this is being sent to the burn address.
    Burned,
    /// Instead of being [`TransferType::Sent`], this is being sent to the settlement payments.
    Offered,
    /// These are payments to the vault's p2 puzzle hash that are output from offer settlement coins.
    /// Change coins and non-offer payments are excluded, since their authenticity cannot be easily verified off-chain.
    /// An offer payment is also excluded if its notarized payment announcement id is not asserted by a coin spend authorized by the vault.
    Received,
    /// When the coin spend originally comes from the vault, and ends up back in the vault, this is an update.
    /// It's only used for singleton transactions.
    Updated,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DropCoin {
    pub puzzle_hash: Bytes32,
    pub amount: u64,
}

impl VaultTransaction {
    pub fn parse(
        allocator: &mut Allocator,
        vault: &VaultSpendReveal,
        coin_spends: Vec<CoinSpend>,
    ) -> Result<Self, DriverError> {
        let our_p2_puzzle_hash = vault_p2_puzzle_hash(vault.launcher_id);

        let all_spent_coin_ids = coin_spends.iter().map(|cs| cs.coin.coin_id()).collect();

        let ParsedDelegatedSpend {
            new_custody_hash,
            our_spent_coin_ids,
            puzzle_assertion_ids,
            drop_coins,
        } = parse_delegated_spend(allocator, vault.delegated_spend, &all_spent_coin_ids)?;

        let ParsedConditions {
            puzzle_assertion_ids,
            all_created_coin_ids,
        } = parse_our_conditions(
            allocator,
            &coin_spends,
            &our_spent_coin_ids,
            puzzle_assertion_ids,
        )?;

        let coin_spends = reorder_coin_spends(coin_spends);

        let mut payments = Vec::new();
        let mut nfts = Vec::new();
        let mut our_input = 0;
        let mut our_output = 0;
        let mut total_input = 0;
        let mut total_output = 0;

        for coin_spend in coin_spends {
            let coin_id = coin_spend.coin.coin_id();
            let is_parent_ours = our_spent_coin_ids.contains(&coin_id);
            let is_parent_ephemeral = all_created_coin_ids.contains(&coin_id);

            total_input += coin_spend.coin.amount;

            if is_parent_ours && !is_parent_ephemeral {
                our_input += coin_spend.coin.amount;
            }

            let puzzle = coin_spend.puzzle_reveal.to_clvm(allocator)?;
            let puzzle = Puzzle::parse(allocator, puzzle);
            let solution = coin_spend.solution.to_clvm(allocator)?;

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

            if let Some((cat, p2_puzzle, p2_solution)) =
                Cat::parse(allocator, coin_spend.coin, puzzle, solution)?
            {
                let p2_output = run_puzzle(allocator, p2_puzzle.ptr(), p2_solution)?;

                let mut p2_create_coins = Vec::<Condition>::from_clvm(allocator, p2_output)?
                    .into_iter()
                    .filter_map(Condition::into_create_coin)
                    .collect::<Vec<_>>();

                let children = Cat::parse_children(allocator, coin_spend.coin, puzzle, solution)?
                    .unwrap_or_default();

                let notarized_payments =
                    if cat.info.p2_puzzle_hash == SETTLEMENT_PAYMENT_HASH.into() {
                        SettlementPaymentsSolution::from_clvm(allocator, p2_solution)?
                            .notarized_payments
                    } else {
                        Vec::new()
                    };

                for child in children {
                    let child_coin_id = child.coin.coin_id();
                    let create_coin = p2_create_coins.remove(0);
                    let parsed_memos = parse_memos(allocator, create_coin, true);
                    let is_child_ours = parsed_memos.p2_puzzle_hash == our_p2_puzzle_hash;
                    let is_child_ephemeral = all_spent_coin_ids.contains(&child_coin_id);

                    total_output += child.coin.amount;

                    if is_parent_ours && !is_child_ephemeral {
                        our_output += child.coin.amount;
                    }

                    // Skip ephemeral coins
                    if our_spent_coin_ids.contains(&child_coin_id) {
                        continue;
                    }

                    if let Some(transfer_type) = calculate_transfer_type(
                        allocator,
                        TransferTypeContext {
                            puzzle_assertion_ids: &puzzle_assertion_ids,
                            notarized_payments: &notarized_payments,
                            create_coin: &create_coin,
                            p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                            full_puzzle_hash: cat.coin.puzzle_hash,
                            is_parent_ours,
                            is_child_ours,
                        },
                    ) {
                        payments.push(ParsedPayment {
                            transfer_type,
                            asset_id: Some(child.info.asset_id),
                            hidden_puzzle_hash: child.info.hidden_puzzle_hash,
                            p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                            coin: child.coin,
                            clawback: parsed_memos.clawback,
                            memos: parsed_memos.memos,
                        });
                    }
                }

                continue;
            }

            let mut is_singleton = false;

            if let Some((nft, p2_puzzle, p2_solution)) =
                Nft::parse(allocator, coin_spend.coin, puzzle, solution)?
            {
                is_singleton = true;

                let p2_output = run_puzzle(allocator, p2_puzzle.ptr(), p2_solution)?;

                let mut p2_create_coins = Vec::<Condition>::from_clvm(allocator, p2_output)?
                    .into_iter()
                    .filter_map(Condition::into_create_coin)
                    .filter(|cc| cc.amount % 2 == 1)
                    .collect::<Vec<_>>();

                let child = Nft::parse_child(allocator, coin_spend.coin, puzzle, solution)?
                    .ok_or(DriverError::MissingChild)?;

                let notarized_payments =
                    if nft.info.p2_puzzle_hash == SETTLEMENT_PAYMENT_HASH.into() {
                        SettlementPaymentsSolution::from_clvm(allocator, p2_solution)?
                            .notarized_payments
                    } else {
                        Vec::new()
                    };

                let child_coin_id = child.coin.coin_id();
                let is_child_ephemeral = all_spent_coin_ids.contains(&child_coin_id);
                let create_coin = p2_create_coins.remove(0);
                let parsed_memos = parse_memos(allocator, create_coin, true);
                let is_child_ours = parsed_memos.p2_puzzle_hash == our_p2_puzzle_hash;

                total_output += child.coin.amount;

                if is_parent_ours && !is_child_ephemeral {
                    our_output += child.coin.amount;
                }

                // Skip ephemeral coins
                if our_spent_coin_ids.contains(&child.coin.coin_id()) {
                    continue;
                }

                if let Some(transfer_type) = calculate_transfer_type(
                    allocator,
                    TransferTypeContext {
                        puzzle_assertion_ids: &puzzle_assertion_ids,
                        notarized_payments: &notarized_payments,
                        create_coin: &create_coin,
                        p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                        full_puzzle_hash: nft.coin.puzzle_hash,
                        is_parent_ours,
                        is_child_ours,
                    },
                ) {
                    let mut includes_unverifiable_updates = false;

                    let new_uris = if let Ok(old_metadata) =
                        NftMetadata::from_clvm(allocator, nft.info.metadata.ptr())
                        && let Ok(new_metadata) =
                            NftMetadata::from_clvm(allocator, child.info.metadata.ptr())
                    {
                        let mut new_uris = Vec::new();

                        for uri in new_metadata.data_uris {
                            if !old_metadata.data_uris.contains(&uri) {
                                new_uris.push(MetadataUpdate {
                                    kind: UriKind::Data,
                                    uri,
                                });
                            }
                        }

                        for uri in new_metadata.metadata_uris {
                            if !old_metadata.metadata_uris.contains(&uri) {
                                new_uris.push(MetadataUpdate {
                                    kind: UriKind::Metadata,
                                    uri,
                                });
                            }
                        }

                        for uri in new_metadata.license_uris {
                            if !old_metadata.license_uris.contains(&uri) {
                                new_uris.push(MetadataUpdate {
                                    kind: UriKind::License,
                                    uri,
                                });
                            }
                        }

                        new_uris
                    } else {
                        includes_unverifiable_updates |= nft.info.metadata != child.info.metadata;

                        vec![]
                    };

                    nfts.push(ParsedNftTransfer {
                        transfer_type,
                        launcher_id: child.info.launcher_id,
                        p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                        coin: child.coin,
                        clawback: parsed_memos.clawback,
                        memos: parsed_memos.memos,
                        new_uris,
                        latest_owner: child.info.current_owner,
                        includes_unverifiable_updates,
                    });
                }
            }

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

            let notarized_payments =
                if coin_spend.coin.puzzle_hash == SETTLEMENT_PAYMENT_HASH.into() {
                    SettlementPaymentsSolution::from_clvm(allocator, solution)?.notarized_payments
                } else {
                    Vec::new()
                };

            for create_coin in create_coins {
                let child_coin = Coin::new(
                    coin_spend.coin.coin_id(),
                    create_coin.puzzle_hash,
                    create_coin.amount,
                );

                let child_coin_id = child_coin.coin_id();
                let is_child_ephemeral = all_spent_coin_ids.contains(&child_coin_id);

                // If this is a singleton, we've already emitted payments for the odd singleton output, so we can skip odd coins
                if is_singleton && child_coin.amount % 2 == 1 {
                    continue;
                }

                let parsed_memos = parse_memos(allocator, create_coin, false);
                let is_child_ours = parsed_memos.p2_puzzle_hash == our_p2_puzzle_hash;

                total_output += child_coin.amount;

                if is_parent_ours && !is_child_ephemeral {
                    our_output += child_coin.amount;
                }

                // Skip ephemeral coins
                if our_spent_coin_ids.contains(&child_coin_id) {
                    continue;
                }

                if let Some(transfer_type) = calculate_transfer_type(
                    allocator,
                    TransferTypeContext {
                        puzzle_assertion_ids: &puzzle_assertion_ids,
                        notarized_payments: &notarized_payments,
                        create_coin: &create_coin,
                        p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                        full_puzzle_hash: coin_spend.coin.puzzle_hash,
                        is_parent_ours,
                        is_child_ours,
                    },
                ) {
                    payments.push(ParsedPayment {
                        transfer_type,
                        asset_id: None,
                        hidden_puzzle_hash: None,
                        p2_puzzle_hash: parsed_memos.p2_puzzle_hash,
                        coin: child_coin,
                        clawback: parsed_memos.clawback,
                        memos: parsed_memos.memos,
                    });
                }
            }
        }

        Ok(Self {
            new_custody_hash,
            payments,
            nfts,
            drop_coins,
            fee_paid: our_input.saturating_sub(our_output),
            total_fee: total_input.saturating_sub(total_output),
        })
    }
}

fn vault_p2_puzzle_hash(launcher_id: Bytes32) -> Bytes32 {
    mips_puzzle_hash(
        0,
        vec![],
        SingletonMember::new(launcher_id).curry_tree_hash(),
        true,
    )
    .into()
}

#[derive(Debug, Clone)]
struct ParsedDelegatedSpend {
    new_custody_hash: Option<TreeHash>,
    our_spent_coin_ids: HashSet<Bytes32>,
    puzzle_assertion_ids: HashSet<Bytes32>,
    drop_coins: Vec<DropCoin>,
}

fn parse_delegated_spend(
    allocator: &mut Allocator,
    delegated_spend: Spend,
    spent_coin_ids: &HashSet<Bytes32>,
) -> Result<ParsedDelegatedSpend, DriverError> {
    let vault_output = run_puzzle(allocator, delegated_spend.puzzle, delegated_spend.solution)?;
    let vault_conditions = Vec::<Condition>::from_clvm(allocator, vault_output)?;

    let mut new_custody_hash = None;
    let mut our_spent_coin_ids = HashSet::new();
    let mut puzzle_assertion_ids = HashSet::new();
    let mut drop_coins = Vec::new();

    for condition in vault_conditions {
        match condition {
            Condition::CreateCoin(condition) => {
                if condition.amount % 2 == 1 {
                    // The vault singleton is being recreated
                    new_custody_hash = Some(condition.puzzle_hash.into());
                } else {
                    drop_coins.push(DropCoin {
                        puzzle_hash: condition.puzzle_hash,
                        amount: condition.amount,
                    });
                }
            }
            Condition::SendMessage(condition) => {
                // If the receiver isn't a specific coin id, we prevent signing
                let sender = MessageFlags::decode(condition.mode, MessageSide::Sender);
                let receiver = MessageFlags::decode(condition.mode, MessageSide::Receiver);

                if sender != MessageFlags::PUZZLE
                    || receiver != MessageFlags::COIN
                    || condition.data.len() != 1
                {
                    // TODO: Handle vault of vaults
                    return Err(DriverError::MissingSpend);
                }

                // If we're authorizing a spend, it must be in the revealed coin spends
                // We can't authorize the same spend twice
                let coin_id = Bytes32::from_clvm(allocator, condition.data[0])?;

                if !spent_coin_ids.contains(&coin_id) || !our_spent_coin_ids.insert(coin_id) {
                    return Err(DriverError::MissingSpend);
                }
            }
            Condition::AssertPuzzleAnnouncement(condition) => {
                puzzle_assertion_ids.insert(condition.announcement_id);
            }
            _ => {}
        }
    }

    Ok(ParsedDelegatedSpend {
        new_custody_hash,
        our_spent_coin_ids,
        puzzle_assertion_ids,
        drop_coins,
    })
}

#[derive(Debug, Clone)]
struct ParsedConditions {
    puzzle_assertion_ids: HashSet<Bytes32>,
    all_created_coin_ids: HashSet<Bytes32>,
}

fn parse_our_conditions(
    allocator: &mut Allocator,
    coin_spends: &[CoinSpend],
    our_coin_ids: &HashSet<Bytes32>,
    mut puzzle_assertion_ids: HashSet<Bytes32>,
) -> Result<ParsedConditions, DriverError> {
    let mut all_created_coin_ids = HashSet::new();

    for coin_spend in coin_spends {
        let coin_id = coin_spend.coin.coin_id();
        let puzzle = coin_spend.puzzle_reveal.to_clvm(allocator)?;
        let solution = coin_spend.solution.to_clvm(allocator)?;
        let output = run_puzzle(allocator, puzzle, solution)?;
        let conditions = Vec::<Condition>::from_clvm(allocator, output)?;

        for condition in conditions {
            match condition {
                Condition::AssertPuzzleAnnouncement(condition) => {
                    if our_coin_ids.contains(&coin_id) {
                        puzzle_assertion_ids.insert(condition.announcement_id);
                    }
                }
                Condition::CreateCoin(condition) => {
                    all_created_coin_ids.insert(
                        Coin::new(coin_id, condition.puzzle_hash, condition.amount).coin_id(),
                    );
                }
                _ => {}
            }
        }
    }

    Ok(ParsedConditions {
        puzzle_assertion_ids,
        all_created_coin_ids,
    })
}

/// The idea here is to order coin spends by the order in which they were created.
/// This simplifies keeping track of the lineage and latest updates of singletons such as NFTs.
/// Coins which weren't created in this transaction are first, followed by coins which they created, and so on.
fn reorder_coin_spends(mut coin_spends: Vec<CoinSpend>) -> Vec<CoinSpend> {
    let mut reordered_coin_spends = Vec::new();
    let mut remaining_spent_coin_ids: HashSet<Bytes32> =
        coin_spends.iter().map(|cs| cs.coin.coin_id()).collect();

    while !coin_spends.is_empty() {
        coin_spends.retain(|cs| {
            if remaining_spent_coin_ids.contains(&cs.coin.parent_coin_info) {
                true
            } else {
                remaining_spent_coin_ids.remove(&cs.coin.coin_id());
                reordered_coin_spends.push(cs.clone());
                false
            }
        });
    }

    reordered_coin_spends
}

#[derive(Debug, Clone)]
struct ParsedMemos {
    p2_puzzle_hash: Bytes32,
    clawback: Option<ClawbackV2>,
    memos: Vec<String>,
}

fn parse_memos(
    allocator: &Allocator,
    p2_create_coin: CreateCoin<NodePtr>,
    requires_hint: bool,
) -> ParsedMemos {
    // If there is no memo list, there's nothing to parse and we can assume there's no clawback
    let Memos::Some(memos) = p2_create_coin.memos else {
        return ParsedMemos {
            p2_puzzle_hash: p2_create_coin.puzzle_hash,
            clawback: None,
            memos: Vec::new(),
        };
    };

    // If there is both a hint and a valid clawback memo that correctly calculates the puzzle hash,
    // then we can parse the clawback and return the rest of the memos, if they are bytes.
    if let Ok((hint, (clawback_memo, rest))) =
        <(Bytes32, (NodePtr, NodePtr))>::from_clvm(allocator, memos)
        && let Some(clawback) = ClawbackV2::from_memo(
            allocator,
            clawback_memo,
            hint,
            p2_create_coin.amount,
            requires_hint,
            p2_create_coin.puzzle_hash,
        )
    {
        return ParsedMemos {
            p2_puzzle_hash: clawback.receiver_puzzle_hash,
            clawback: Some(clawback),
            memos: parse_memo_list(allocator, rest),
        };
    }

    // If we're parsing a CAT output, we can remove the hint from the memos if applicable.
    if requires_hint && let Ok((_hint, rest)) = <(Bytes32, NodePtr)>::from_clvm(allocator, memos) {
        return ParsedMemos {
            p2_puzzle_hash: p2_create_coin.puzzle_hash,
            clawback: None,
            memos: parse_memo_list(allocator, rest),
        };
    }

    // Otherwise, we assume there's no clawback and return the memos as is, if they are bytes.
    ParsedMemos {
        p2_puzzle_hash: p2_create_coin.puzzle_hash,
        clawback: None,
        memos: parse_memo_list(allocator, memos),
    }
}

fn parse_memo_list(allocator: &Allocator, memos: NodePtr) -> Vec<String> {
    let memos = Vec::<NodePtr>::from_clvm(allocator, memos).unwrap_or_default();

    let mut result = Vec::new();

    for memo in memos {
        let Ok(memo) = String::from_clvm(allocator, memo) else {
            continue;
        };
        result.push(memo);
    }

    result
}

#[derive(Debug, Clone, Copy)]
struct TransferTypeContext<'a> {
    puzzle_assertion_ids: &'a HashSet<Bytes32>,
    notarized_payments: &'a Vec<NotarizedPayment>,
    create_coin: &'a CreateCoin<NodePtr>,
    p2_puzzle_hash: Bytes32,
    full_puzzle_hash: Bytes32,
    is_parent_ours: bool,
    is_child_ours: bool,
}

fn calculate_transfer_type(
    allocator: &Allocator,
    context: TransferTypeContext<'_>,
) -> Option<TransferType> {
    let TransferTypeContext {
        puzzle_assertion_ids,
        notarized_payments,
        create_coin,
        p2_puzzle_hash,
        full_puzzle_hash,
        is_parent_ours,
        is_child_ours,
    } = context;

    if is_parent_ours && !is_child_ours {
        // We know that the coin spend is authorized by the delegated spend, and we don't own the child coin
        // Therefore, it's a valid sent payment
        if p2_puzzle_hash == BURN_PUZZLE_HASH {
            Some(TransferType::Burned)
        } else if p2_puzzle_hash == SETTLEMENT_PAYMENT_HASH.into() {
            Some(TransferType::Offered)
        } else {
            Some(TransferType::Sent)
        }
    } else if !is_parent_ours
        && is_child_ours
        && let Some(notarized_payment) = notarized_payments.iter().find(|np| {
            np.payments
                .iter()
                .any(|p| p.puzzle_hash == create_coin.puzzle_hash && p.amount == create_coin.amount)
        })
    {
        let notarized_payment_hash = tree_hash_notarized_payment(allocator, notarized_payment);
        let settlement_announcement_id = announcement_id(full_puzzle_hash, notarized_payment_hash);

        // Since the parent spend isn't verifiable, we need to know that we've asserted the payment
        // Otherwise, it may as well not exist since we could be being lied to by the coin spend provider
        if puzzle_assertion_ids.contains(&settlement_announcement_id) {
            Some(TransferType::Received)
        } else {
            None
        }
    } else if is_parent_ours && is_child_ours {
        // For non-fungible assets that we sent to ourself, we can assume they are updated
        Some(TransferType::Updated)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use anyhow::Result;
    use chia_puzzles::SINGLETON_LAUNCHER_HASH;
    use chia_sdk_test::Simulator;
    use chia_sdk_types::Conditions;
    use rstest::rstest;

    use crate::{Action, Id, SpendContext, Spends, TestVault};

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum AssetKind {
        Xch,
        Cat,
        RevocableCat,
    }

    #[rstest]
    fn test_clear_signing_sent(
        #[values(AssetKind::Xch, AssetKind::Cat, AssetKind::RevocableCat)] asset_kind: AssetKind,
        #[values(0, 100)] fee: u64,
    ) -> Result<()> {
        let mut sim = Simulator::new();
        let mut ctx = SpendContext::new();

        let alice = TestVault::mint(&mut sim, &mut ctx, 1000 + fee)?;
        let bob = TestVault::mint(&mut sim, &mut ctx, 0)?;

        let (id, asset_id) = if let AssetKind::Cat | AssetKind::RevocableCat = asset_kind {
            let result = alice.spend(
                &mut sim,
                &mut ctx,
                &[Action::single_issue_cat(
                    if let AssetKind::RevocableCat = asset_kind {
                        Some(Bytes32::default())
                    } else {
                        None
                    },
                    1000,
                )],
            )?;

            let asset_id = result.outputs.cats[0][0].info.asset_id;
            let id = Id::Existing(asset_id);
            (id, Some(asset_id))
        } else {
            (Id::Xch, None)
        };

        let result = alice.spend(
            &mut sim,
            &mut ctx,
            &[
                Action::send(id, bob.puzzle_hash(), 1000, Memos::None),
                Action::fee(fee),
            ],
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: alice.launcher_id(),
            custody_hash: alice.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;
        assert_eq!(tx.new_custody_hash, Some(alice.custody_hash()));
        assert_eq!(tx.payments.len(), 1);
        assert_eq!(tx.fee_paid, fee);
        assert_eq!(tx.total_fee, fee);

        let payment = &tx.payments[0];
        assert_eq!(payment.transfer_type, TransferType::Sent);
        assert_eq!(payment.asset_id, asset_id);
        assert_eq!(payment.p2_puzzle_hash, bob.puzzle_hash());
        assert_eq!(payment.coin.amount, 1000);

        Ok(())
    }

    #[rstest]
    fn test_clear_signing_received(
        #[values(AssetKind::Xch, AssetKind::Cat, AssetKind::RevocableCat)] asset_kind: AssetKind,
        #[values(true, false)] disable_settlement_assertions: bool,
        #[values(0, 100)] alice_fee: u64,
        #[values(0, 100)] bob_fee: u64,
    ) -> Result<()> {
        let mut sim = Simulator::new();
        let mut ctx = SpendContext::new();

        let alice = TestVault::mint(&mut sim, &mut ctx, 1000 + alice_fee)?;
        let bob = TestVault::mint(&mut sim, &mut ctx, bob_fee)?;

        let (id, asset_id) = if let AssetKind::Cat | AssetKind::RevocableCat = asset_kind {
            let result = alice.spend(
                &mut sim,
                &mut ctx,
                &[Action::single_issue_cat(
                    if let AssetKind::RevocableCat = asset_kind {
                        Some(Bytes32::default())
                    } else {
                        None
                    },
                    1000,
                )],
            )?;

            let asset_id = result.outputs.cats[0][0].info.asset_id;
            let id = Id::Existing(asset_id);
            (id, Some(asset_id))
        } else {
            (Id::Xch, None)
        };

        let result = alice.spend(
            &mut sim,
            &mut ctx,
            &[
                Action::send(id, SETTLEMENT_PAYMENT_HASH.into(), 1000, Memos::None),
                Action::fee(alice_fee),
            ],
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: bob.launcher_id(),
            custody_hash: bob.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;

        assert_eq!(tx.payments.len(), 1);
        assert_eq!(tx.fee_paid, alice_fee);
        assert_eq!(tx.total_fee, alice_fee);

        let payment = &tx.payments[0];
        assert_eq!(payment.transfer_type, TransferType::Offered);
        assert_eq!(payment.asset_id, asset_id);
        assert_eq!(payment.p2_puzzle_hash, SETTLEMENT_PAYMENT_HASH.into());
        assert_eq!(payment.coin.amount, 1000);

        let mut spends = Spends::new(bob.puzzle_hash());
        if id == Id::Xch {
            spends.add(result.outputs.xch[0]);
        } else {
            spends.add(result.outputs.cats[&id][0]);
        }
        spends.conditions.disable_settlement_assertions = disable_settlement_assertions;

        let result = bob.custom_spend(
            &mut sim,
            &mut ctx,
            &[Action::fee(bob_fee)],
            spends,
            Conditions::new(),
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: bob.launcher_id(),
            custody_hash: bob.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;

        if disable_settlement_assertions {
            assert_eq!(tx.payments.len(), 0);
            assert_eq!(tx.fee_paid, bob_fee);
            assert_eq!(tx.total_fee, bob_fee);
        } else {
            assert_eq!(tx.payments.len(), 1);
            assert_eq!(tx.fee_paid, bob_fee);
            assert_eq!(tx.total_fee, bob_fee);

            let payment = &tx.payments[0];
            assert_eq!(payment.transfer_type, TransferType::Received);
            assert_eq!(payment.asset_id, asset_id);
            assert_eq!(payment.p2_puzzle_hash, bob.puzzle_hash());
            assert_eq!(payment.coin.amount, 1000);
        }

        Ok(())
    }

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

        let alice = TestVault::mint(&mut sim, &mut ctx, 1)?;
        let bob = TestVault::mint(&mut sim, &mut ctx, 0)?;

        let result = alice.spend(&mut sim, &mut ctx, &[Action::mint_empty_nft()])?;

        let reveal = VaultSpendReveal {
            launcher_id: alice.launcher_id(),
            custody_hash: alice.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;

        assert_eq!(tx.payments.len(), 1);
        assert_eq!(tx.nfts.len(), 1);
        assert_eq!(tx.fee_paid, 0);
        assert_eq!(tx.total_fee, 0);

        // Even though this is for an NFT mint, the launcher is tracked as a sent payment
        let payment = &tx.payments[0];
        assert_eq!(payment.transfer_type, TransferType::Sent);
        assert_eq!(payment.p2_puzzle_hash, SINGLETON_LAUNCHER_HASH.into());
        assert_eq!(payment.coin.amount, 0);

        // The NFT should be included
        let nft = &tx.nfts[0];
        assert_eq!(nft.transfer_type, TransferType::Updated);
        assert_eq!(nft.p2_puzzle_hash, alice.puzzle_hash());
        assert!(!nft.includes_unverifiable_updates);

        // Transfer the NFT to Bob
        let nft_id = Id::Existing(nft.launcher_id);
        let bob_hint = ctx.hint(bob.puzzle_hash())?;

        let result = alice.spend(
            &mut sim,
            &mut ctx,
            &[Action::send(nft_id, bob.puzzle_hash(), 1, bob_hint)],
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: alice.launcher_id(),
            custody_hash: alice.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;

        assert_eq!(tx.payments.len(), 0);
        assert_eq!(tx.nfts.len(), 1);
        assert_eq!(tx.fee_paid, 0);
        assert_eq!(tx.total_fee, 0);

        let nft = &tx.nfts[0];
        assert_eq!(nft.transfer_type, TransferType::Sent);
        assert_eq!(nft.p2_puzzle_hash, bob.puzzle_hash());
        assert!(!nft.includes_unverifiable_updates);

        Ok(())
    }

    #[rstest]
    fn test_clear_signing_split(
        #[values(AssetKind::Xch, AssetKind::Cat, AssetKind::RevocableCat)] asset_kind: AssetKind,
        #[values(0, 100)] fee: u64,
    ) -> Result<()> {
        let mut sim = Simulator::new();
        let mut ctx = SpendContext::new();

        let alice = TestVault::mint(&mut sim, &mut ctx, 1000 + fee)?;

        let (id, asset_id) = if let AssetKind::Cat | AssetKind::RevocableCat = asset_kind {
            let result = alice.spend(
                &mut sim,
                &mut ctx,
                &[Action::single_issue_cat(
                    if let AssetKind::RevocableCat = asset_kind {
                        Some(Bytes32::default())
                    } else {
                        None
                    },
                    1000,
                )],
            )?;

            let asset_id = result.outputs.cats[0][0].info.asset_id;
            let id = Id::Existing(asset_id);
            (id, Some(asset_id))
        } else {
            (Id::Xch, None)
        };

        let result = alice.spend(
            &mut sim,
            &mut ctx,
            &[
                Action::send(id, alice.puzzle_hash(), 250, Memos::None),
                Action::send(id, alice.puzzle_hash(), 250, Memos::None),
                Action::send(id, alice.puzzle_hash(), 250, Memos::None),
                Action::send(id, alice.puzzle_hash(), 250, Memos::None),
                Action::fee(fee),
            ],
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: alice.launcher_id(),
            custody_hash: alice.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;
        assert_eq!(tx.new_custody_hash, Some(alice.custody_hash()));
        assert_eq!(tx.payments.len(), 4);
        assert_eq!(tx.fee_paid, fee);
        assert_eq!(tx.total_fee, fee);

        for payment in &tx.payments {
            assert_eq!(payment.transfer_type, TransferType::Updated);
            assert_eq!(payment.asset_id, asset_id);
            assert_eq!(payment.p2_puzzle_hash, alice.puzzle_hash());
            assert_eq!(payment.coin.amount, 250);
        }

        let result = alice.spend(
            &mut sim,
            &mut ctx,
            &[Action::send(id, alice.puzzle_hash(), 1000, Memos::None)],
        )?;

        let reveal = VaultSpendReveal {
            launcher_id: alice.launcher_id(),
            custody_hash: alice.custody_hash(),
            delegated_spend: result.delegated_spend,
        };

        let tx = VaultTransaction::parse(&mut ctx, &reveal, result.coin_spends)?;
        assert_eq!(tx.new_custody_hash, Some(alice.custody_hash()));
        assert_eq!(tx.payments.len(), 1);
        assert_eq!(tx.fee_paid, 0);
        assert_eq!(tx.total_fee, 0);

        let payment = &tx.payments[0];
        assert_eq!(payment.transfer_type, TransferType::Updated);
        assert_eq!(payment.asset_id, asset_id);
        assert_eq!(payment.p2_puzzle_hash, alice.puzzle_hash());
        assert_eq!(payment.coin.amount, 1000);

        Ok(())
    }
}