dig-chainsource-interface 0.3.1

The DIG Network canonical ChainSource provider interface: the single pure trait + query types every Chia chain-source provider implements and every consumer depends on. Reads-only, no I/O, no keys, no network — chia-* deps only.
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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
//! Adversarial tests for the canonical singleton lineage walk (needs
//! `--features lineage-walk,testing`).
//!
//! The authentic cases run against REAL singleton spends produced by the in-process Chia simulator —
//! a genuine launcher, its eve, a recreation, and a melt — so the walk is exercised on chain data it
//! did not invent. The fail-closed cases use [`MockChainSource`], which can lie in ways a simulator
//! cannot.
//!
//! The load-bearing test is [`a_lookalike_coin_wearing_the_singleton_puzzle_hash_is_not_a_member`]:
//! a coin that genuinely exists on chain, genuinely wears the victim singleton's outer puzzle hash,
//! and genuinely has the same amount — but was created by an ordinary spend rather than by a
//! singleton recreation. Nothing about the coin itself distinguishes it from the real tip; only the
//! derivation does. A walk that recognised coins instead of deriving them would admit it.

#![cfg(all(feature = "lineage-walk", feature = "testing"))]

use std::cell::Cell;

use anyhow::Result;
use chia_bls::{PublicKey, SecretKey};
use chia_protocol::{Bytes32, Coin, CoinSpend, Program};
use chia_puzzle_types::singleton::{SingletonArgs, SingletonSolution};
use chia_puzzle_types::{EveProof, LineageProof, Memos, Proof};
use chia_sdk_driver::{
    Launcher, Layer, SingletonLayer, Spend, SpendContext, SpendWithConditions, StandardLayer,
};
use chia_sdk_test::Simulator;
use chia_sdk_types::{Condition, Conditions};
use clvm_utils::{tree_hash, TreeHash};
use clvmr::serde::{node_from_bytes, node_to_bytes, node_to_bytes_backrefs};
use clvmr::{Allocator, NodePtr};
use dig_chainsource_interface::{
    walk_singleton_lineage, walk_singleton_lineage_bounded, ChainSource, ChainSourceError,
    CoinRecord, LineageWalkError, MockChainSource, SingletonLineage,
};

// ---------------------------------------------------------------------------------------------
// A chain view backed entirely by the real simulator.
// ---------------------------------------------------------------------------------------------

/// An honest [`ChainSource`] over the in-process simulator: every read is answered from real
/// simulated chain state, so nothing in these fixtures is hand-forged.
struct SimSource<'a> {
    sim: &'a Simulator,
    /// How many times the walk consulted [`ChainSource::coin_records_by_parent`]. A sound walk
    /// DERIVES its successor from the parent's own spend, so this must stay zero: any reliance on
    /// the child list hands a source the power to steer the lineage (see
    /// [`a_genuine_sibling_of_the_successor_is_not_selected_as_the_successor`]).
    children_reads: Cell<usize>,
    /// A coin whose SPEND this source withholds while still reporting the coin as spent — an
    /// otherwise honest source that has simply lost one spend (a pruned node, a partial index).
    withheld_spend: Option<Bytes32>,
    /// A coin whose RECORD this source withholds, so a derived successor cannot be bound to real
    /// chain state. Drives [`require_coin_exists`]'s guard.
    withheld_record: Option<Bytes32>,
    /// Re-serializes every puzzle reveal in the CLVM **back-reference** form — the compressed
    /// encoding full nodes accept and block generators emit. The chain data is byte-for-byte
    /// equivalent; only its serialization differs.
    backref_reveals: bool,
}

impl SimSource<'_> {
    /// Applies [`SimSource::backref_reveals`] to a spend on its way out of the source.
    fn serialized_as_configured(&self, spend: CoinSpend) -> CoinSpend {
        if !self.backref_reveals {
            return spend;
        }
        CoinSpend::new(
            spend.coin,
            backref_serialized(&spend.puzzle_reveal),
            spend.solution,
        )
    }
}

/// Re-encodes `program` using CLVM back-references, preserving the tree it denotes exactly.
fn backref_serialized(program: &Program) -> Program {
    let mut allocator = Allocator::new();
    let node = node_from_bytes(&mut allocator, program.as_ref()).expect("the program deserializes");
    Program::from(node_to_bytes_backrefs(&allocator, node).expect("the program re-serializes"))
}

impl ChainSource for SimSource<'_> {
    type Error = ChainSourceError;

    fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
        if self.withheld_record == Some(coin_id) {
            return Ok(None);
        }
        Ok(self.sim.coin_state(coin_id).map(CoinRecord::from))
    }

    fn coin_records_by_puzzle_hash(
        &self,
        puzzle_hash: Bytes32,
        include_spent: bool,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        Ok(self
            .sim
            .unspent_coins(puzzle_hash, false)
            .into_iter()
            .filter_map(|coin| self.sim.coin_state(coin.coin_id()))
            .map(CoinRecord::from)
            .filter(|record| include_spent || !record.is_spent())
            .collect())
    }

    fn coin_records_by_parent(
        &self,
        parent_coin_id: Bytes32,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        self.children_reads.set(self.children_reads.get() + 1);
        Ok(self
            .sim
            .children(parent_coin_id)
            .into_iter()
            .map(CoinRecord::from)
            .collect())
    }

    fn coin_spend(&self, coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
        if self.withheld_spend == Some(coin_id) {
            return Ok(None);
        }
        Ok(self
            .sim
            .coin_spend(coin_id)
            .map(|spend| self.serialized_as_configured(spend)))
    }

    fn resolve_singleton_lineage(
        &self,
        launcher_id: Bytes32,
    ) -> Result<Option<SingletonLineage>, Self::Error> {
        // The helper under test is the whole point; delegating here proves the one-line body works.
        dig_chainsource_interface::resolve_singleton_lineage_via_walk(self, launcher_id)
    }

    fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
        Ok(None)
    }

    fn block_timestamp(&self, _height: u32) -> Result<Option<u64>, Self::Error> {
        Ok(None)
    }
}

// ---------------------------------------------------------------------------------------------
// Fixture construction: a real singleton, advanced by real spends.
// ---------------------------------------------------------------------------------------------

/// A live singleton in the simulator, tracked as the test advances it.
struct Singleton {
    launcher_id: Bytes32,
    /// Launcher -> ... -> tip, in walk order.
    trail: Vec<Coin>,
    proof: Proof,
    inner_puzzle_hash: Bytes32,
    pk: PublicKey,
    sk: SecretKey,
}

impl Singleton {
    fn tip(&self) -> Coin {
        *self.trail.last().expect("a launched singleton has a tip")
    }

    /// The full (singleton-wrapped) puzzle hash the singleton's coins wear.
    fn outer_puzzle_hash(&self) -> Bytes32 {
        SingletonArgs::curry_tree_hash(self.launcher_id, TreeHash::from(self.inner_puzzle_hash))
            .into()
    }
}

/// Launches a real singleton with a standard p2 inner puzzle and settles it, returning the launcher
/// coin, the eve coin, and everything needed to advance it.
fn launch(sim: &mut Simulator, ctx: &mut SpendContext) -> Result<Singleton> {
    launch_with_amount(sim, ctx, 1)
}

/// [`launch`] with a chosen singleton amount, so a spend can both recreate the singleton (an odd
/// amount) AND pay an even-amount decoy out of the same coin.
fn launch_with_amount(
    sim: &mut Simulator,
    ctx: &mut SpendContext,
    amount: u64,
) -> Result<Singleton> {
    let owner = sim.bls(amount);
    let launcher = Launcher::new(owner.coin.coin_id(), amount);
    let launcher_coin = launcher.coin();
    let (conditions, eve) = launcher.spend(ctx, owner.puzzle_hash, ())?;
    StandardLayer::new(owner.pk).spend(ctx, owner.coin, conditions)?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&owner.sk))?;

    Ok(Singleton {
        launcher_id: launcher_coin.coin_id(),
        trail: vec![launcher_coin, eve],
        proof: Proof::Eve(EveProof {
            parent_parent_coin_info: launcher_coin.parent_coin_info,
            parent_amount: launcher_coin.amount,
        }),
        inner_puzzle_hash: owner.puzzle_hash,
        pk: owner.pk,
        sk: owner.sk,
    })
}

/// Advances the singleton by one genuine recreation spend, appending the new tip to the trail.
fn advance(sim: &mut Simulator, ctx: &mut SpendContext, singleton: &mut Singleton) -> Result<()> {
    advance_paying(sim, ctx, singleton, singleton.tip().amount, None)
}

/// Advances the singleton, recreating it with `recreate_amount` and optionally paying an extra
/// even-amount coin to `decoy` out of the SAME spend — so the recreation gets a genuine sibling.
fn advance_paying(
    sim: &mut Simulator,
    ctx: &mut SpendContext,
    singleton: &mut Singleton,
    recreate_amount: u64,
    decoy: Option<(Bytes32, u64)>,
) -> Result<()> {
    let tip = singleton.tip();
    let sk = singleton.sk.clone();

    let mut conditions =
        Conditions::new().create_coin(singleton.inner_puzzle_hash, recreate_amount, Memos::None);
    if let Some((puzzle_hash, amount)) = decoy {
        conditions = conditions.create_coin(puzzle_hash, amount, Memos::None);
    }
    let inner = StandardLayer::new(singleton.pk).spend_with_conditions(ctx, conditions)?;
    let layer = SingletonLayer::new(singleton.launcher_id, StandardLayer::new(singleton.pk));
    let solution = SingletonSolution {
        lineage_proof: singleton.proof,
        amount: tip.amount,
        inner_solution: inner.solution,
    };
    let puzzle = layer.construct_puzzle(ctx)?;
    let solution = ctx.alloc(&solution)?;
    ctx.spend(tip, Spend::new(puzzle, solution))?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&sk))?;

    singleton.proof = Proof::Lineage(LineageProof {
        parent_parent_coin_info: tip.parent_coin_info,
        parent_inner_puzzle_hash: singleton.inner_puzzle_hash,
        parent_amount: tip.amount,
    });
    singleton.trail.push(Coin::new(
        tip.coin_id(),
        singleton.outer_puzzle_hash(),
        recreate_amount,
    ));
    Ok(())
}

fn source(sim: &Simulator) -> SimSource<'_> {
    SimSource {
        sim,
        children_reads: Cell::new(0),
        withheld_spend: None,
        withheld_record: None,
        backref_reveals: false,
    }
}

// ---------------------------------------------------------------------------------------------
// The authentic walk.
// ---------------------------------------------------------------------------------------------

#[test]
fn walk_returns_every_coin_from_the_launcher_to_the_tip() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;
    advance(&mut sim, ctx, &mut singleton)?;

    let src = source(&sim);
    let lineage = walk_singleton_lineage(&src, singleton.launcher_id)?
        .expect("a live singleton has a lineage");

    assert_eq!(lineage.tip(), singleton.tip().coin_id());
    assert_eq!(lineage.len(), singleton.trail.len());
    for coin in &singleton.trail {
        assert!(
            lineage.contains(coin.coin_id()),
            "genuine lineage coin {} is missing",
            coin.coin_id()
        );
    }
    Ok(())
}

/// The SAME honest chain, with every puzzle reveal serialized in the CLVM **back-reference** form.
///
/// Back-references are the compressed encoding full nodes accept and block generators emit: a
/// repeated subtree is written once and pointed at thereafter. A curried singleton puzzle repeats
/// subtrees heavily, so this is not an exotic case — it is what a real singleton's reveal looks
/// like whenever it travels compressed.
///
/// `chia_protocol::Program`'s `ToClvm` deserializes with the NON-backref reader, so a walk that
/// allocates a reveal that way cannot read one, and reports `Malformed` — "the chain data is
/// untrustworthy" — about a genuine singleton served by an honest source. `Program::run` in that
/// very same file uses the backref reader, which is the shape the walk must match.
#[test]
fn a_backref_serialized_puzzle_reveal_resolves_exactly_as_the_plain_one() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;
    advance(&mut sim, ctx, &mut singleton)?;

    // The fixture is only distinguishing if some reveal genuinely compresses — a chain whose
    // backref encoding happened to equal its plain one would re-run the honest test and prove
    // nothing. (The eve's curried singleton reveal is the one that does.)
    let eve_reveal = sim
        .coin_spend(singleton.trail[1].coin_id())
        .expect("the eve is spent")
        .puzzle_reveal;
    let compressed = backref_serialized(&eve_reveal);
    assert_ne!(
        compressed.as_ref(),
        eve_reveal.as_ref(),
        "the reveal must actually use back-references for this fixture to bite"
    );
    let mut allocator = Allocator::new();
    assert!(
        node_from_bytes(&mut allocator, compressed.as_ref()).is_err(),
        "the non-backref reader must be unable to read the compressed reveal"
    );

    let mut src = source(&sim);
    src.backref_reveals = true;
    let lineage = walk_singleton_lineage(&src, singleton.launcher_id)?
        .expect("a compressed reveal is still a genuine singleton");

    assert_eq!(lineage.tip(), singleton.tip().coin_id());
    assert_eq!(lineage.len(), singleton.trail.len());
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// THE ADVERSARIAL TEST.
// ---------------------------------------------------------------------------------------------

/// A coin that exists on chain, wears the victim singleton's exact outer puzzle hash, and carries
/// the same amount — but was created by an ordinary payment, not by a singleton recreation.
///
/// Nothing observable about the coin distinguishes it from the genuine tip, so this is precisely the
/// fixture a walk that RECOGNISES coins (by puzzle hash, by curried launcher id, or by picking a
/// plausible child) cannot survive. It must be neither a member nor the tip.
#[test]
fn a_lookalike_coin_wearing_the_singleton_puzzle_hash_is_not_a_member() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;

    // An unrelated party pays 1 mojo to the victim singleton's outer puzzle hash.
    let attacker = sim.bls(1);
    let spoofed_puzzle_hash = singleton.outer_puzzle_hash();
    StandardLayer::new(attacker.pk).spend(
        ctx,
        attacker.coin,
        Conditions::new().create_coin(spoofed_puzzle_hash, 1, Memos::None),
    )?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&attacker.sk))?;
    let spoof = Coin::new(attacker.coin.coin_id(), spoofed_puzzle_hash, 1);

    // The spoof really is on chain and really does wear the singleton's puzzle hash.
    assert!(sim.coin_state(spoof.coin_id()).is_some());
    assert_eq!(spoof.puzzle_hash, singleton.tip().puzzle_hash);
    assert_ne!(spoof.coin_id(), singleton.tip().coin_id());

    let src = source(&sim);
    let lineage = walk_singleton_lineage(&src, singleton.launcher_id)?.expect("live singleton");

    assert!(
        !lineage.contains(spoof.coin_id()),
        "a look-alike coin with no genuine recreation parent-spend was admitted"
    );
    assert_eq!(lineage.tip(), singleton.tip().coin_id());
    Ok(())
}

/// The walk must not be steerable by a look-alike that is a GENUINE SIBLING of the real successor
/// — the nearest wrong implementation picks the successor out of
/// [`ChainSource::coin_records_by_parent`].
///
/// The singleton spend here recreates itself (odd amount 3) and, out of the SAME coin, pays a decoy
/// (even amount 2) wearing the successor's EXACT full puzzle hash. So the parent has two children
/// with identical puzzle hashes, and a child-selecting walk has nothing to choose between them. A
/// derivation has: only one of the two is the coin the parent's own solution creates as its odd
/// continuation.
#[test]
fn a_genuine_sibling_of_the_successor_is_not_selected_as_the_successor() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch_with_amount(&mut sim, ctx, 5)?;

    let successor_puzzle_hash = singleton.outer_puzzle_hash();
    let eve = singleton.tip();
    advance_paying(
        &mut sim,
        ctx,
        &mut singleton,
        3,
        Some((successor_puzzle_hash, 2)),
    )?;
    let decoy = Coin::new(eve.coin_id(), successor_puzzle_hash, 2);

    // The fixture is only distinguishing if the decoy really is a sibling wearing the same hash.
    let src = source(&sim);
    let children = src.coin_records_by_parent(eve.coin_id())?;
    assert_eq!(children.len(), 2, "the successor must have a real sibling");
    assert!(children
        .iter()
        .all(|child| child.coin.puzzle_hash == successor_puzzle_hash));
    assert!(sim.coin_state(decoy.coin_id()).is_some());

    src.children_reads.set(0);
    let lineage = walk_singleton_lineage(&src, singleton.launcher_id)?.expect("live singleton");
    assert_eq!(lineage.tip(), singleton.tip().coin_id());
    assert!(
        !lineage.contains(decoy.coin_id()),
        "an even-amount sibling wearing the successor's puzzle hash was admitted"
    );
    // The outcome above is order-dependent for a child-selecting walk — it could pick the genuine
    // successor by luck. This is the assertion that is NOT: a sound walk never asks for the child
    // list at all, so no ordering, and no source, can steer it.
    assert_eq!(
        src.children_reads.get(),
        0,
        "the walk consulted the child list, so a source could choose its successor"
    );
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// Three-valued discipline: absence vs unreadable vs unsupported.
// ---------------------------------------------------------------------------------------------

#[test]
fn an_unknown_launcher_is_a_genuine_absence() -> Result<()> {
    let sim = Simulator::new();
    let src = source(&sim);
    assert_eq!(
        walk_singleton_lineage(&src, Bytes32::new([0x11; 32]))?,
        None
    );
    Ok(())
}

#[test]
fn a_coin_that_is_not_a_launcher_is_a_genuine_absence() -> Result<()> {
    let mut sim = Simulator::new();
    let ordinary = sim.bls(1);
    let src = source(&sim);
    assert_eq!(
        walk_singleton_lineage(&src, ordinary.coin.coin_id())?,
        None,
        "an ordinary coin's id names no singleton"
    );
    Ok(())
}

#[test]
fn a_transport_failure_is_never_reported_as_an_absent_lineage() {
    let source = MockChainSource::new().fail_with(ChainSourceError::Transport("socket".into()));
    let error = walk_singleton_lineage(&source, Bytes32::new([0x22; 32]))
        .expect_err("a read failure must not resolve");
    assert_eq!(
        error,
        LineageWalkError::Source(ChainSourceError::Transport("socket".into())),
        "the source's own error must survive the walk verbatim"
    );
}

#[test]
fn an_unsupported_read_stays_distinguishable_from_unreadable_and_from_absent() {
    let source = MockChainSource::new().fail_with(ChainSourceError::Unsupported("coin_record"));
    let projected: ChainSourceError = walk_singleton_lineage(&source, Bytes32::new([0x33; 32]))
        .expect_err("unsupported is not an absence")
        .into();
    assert_eq!(projected, ChainSourceError::Unsupported("coin_record"));
    assert_ne!(projected, ChainSourceError::Malformed("coin_record".into()));
}

/// Spends the singleton's tip with `melt`, a condition list that emits no singleton recreation.
fn melt_with(
    sim: &mut Simulator,
    ctx: &mut SpendContext,
    singleton: &Singleton,
    melt: Conditions,
) -> Result<()> {
    let tip = singleton.tip();
    let sk = singleton.sk.clone();
    let inner = StandardLayer::new(singleton.pk).spend_with_conditions(ctx, melt)?;
    let layer = SingletonLayer::new(singleton.launcher_id, StandardLayer::new(singleton.pk));
    let puzzle = layer.construct_puzzle(ctx)?;
    let solution = ctx.alloc(&SingletonSolution {
        lineage_proof: singleton.proof,
        amount: tip.amount,
        inner_solution: inner.solution,
    })?;
    ctx.spend(tip, Spend::new(puzzle, solution))?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&sk))?;
    Ok(())
}

/// A melt whose `CREATE_COIN` names a 32-byte puzzle hash alongside the `-113` marker: the top
/// layer turns that output into an ORDINARY coin, so the singleton emits no successor.
#[test]
fn a_melted_singleton_has_no_lineage() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let singleton = launch(&mut sim, ctx)?;

    let melt = ctx.alloc(&(51, (singleton.inner_puzzle_hash, (-113, ()))))?;
    melt_with(
        &mut sim,
        ctx,
        &singleton,
        Conditions::new().with(Condition::Other(melt)),
    )?;

    let src = source(&sim);
    assert_eq!(walk_singleton_lineage(&src, singleton.launcher_id)?, None);
    Ok(())
}

/// The melt the ECOSYSTEM actually emits: `Conditions::melt_singleton()`, whose `CREATE_COIN`
/// carries a **NIL** puzzle hash (`chia_sdk_types` declares `MeltSingleton { puzzle_hash: () }`).
///
/// This is the form `dig-did` and `chip35_dl_coin` produce, because they build spends with
/// standard chia-wallet-sdk tooling. A walk that decodes the puzzle hash before testing the melt
/// marker refuses it, and the melted singleton then reports "the chain data is inconsistent"
/// forever — a dead identity that can never be resolved as dead, with an honest source blamed.
/// The 32-byte fixture above cannot express this; that is precisely why both exist.
#[test]
fn a_singleton_melted_with_standard_tooling_has_no_lineage() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let singleton = launch(&mut sim, ctx)?;

    melt_with(
        &mut sim,
        ctx,
        &singleton,
        Conditions::new().melt_singleton(),
    )?;

    // The fixture is only distinguishing if the melt really carries a NIL puzzle hash: serialized,
    // `(51 () -113)` is `ff 33 ff 80 ff 81 8f 80`. A fixture that quietly emitted a 32-byte hash
    // would duplicate the test above and prove nothing.
    const CANONICAL_MELT: [u8; 8] = [0xff, 0x33, 0xff, 0x80, 0xff, 0x81, 0x8f, 0x80];
    let spend = sim
        .coin_spend(singleton.tip().coin_id())
        .expect("the melt spend is on chain");
    assert!(
        spend
            .solution
            .as_ref()
            .windows(CANONICAL_MELT.len())
            .any(|window| window == CANONICAL_MELT),
        "the standard melt must serialize its CREATE_COIN with a nil puzzle hash"
    );

    assert_eq!(
        walk_singleton_lineage(&source(&sim), singleton.launcher_id)?,
        None,
        "a singleton melted with standard tooling is a genuine absence, not a refusal"
    );
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// Bounds and lying sources.
// ---------------------------------------------------------------------------------------------

/// The bound must be a REFUSAL, not a truncation: a partial member set would answer `false` for
/// genuine members, which is a fail-open membership answer on a money path.
#[test]
fn exceeding_the_hop_bound_refuses_rather_than_truncating() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;
    advance(&mut sim, ctx, &mut singleton)?;

    let src = source(&sim);

    // The chain is launcher -> eve -> C2 -> C3, i.e. exactly THREE spends. One under the bound must
    // refuse rather than return the first three coins as if they were the whole lineage.
    assert_eq!(singleton.trail.len(), 4);
    let error = walk_singleton_lineage_bounded(&src, singleton.launcher_id, 2)
        .expect_err("an over-deep walk must not resolve");
    assert_eq!(error, LineageWalkError::TooDeep { limit: 2 });
    assert_eq!(
        ChainSourceError::from(error),
        ChainSourceError::LineageTooDeep { limit: 2 },
        "the over-deep refusal must stay distinguishable from every other failure"
    );

    // AT the bound it resolves — a limit pinned only from below could only confirm itself.
    let lineage = walk_singleton_lineage_bounded(&src, singleton.launcher_id, 3)?
        .expect("the walk completes at exactly the bound");
    assert_eq!(lineage.tip(), singleton.tip().coin_id());
    Ok(())
}

/// The spend a source serves must be the spend of the coin it was ASKED for.
///
/// The fixture deliberately hands over a spend that is otherwise beyond reproach: the reveal is the
/// genuine launcher puzzle, so it hashes correctly, and the solution mints an eve the source knows.
/// Every other guard is therefore satisfied, and only the coin-identity check stands between the
/// walk and a lineage assembled from another coin's history. A fixture whose reveal did not hash
/// correctly would be refused by the reveal check instead, and would pin nothing.
#[test]
fn a_spend_of_the_wrong_coin_fails_closed() {
    let launcher_ph = Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH);
    let asked_for = Coin::new(Bytes32::new([0x01; 32]), launcher_ph, 1);
    let other = Coin::new(Bytes32::new([0x02; 32]), launcher_ph, 1);
    let eve_puzzle_hash = Bytes32::new([0x0B; 32]);
    let eve = Coin::new(asked_for.coin_id(), eve_puzzle_hash, 1);

    let source = MockChainSource::new()
        .with_coin(asked_for.coin_id(), record(asked_for))
        .with_coin(eve.coin_id(), record(eve))
        .with_spend(
            asked_for.coin_id(),
            CoinSpend::new(
                other,
                launcher_reveal(),
                launcher_solution(eve_puzzle_hash, 1),
            ),
        );

    let error = walk_singleton_lineage(&source, asked_for.coin_id())
        .expect_err("a mismatched spend must fail closed");
    assert_eq!(
        error,
        LineageWalkError::Malformed(format!(
            "source returned a spend of coin {} when asked for {}",
            other.coin_id(),
            asked_for.coin_id()
        )),
        "the refusal must be the coin-identity check, not some other guard that also says Malformed"
    );

    // The control: the SAME spend, correctly attributed, resolves — so the refusal above is the
    // identity check biting rather than a fixture that could never have worked.
    let honest = MockChainSource::new()
        .with_coin(asked_for.coin_id(), record(asked_for))
        .with_coin(eve.coin_id(), record(eve))
        .with_spend(
            asked_for.coin_id(),
            CoinSpend::new(
                asked_for,
                launcher_reveal(),
                launcher_solution(eve_puzzle_hash, 1),
            ),
        );
    assert_eq!(
        walk_singleton_lineage(&honest, asked_for.coin_id())
            .expect("the honest launcher resolves")
            .expect("a launched singleton")
            .tip(),
        eve.coin_id()
    );
}

/// A SPENT coin that is not a launcher is still a genuine absence, and this is the only fixture
/// shape that can say so.
///
/// [`a_coin_that_is_not_a_launcher_is_a_genuine_absence`] uses an UNSPENT ordinary coin, so its
/// `Ok(None)` arrives whether the launcher puzzle-hash check exists or not: without the check the
/// walk simply finds no spend and returns the at-launcher `None`. Only a coin that IS spent — and
/// whose spend would otherwise mint a perfectly good eve — distinguishes the two, and answering
/// `Ok(Some(_))` for it would report an ordinary two-coin payment chain as a singleton lineage.
#[test]
fn a_spent_coin_that_is_not_a_launcher_is_still_a_genuine_absence() {
    // `(q . ((51 <eve_ph> 1)))` — a puzzle that mints one odd-amount child for any solution.
    let eve_puzzle_hash = Bytes32::new([0x0A; 32]);
    let reveal = quoting_puzzle(&vec![(51, (eve_puzzle_hash, (1, ())))]);
    let ordinary = Coin::new(Bytes32::new([0x09; 32]), tree_hash_of(&reveal), 1);
    let eve = Coin::new(ordinary.coin_id(), eve_puzzle_hash, 1);

    // The fixture only distinguishes anything if the coin genuinely is not a launcher.
    assert_ne!(
        ordinary.puzzle_hash,
        Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH)
    );

    let source = MockChainSource::new()
        .with_coin(ordinary.coin_id(), spent_record(ordinary, 7))
        .with_coin(eve.coin_id(), record(eve))
        .with_spend(
            ordinary.coin_id(),
            CoinSpend::new(ordinary, reveal, Program::from(vec![0x80])),
        );

    assert_eq!(
        walk_singleton_lineage(&source, ordinary.coin_id()),
        Ok(None),
        "an ordinary spent coin names no singleton, however well its spend reads"
    );
}

#[test]
fn a_reveal_that_does_not_hash_to_the_coin_fails_closed() {
    let launcher_ph = Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH);
    let launcher = Coin::new(Bytes32::new([0x03; 32]), launcher_ph, 1);

    // `(q . ())` is a valid program, but it is not the launcher puzzle, so it cannot hash to the
    // launcher puzzle hash — the source is passing off someone else's reveal.
    let source = MockChainSource::new()
        .with_coin(launcher.coin_id(), record(launcher))
        .with_spend(
            launcher.coin_id(),
            CoinSpend::new(
                launcher,
                Program::from(vec![0x01, 0x80]),
                Program::from(vec![0x80]),
            ),
        );

    let error = walk_singleton_lineage(&source, launcher.coin_id())
        .expect_err("a foreign reveal must fail closed");
    assert!(matches!(error, LineageWalkError::Malformed(_)));
}

/// A launcher coin that was never spent has minted no eve, so there is no singleton state yet.
#[test]
fn an_unspent_launcher_has_no_singleton_state() {
    let launcher_ph = Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH);
    let launcher = Coin::new(Bytes32::new([0x04; 32]), launcher_ph, 1);
    let source = MockChainSource::new().with_coin(launcher.coin_id(), record(launcher));

    assert_eq!(
        walk_singleton_lineage(&source, launcher.coin_id()),
        Ok(None)
    );
}

/// A launcher whose spend creates a NON-singleton eve: the launcher puzzle emits whatever
/// `CREATE_COIN` its solution names, so a launcher can perfectly well create an ordinary coin.
///
/// The eve then exists, is genuinely the launcher's child, and is genuinely spendable — and is still
/// not a singleton. Only parsing the eve's own reveal as a singleton layer can tell, which is why
/// the walk does exactly that rather than trusting the launcher's word.
#[test]
fn an_eve_that_is_not_a_singleton_fails_closed() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let owner = sim.bls(1);

    let launcher_coin = Coin::new(
        owner.coin.coin_id(),
        Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH),
        1,
    );
    StandardLayer::new(owner.pk).spend(
        ctx,
        owner.coin,
        Conditions::new().create_coin(launcher_coin.puzzle_hash, 1, Memos::None),
    )?;

    // Spend the launcher so it creates an ORDINARY standard coin rather than a singleton.
    let launcher_puzzle = ctx.alloc(&Program::from(chia_puzzles::SINGLETON_LAUNCHER.to_vec()))?;
    let launcher_solution = ctx.alloc(&(owner.puzzle_hash, (1, (Vec::<Bytes32>::new(), ()))))?;
    ctx.spend(
        launcher_coin,
        Spend::new(launcher_puzzle, launcher_solution),
    )?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&owner.sk))?;

    // Spend the fake eve so the walk reaches its reveal (an unspent coin would end the walk first).
    let fake_eve = Coin::new(launcher_coin.coin_id(), owner.puzzle_hash, 1);
    StandardLayer::new(owner.pk).spend(ctx, fake_eve, Conditions::new())?;
    sim.spend_coins(ctx.take(), std::slice::from_ref(&owner.sk))?;

    let src = source(&sim);
    let error = walk_singleton_lineage(&src, launcher_coin.coin_id())
        .expect_err("a non-singleton eve must not resolve to a lineage");
    assert_eq!(
        error,
        LineageWalkError::NotASingleton {
            coin_id: fake_eve.coin_id()
        }
    );
    Ok(())
}

#[test]
fn a_launcher_record_for_the_wrong_coin_fails_closed() {
    let launcher_ph = Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH);
    let asked_for = Coin::new(Bytes32::new([0x05; 32]), launcher_ph, 1);
    let returned = Coin::new(Bytes32::new([0x06; 32]), launcher_ph, 1);

    let source = MockChainSource::new().with_coin(asked_for.coin_id(), record(returned));

    let error = walk_singleton_lineage(&source, asked_for.coin_id())
        .expect_err("a record for a different coin must fail closed");
    assert!(matches!(error, LineageWalkError::Malformed(_)));
}

#[test]
fn every_failure_reports_itself_distinguishably() {
    let coin_id = Bytes32::new([0x07; 32]);
    let messages = [
        LineageWalkError::Source(ChainSourceError::Timeout).to_string(),
        LineageWalkError::<ChainSourceError>::Malformed("bad".into()).to_string(),
        LineageWalkError::<ChainSourceError>::NotASingleton { coin_id }.to_string(),
        LineageWalkError::<ChainSourceError>::TooDeep { limit: 9 }.to_string(),
    ];
    assert!(messages.iter().all(|message| !message.is_empty()));
    assert_eq!(
        messages
            .iter()
            .collect::<std::collections::BTreeSet<_>>()
            .len(),
        messages.len(),
        "each failure must read differently in a log"
    );

    assert_eq!(
        ChainSourceError::from(LineageWalkError::<ChainSourceError>::NotASingleton { coin_id }),
        ChainSourceError::Malformed(format!(
            "coin {coin_id} is not a genuine singleton of this launcher"
        ))
    );
    assert_eq!(
        ChainSourceError::from(LineageWalkError::<ChainSourceError>::Malformed("x".into())),
        ChainSourceError::Malformed("x".into())
    );
}

// ---------------------------------------------------------------------------------------------
// A spend the source cannot serve is UNKNOWN, never a tip (the `Ok(None)` ambiguity).
// ---------------------------------------------------------------------------------------------

/// `ChainSource::coin_spend` returns `Ok(None)` for "unspent OR unknown", and only the coin's own
/// `spent_height` tells the two apart. A walk that conflates them reports the last coin it could
/// read as the unspent tip.
///
/// Here the chain is launcher -> eve -> C2 -> C3 and the source is honest about every coin's
/// record — it has simply lost C2's spend, as a pruned or partially-indexed node would. C2 is
/// therefore recorded as SPENT while its spend reads as absent. Answering `C2` as the tip would
/// assert that a superseded state is current; the walk must refuse instead.
#[test]
fn a_spent_coin_whose_spend_the_source_cannot_serve_is_never_reported_as_the_tip() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;
    advance(&mut sim, ctx, &mut singleton)?;

    let stale = singleton.trail[2];
    let tip = singleton.tip();

    // The fixture only distinguishes anything if C2 really is spent and really is NOT the tip.
    let spent_state = sim.coin_state(stale.coin_id()).expect("C2 is on chain");
    assert!(
        spent_state.spent_height.is_some(),
        "C2 must be spent for the ambiguity to exist"
    );
    assert_ne!(stale.coin_id(), tip.coin_id());

    let mut src = source(&sim);
    src.withheld_spend = Some(stale.coin_id());

    let error = walk_singleton_lineage(&src, singleton.launcher_id)
        .expect_err("a spend the source cannot serve is an unknown, not a tip");
    assert!(
        matches!(error, LineageWalkError::Malformed(_)),
        "expected a refusal, got {error:?}"
    );

    // And the honest control: with the same source telling the whole truth, the walk resolves.
    let honest = source(&sim);
    assert_eq!(
        walk_singleton_lineage(&honest, singleton.launcher_id)?
            .expect("the honest chain resolves")
            .tip(),
        tip.coin_id(),
    );
    Ok(())
}

/// The same ambiguity at the LAUNCHER degrades an unknown into "this singleton never existed" —
/// the SPEC §3 violation, and the one that reads as a genuine absence rather than a stale tip.
#[test]
fn a_spent_launcher_whose_spend_the_source_cannot_serve_is_not_an_absence() {
    let launcher_ph = Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH);
    let launcher = Coin::new(Bytes32::new([0x08; 32]), launcher_ph, 1);

    let source = MockChainSource::new().with_coin(launcher.coin_id(), spent_record(launcher, 12));

    let error = walk_singleton_lineage(&source, launcher.coin_id())
        .expect_err("a spent launcher with no readable spend is unknown, not unlaunched");
    assert!(
        matches!(error, LineageWalkError::Malformed(_)),
        "expected a refusal, got {error:?}"
    );

    // The control: the SAME launcher recorded as UNSPENT is a genuine absence, so the refusal above
    // is driven by `spent_height`, not merely by the missing spend.
    let unspent = MockChainSource::new().with_coin(launcher.coin_id(), record(launcher));
    assert_eq!(
        walk_singleton_lineage(&unspent, launcher.coin_id()),
        Ok(None)
    );
}

// ---------------------------------------------------------------------------------------------
// The anti-lying-source guards, each pinned by a test that dies with it.
// ---------------------------------------------------------------------------------------------

/// SPEC §4a requirement 2: a derived successor must be bound to a real `coin_record`.
///
/// A solution is not committed to by the coin's puzzle hash, so a source that pairs a genuine
/// reveal with a fabricated solution can name any successor it likes. This fixture is the readable
/// half of that: the successor C2 is derived from a genuine spend, but the source does not admit
/// the coin exists. Deleting the existence check makes the walk sail past C2 to the real tip and
/// answer `Ok(Some(..))`, so this test is what keeps the check alive.
#[test]
fn a_derived_successor_the_source_does_not_know_fails_closed() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let mut singleton = launch(&mut sim, ctx)?;
    advance(&mut sim, ctx, &mut singleton)?;
    advance(&mut sim, ctx, &mut singleton)?;

    let unknown = singleton.trail[2];
    let mut src = source(&sim);
    src.withheld_record = Some(unknown.coin_id());

    let error = walk_singleton_lineage(&src, singleton.launcher_id)
        .expect_err("a successor the source does not know must fail closed");
    match error {
        LineageWalkError::Malformed(detail) => assert!(
            detail.contains(&unknown.coin_id().to_string()),
            "the refusal must name the unknown coin: {detail}"
        ),
        other => panic!("expected a refusal, got {other:?}"),
    }

    // The control: without the veil, the very same chain resolves to the real tip — so the failure
    // above is the guard biting, not a broken fixture.
    let honest = source(&sim);
    assert_eq!(
        walk_singleton_lineage(&honest, singleton.launcher_id)?
            .expect("the honest chain resolves")
            .tip(),
        singleton.tip().coin_id(),
    );
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// The documented return table, pinned.
// ---------------------------------------------------------------------------------------------

/// A launcher spent into an eve that is still UNSPENT resolves to a two-coin lineage whose tip is
/// the eve — even though the eve's own singleton structure cannot be proven until it is spent.
///
/// This is a deliberate, documented limitation, not an oversight: the launcher's `CREATE_COIN`
/// carries the eve's FULL puzzle hash, which is non-invertible, so nothing but the launcher's own
/// spender chose it. It fails closed with `NotASingleton` the moment the eve is spent. The test
/// exists so the documented behaviour is enforced rather than merely described.
#[test]
fn an_unspent_eve_is_the_tip_of_a_two_coin_lineage() -> Result<()> {
    let mut sim = Simulator::new();
    let ctx = &mut SpendContext::new();
    let singleton = launch(&mut sim, ctx)?;

    let eve = singleton.tip();
    assert!(
        sim.coin_spend(eve.coin_id()).is_none(),
        "the eve must be unspent for this to be the documented case"
    );

    let src = source(&sim);
    let lineage =
        walk_singleton_lineage(&src, singleton.launcher_id)?.expect("a freshly launched singleton");
    assert_eq!(lineage.tip(), eve.coin_id());
    assert_eq!(lineage.len(), 2);
    assert!(lineage.contains(singleton.launcher_id));
    Ok(())
}

/// A coin on the walk whose reveal parses as a perfectly good singleton — of a DIFFERENT launcher.
///
/// This is the only shape that reaches the curried-launcher-id check. Every other non-singleton
/// fixture (an ordinary p2 eve, say) is refused one step earlier, when the reveal fails to parse as
/// a singleton layer at all — so `an_eve_that_is_not_a_singleton_fails_closed` fires through a
/// different branch and leaves this guard untouched.
///
/// Admitting such a coin would let anyone extend a victim's lineage with their own singleton's
/// history: the curried launcher id is the only thing tying a well-formed singleton to the launcher
/// under resolution.
#[test]
fn a_singleton_curried_to_a_different_launcher_is_not_a_member() -> Result<()> {
    let ctx = &mut SpendContext::new();
    let victim = Coin::new(
        Bytes32::new([0x0E; 32]),
        Bytes32::new(chia_puzzles::SINGLETON_LAUNCHER_HASH),
        1,
    );
    let foreign_launcher_id = Bytes32::new([0xFE; 32]);

    // A genuine singleton top layer, curried to somebody else's launcher, wrapping an inner puzzle
    // that recreates itself — so with the guard removed the walk has a successor to derive.
    let inner = ctx.alloc(&vec![(51, (Bytes32::new([0x0F; 32]), (1, ())))])?;
    let quoted_inner = ctx.alloc(&(1, inner))?;
    let foreign = ctx.curry(SingletonArgs::new(foreign_launcher_id, quoted_inner))?;
    let eve = Coin::new(victim.coin_id(), Bytes32::from(tree_hash(ctx, foreign)), 1);
    let eve_solution = ctx.alloc(&SingletonSolution {
        lineage_proof: Proof::Eve(EveProof {
            parent_parent_coin_info: victim.parent_coin_info,
            parent_amount: 1,
        }),
        amount: 1,
        inner_solution: NodePtr::NIL,
    })?;

    let source = MockChainSource::new()
        .with_coin(victim.coin_id(), record(victim))
        .with_coin(eve.coin_id(), spent_record(eve, 8))
        .with_spend(
            victim.coin_id(),
            CoinSpend::new(
                victim,
                launcher_reveal(),
                launcher_solution(eve.puzzle_hash, 1),
            ),
        )
        .with_spend(
            eve.coin_id(),
            CoinSpend::new(eve, ctx.serialize(&foreign)?, ctx.serialize(&eve_solution)?),
        );

    // The fixture is only distinguishing if the reveal really does parse as a singleton — otherwise
    // this would re-test the parse failure that `an_eve_that_is_not_a_singleton_fails_closed` covers.
    assert!(
        SingletonLayer::<chia_sdk_driver::Puzzle>::parse_puzzle(
            ctx,
            chia_sdk_driver::Puzzle::parse(ctx, foreign)
        )?
        .is_some_and(|layer| layer.launcher_id == foreign_launcher_id),
        "the reveal must be a well-formed singleton of the OTHER launcher"
    );

    assert_eq!(
        walk_singleton_lineage(&source, victim.coin_id()),
        Err(LineageWalkError::NotASingleton {
            coin_id: eve.coin_id()
        }),
        "a singleton of another launcher must be refused as such, not derived from"
    );
    Ok(())
}

/// The well-known singleton launcher puzzle, serialized.
fn launcher_reveal() -> Program {
    Program::from(chia_puzzles::SINGLETON_LAUNCHER.to_vec())
}

/// A launcher solution minting an eve at `puzzle_hash` for `amount`, with no key-value list.
fn launcher_solution(puzzle_hash: Bytes32, amount: u64) -> Program {
    serialized(&(puzzle_hash, (amount, (Vec::<Bytes32>::new(), ()))))
}

/// `(q . conditions)` — a puzzle that emits `conditions` verbatim whatever its solution.
fn quoting_puzzle<T: clvm_traits::ToClvm<Allocator>>(conditions: &T) -> Program {
    serialized(&(1, conditions))
}

/// The CLVM tree hash of a serialized program.
fn tree_hash_of(program: &Program) -> Bytes32 {
    let mut allocator = Allocator::new();
    let node = node_from_bytes(&mut allocator, program.as_ref()).expect("the program deserializes");
    Bytes32::from(tree_hash(&allocator, node))
}

/// Serializes `value` to a [`Program`].
fn serialized<T: clvm_traits::ToClvm<Allocator>>(value: &T) -> Program {
    let mut allocator = Allocator::new();
    let node =
        clvm_traits::ToClvm::to_clvm(value, &mut allocator).expect("the value always allocates");
    Program::from(node_to_bytes(&allocator, node).expect("the value always serializes"))
}

fn record(coin: Coin) -> CoinRecord {
    CoinRecord {
        coin,
        confirmed_height: Some(1),
        spent_height: None,
        timestamp: None,
        coinbase: false,
    }
}

/// [`record`] for a coin the source reports as SPENT — the state no fixture could express while
/// `spent_height` was hardcoded to `None`.
fn spent_record(coin: Coin, spent_height: u32) -> CoinRecord {
    CoinRecord {
        spent_height: Some(spent_height),
        ..record(coin)
    }
}