chia-query 0.7.0

Query the Chia blockchain via decentralized peers with coinset.org fallback
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
//! The provider registry and its two views: the fail-closed **custody** view
//! ([`ProviderRegistry::trusted`]) and the low-trust **discovery** view
//! ([`ProviderRegistry::any`]).
//!
//! The registry composes arbitrary [`ChainSourceProvider`]s (a local node, coinset.org, DIG peers,
//! an operator override) under an operator-assigned [`TrustLevel`]. Its custody view answers a read
//! ONLY from an operator-trusted source or a qualifying quorum, and FAILS CLOSED otherwise — a
//! provider's self-declared `trustless` flag is advisory and never grants custody trust (SPEC §5).

use chia_protocol::{Bytes32, CoinSpend};
use dig_chainsource_interface::{
    ChainSource, ChainSourceError, ChainSourceProvider, CoinRecord, ProviderKind, SingletonLineage,
};

/// The trust an OPERATOR assigns a provider for custody (money-routing) reads. This is the
/// authority the custody view relies on — distinct from a provider's advisory `trustless` flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrustLevel {
    /// The operator vouches for this source for custody reads (their own verified node).
    Trusted,
    /// Not vouched for custody; usable only within a qualifying quorum or for discovery reads.
    Untrusted,
}

impl TrustLevel {
    /// The default trust for a provider kind: a local node the operator runs is `Trusted`; every
    /// public/shared source is `Untrusted` until the operator explicitly vouches for it.
    pub fn default_for(kind: ProviderKind) -> Self {
        match kind {
            ProviderKind::LocalNode => Self::Trusted,
            ProviderKind::PublicOracle | ProviderKind::DigPeers | ProviderKind::Custom => {
                Self::Untrusted
            }
        }
    }
}

/// The number of independent groups that must agree for a pure-public quorum to satisfy custody.
const PUBLIC_QUORUM_THRESHOLD: usize = 2;

/// The maximum number of coin records accepted in a single quorum answer from an UNTRUSTED public
/// source.
///
/// A list read ([`ChainSource::coin_records_by_puzzle_hash`], [`ChainSource::coin_records_by_parent`])
/// answers with an attacker-influenceable, unbounded `Vec`. Canonicalizing + comparing it costs CPU
/// and memory proportional to its length, so a hostile source could return a huge list to exhaust
/// resources during a quorum. This ceiling bounds that work and fails closed
/// ([`ChainSourceError::TooManyRecords`]) past it — mirroring the bounded-input discipline of #1323. It is
/// generous: no legitimate puzzle hash or parent coin has anywhere near this many children, so a
/// genuine answer is never rejected, while an adversarial flood is capped.
const MAX_QUORUM_RECORDS: usize = 100_000;

/// A boxed, dynamically-dispatched registry participant.
type DynProvider = dyn ChainSourceProvider<Error = ChainSourceError>;

/// One registered provider: the source itself, its operator-assigned trust, and the independence
/// group it belongs to (two providers in the same group are NOT independent).
struct Registration {
    provider: Box<DynProvider>,
    trust: TrustLevel,
    independence_group: String,
}

/// Composes [`ChainSourceProvider`]s under an operator trust model, exposing a fail-closed custody
/// view and a low-trust discovery view.
#[derive(Default)]
pub struct ProviderRegistry {
    providers: Vec<Registration>,
    allow_public_quorum_custody: bool,
}

impl ProviderRegistry {
    /// A new, empty registry (custody fails closed until a trusted or quorum-qualifying source is
    /// registered).
    pub fn new() -> Self {
        Self::default()
    }

    /// Enables (`true`) or disables (`false`, the safe default) pure-public-quorum custody.
    ///
    /// With this OFF, a registry holding only public/untrusted sources cannot satisfy custody —
    /// every custody read fails closed. Turning it ON is a deliberate operator choice that accepts
    /// the reduced assurance of a [`PUBLIC_QUORUM_THRESHOLD`]-of-independent-groups agreement in
    /// place of an operator-trusted source (SPEC §5).
    pub fn allow_public_quorum_custody(mut self, allow: bool) -> Self {
        self.allow_public_quorum_custody = allow;
        if allow {
            log::warn!(
                "chia-query registry: pure-public-quorum custody ENABLED — custody reads may be \
                 satisfied by {PUBLIC_QUORUM_THRESHOLD} independent public sources with NO \
                 operator-trusted source. Reduced assurance vs a trusted local node."
            );
        }
        self
    }

    /// Registers a provider, defaulting its trust from its [`ProviderKind`] unless the operator
    /// overrides it, and placing it in `independence_group` (sources that could fail or lie
    /// together — e.g. two views of the same coinset.org — share a group id).
    pub fn register(
        mut self,
        provider: Box<DynProvider>,
        trust_override: Option<TrustLevel>,
        independence_group: impl Into<String>,
    ) -> Self {
        let trust = trust_override
            .unwrap_or_else(|| TrustLevel::default_for(provider.provider_info().kind));
        self.providers.push(Registration {
            provider,
            trust,
            independence_group: independence_group.into(),
        });
        self
    }

    /// The CUSTODY view — sound for money-routing reads.
    ///
    /// A read is satisfied ONLY by an operator-[`Trusted`](TrustLevel::Trusted) source (preferred
    /// when present) or, when `allow_public_quorum_custody` is set, a quorum of
    /// [`PUBLIC_QUORUM_THRESHOLD`] independent public sources that agree. Otherwise it fails closed.
    pub fn trusted(&self) -> TrustedView<'_> {
        TrustedView { registry: self }
    }

    /// The DISCOVERY view — low-trust, single-provider reads for NON-custody use.
    ///
    /// It returns the first provider that answers, with NO trust or quorum guarantee. Its result
    /// MUST NOT be used to route funds; use [`trusted`](Self::trusted) for anything custody-bearing.
    pub fn any(&self) -> DiscoveryView<'_> {
        DiscoveryView { registry: self }
    }

    /// The registered providers sorted by ascending `priority` (lowest tried first).
    fn by_priority(&self) -> Vec<&Registration> {
        let mut ordered: Vec<&Registration> = self.providers.iter().collect();
        ordered.sort_by_key(|reg| reg.provider.provider_info().priority);
        ordered
    }
}

/// The custody view over a [`ProviderRegistry`] — see [`ProviderRegistry::trusted`].
pub struct TrustedView<'a> {
    registry: &'a ProviderRegistry,
}

impl TrustedView<'_> {
    /// Answers `query` under the custody trust rule, failing closed when no trusted source or
    /// qualifying quorum can answer.
    fn custody_read<T, Q>(&self, query: Q) -> Result<T, ChainSourceError>
    where
        T: QuorumComparable + Clone,
        Q: Fn(&DynProvider) -> Result<T, ChainSourceError>,
    {
        let trusted: Vec<&Registration> = self
            .registry
            .by_priority()
            .into_iter()
            .filter(|reg| reg.trust == TrustLevel::Trusted)
            .collect();

        // (a) An operator-trusted source is the gold standard — always preferred when present.
        if !trusted.is_empty() {
            let mut last_error = ChainSourceError::NoProvider;
            for reg in trusted {
                match query(&*reg.provider) {
                    Ok(value) => return Ok(value),
                    Err(error) => last_error = error,
                }
            }
            // Every trusted source failed to answer — fail closed, never degrade to a public source.
            return Err(last_error);
        }

        // (b) No trusted source. A pure-public quorum only qualifies when explicitly opted in.
        if !self.registry.allow_public_quorum_custody {
            return Err(ChainSourceError::NoProvider);
        }
        quorum_read(&self.registry.providers, PUBLIC_QUORUM_THRESHOLD, query)
    }
}

/// The discovery view over a [`ProviderRegistry`] — see [`ProviderRegistry::any`].
pub struct DiscoveryView<'a> {
    registry: &'a ProviderRegistry,
}

impl DiscoveryView<'_> {
    /// Answers `query` from the first provider that responds — NO trust or quorum guarantee.
    ///
    /// Even without a quorum, a discovery answer is still UNTRUSTED input, so each candidate is
    /// bounded ([`QuorumComparable::validate_bound`]) before it is accepted — mirroring the quorum
    /// path (#1341), which drops an over-cap member rather than aborting. An oversized answer here is
    /// likewise treated as a non-answer: it records the bound violation in `last_error` and falls
    /// through to the next provider, so one hostile source returning a multi-GB flood can neither be
    /// returned to the caller nor deny an honest fallback provider its turn.
    fn discovery_read<T, Q>(&self, query: Q) -> Result<T, ChainSourceError>
    where
        T: QuorumComparable,
        Q: Fn(&DynProvider) -> Result<T, ChainSourceError>,
    {
        let mut last_error = ChainSourceError::NoProvider;
        for reg in self.registry.by_priority() {
            match query(&*reg.provider) {
                Ok(value) => match value.validate_bound() {
                    Ok(()) => return Ok(value),
                    Err(error) => last_error = error,
                },
                Err(error) => last_error = error,
            }
        }
        Err(last_error)
    }
}

/// Order-insensitive equality for quorum agreement.
///
/// Two honest, independent sources may return the SAME records in a DIFFERENT order — the list
/// reads ([`ChainSource::coin_records_by_puzzle_hash`], [`ChainSource::coin_records_by_parent`])
/// promise a set of matching coins, not an ordering. A byte-for-byte `Vec` comparison would make
/// such sources spuriously "disagree" and fail an otherwise-satisfiable quorum (an availability
/// nit). `quorum_eq` compares answers by VALUE independent of incidental ordering, while still
/// treating genuinely different record SETS as disagreement — the quorum security property (SPEC §5)
/// is preserved; only the false-negative on ordering is removed.
trait QuorumComparable {
    /// Whether two source answers agree for the purpose of a quorum, ignoring incidental ordering.
    fn quorum_eq(&self, other: &Self) -> bool;

    /// Rejects an implausibly large answer from an untrusted source BEFORE it is canonicalized or
    /// compared, bounding quorum CPU + memory. The default imposes no bound (fixed-size answers);
    /// only unbounded list answers override it.
    fn validate_bound(&self) -> Result<(), ChainSourceError> {
        Ok(())
    }
}

/// Answers with no meaningful internal ordering agree exactly when they are equal.
macro_rules! quorum_eq_via_partial_eq {
    ($($t:ty),+ $(,)?) => {
        $(impl QuorumComparable for $t {
            fn quorum_eq(&self, other: &Self) -> bool {
                self == other
            }
        })+
    };
}

quorum_eq_via_partial_eq!(
    Option<CoinRecord>,
    Option<CoinSpend>,
    Option<SingletonLineage>,
    Option<u32>,
    Option<u64>,
);

impl QuorumComparable for Vec<CoinRecord> {
    fn quorum_eq(&self, other: &Self) -> bool {
        canonical_order(self) == canonical_order(other)
    }

    fn validate_bound(&self) -> Result<(), ChainSourceError> {
        if self.len() > MAX_QUORUM_RECORDS {
            return Err(ChainSourceError::TooManyRecords {
                count: self.len(),
                limit: MAX_QUORUM_RECORDS,
            });
        }
        Ok(())
    }
}

/// Borrows the records in a canonical order keyed by coin id so two equal SETS returned in different
/// orders compare equal.
///
/// Each record's coin id is a SHA-256 commitment to the whole coin, computed ONCE per record into the
/// sort key here — so the comparison hashes O(n) times, not the O(n log n) a `sort_by` recomputing
/// `coin_id()` in every comparison would cost. The id totally orders distinct coins; records sharing
/// a coin but differing in metadata still differ (the comparison includes the record), so genuine
/// disagreement is preserved.
fn canonical_order(records: &[CoinRecord]) -> Vec<(Bytes32, &CoinRecord)> {
    let mut keyed: Vec<(Bytes32, &CoinRecord)> =
        records.iter().map(|r| (r.coin.coin_id(), r)).collect();
    keyed.sort_by(|a, b| a.0.as_ref().cmp(b.0.as_ref()));
    keyed
}

/// Requires `threshold` DISTINCT independence groups to return the SAME answer for `query`.
///
/// Each group contributes at most one answer (its first provider that responds); the count is over
/// distinct groups, so two providers in the same group can never satisfy a `threshold >= 2` on
/// their own. Agreement is order-insensitive ([`QuorumComparable`]), so two honest sources returning
/// the same record set in a different order still agree. Insufficient agreement — disagreement, too
/// few groups, or all errors — fails closed (SPEC §5).
fn quorum_read<T, Q>(
    providers: &[Registration],
    threshold: usize,
    query: Q,
) -> Result<T, ChainSourceError>
where
    T: QuorumComparable + Clone,
    Q: Fn(&DynProvider) -> Result<T, ChainSourceError>,
{
    // One representative answer per independence group (the first provider in the group to answer).
    let mut per_group: Vec<(&str, T)> = Vec::new();
    for reg in providers {
        let group = reg.independence_group.as_str();
        if per_group.iter().any(|(existing, _)| *existing == group) {
            continue; // this group already contributed a representative answer
        }
        if let Ok(answer) = query(&*reg.provider) {
            // Drop an implausibly large untrusted answer BEFORE any canonicalization/comparison, so
            // it costs no O(n log n) work and never enters the tally. Skipping (not propagating) is
            // deliberate: a single hostile member returning an oversized list simply loses its vote,
            // exactly as a non-responding member would — it must NOT abort the whole quorum and deny
            // an otherwise-valid honest agreement (that would be a self-defeating DoS lever).
            if answer.validate_bound().is_err() {
                continue;
            }
            per_group.push((group, answer));
        }
    }

    // An answer qualifies when `threshold` distinct groups agree on it (order-insensitively).
    for (_, candidate) in &per_group {
        let agreeing = per_group
            .iter()
            .filter(|(_, a)| a.quorum_eq(candidate))
            .count();
        if agreeing >= threshold {
            return Ok(candidate.clone());
        }
    }
    Err(ChainSourceError::NoProvider)
}

// The two views present the full [`ChainSource`] surface; each method dispatches through the view's
// trust rule via a closure capturing the query's arguments.

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

    fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
        self.custody_read(move |p| p.coin_record(coin_id))
    }

    fn coin_records_by_puzzle_hash(
        &self,
        puzzle_hash: Bytes32,
        include_spent: bool,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        self.custody_read(move |p| p.coin_records_by_puzzle_hash(puzzle_hash, include_spent))
    }

    fn coin_records_by_parent(
        &self,
        parent_coin_id: Bytes32,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        self.custody_read(move |p| p.coin_records_by_parent(parent_coin_id))
    }

    fn coin_spend(&self, coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
        self.custody_read(move |p| p.coin_spend(coin_id))
    }

    fn resolve_singleton_lineage(
        &self,
        launcher_id: Bytes32,
    ) -> Result<Option<SingletonLineage>, Self::Error> {
        // Cross-source agreement on a lineage requires the FULL lineage to match; consumers still
        // apply the authority MEMBERSHIP test (`SingletonLineage::contains`) to the result — never
        // tip/puzzle-hash equality (SPEC §5).
        self.custody_read(move |p| p.resolve_singleton_lineage(launcher_id))
    }

    fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
        self.custody_read(|p| p.peak_height())
    }

    fn block_timestamp(&self, height: u32) -> Result<Option<u64>, Self::Error> {
        self.custody_read(move |p| p.block_timestamp(height))
    }
}

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

    fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
        self.discovery_read(move |p| p.coin_record(coin_id))
    }

    fn coin_records_by_puzzle_hash(
        &self,
        puzzle_hash: Bytes32,
        include_spent: bool,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        self.discovery_read(move |p| p.coin_records_by_puzzle_hash(puzzle_hash, include_spent))
    }

    fn coin_records_by_parent(
        &self,
        parent_coin_id: Bytes32,
    ) -> Result<Vec<CoinRecord>, Self::Error> {
        self.discovery_read(move |p| p.coin_records_by_parent(parent_coin_id))
    }

    fn coin_spend(&self, coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
        self.discovery_read(move |p| p.coin_spend(coin_id))
    }

    fn resolve_singleton_lineage(
        &self,
        launcher_id: Bytes32,
    ) -> Result<Option<SingletonLineage>, Self::Error> {
        self.discovery_read(move |p| p.resolve_singleton_lineage(launcher_id))
    }

    fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
        self.discovery_read(|p| p.peak_height())
    }

    fn block_timestamp(&self, height: u32) -> Result<Option<u64>, Self::Error> {
        self.discovery_read(move |p| p.block_timestamp(height))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chia_protocol::Coin;
    use dig_chainsource_interface::MockChainSource;

    use crate::provider_registry::providers::{CoinsetProvider, CustomProvider, LocalNodeProvider};

    fn coin_id(byte: u8) -> Bytes32 {
        Coin::new(Bytes32::new([byte; 32]), Bytes32::new([byte; 32]), 1).coin_id()
    }

    fn record_for(id: Bytes32) -> CoinRecord {
        CoinRecord {
            coin: Coin::new(id, Bytes32::new([0x22; 32]), 1),
            confirmed_height: Some(100),
            spent_height: None,
            timestamp: Some(1_700_000_000),
            coinbase: false,
        }
    }

    fn mock_with(id: Bytes32) -> MockChainSource {
        MockChainSource::new().with_coin(id, record_for(id))
    }

    // ---- Test #2 (LOAD-BEARING): pure-public quorum WITHOUT opt-in fails closed ----

    #[test]
    fn pure_public_quorum_without_optin_fails_closed_for_custody() {
        let id = coin_id(0x01);
        // Two INDEPENDENT public sources that both KNOW the coin and AGREE — yet, with no
        // operator-trusted source and no opt-in, custody MUST NOT be satisfied.
        let registry = ProviderRegistry::new()
            .register(
                Box::new(CoinsetProvider::new("coinset-a", 10, mock_with(id))),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new("mirror-b", 20, mock_with(id))),
                None,
                "mirror.example",
            );

        let result = registry.trusted().coin_record(id);
        assert_eq!(
            result,
            Err(ChainSourceError::NoProvider),
            "pure-public custody must fail closed without allow_public_quorum_custody"
        );
    }

    // ---- Test #3: an operator-Trusted LocalNode satisfies custody ----

    #[test]
    fn operator_trusted_local_node_satisfies_custody() {
        let id = coin_id(0x02);
        let registry = ProviderRegistry::new().register(
            Box::new(LocalNodeProvider::new("local", 0, mock_with(id))),
            None, // LocalNode defaults to Trusted
            "local-node",
        );

        let record = registry.trusted().coin_record(id).unwrap();
        assert_eq!(record, Some(record_for(id)));
    }

    #[test]
    fn local_node_defaults_to_trusted() {
        assert_eq!(
            TrustLevel::default_for(ProviderKind::LocalNode),
            TrustLevel::Trusted
        );
        assert_eq!(
            TrustLevel::default_for(ProviderKind::PublicOracle),
            TrustLevel::Untrusted
        );
    }

    // ---- Test #4: a quorum INCLUDING a trusted member satisfies custody ----

    #[test]
    fn quorum_including_trusted_member_satisfies_custody() {
        let id = coin_id(0x03);
        let registry = ProviderRegistry::new()
            .register(
                Box::new(LocalNodeProvider::new("local", 0, mock_with(id))),
                None, // Trusted
                "local-node",
            )
            .register(
                Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
                None, // Untrusted public
                "coinset.org",
            );

        // The trusted member answers; custody is satisfied.
        let record = registry.trusted().coin_record(id).unwrap();
        assert_eq!(record, Some(record_for(id)));
    }

    #[test]
    fn trusted_source_error_fails_closed_not_public_fallback() {
        let id = coin_id(0x04);
        let registry = ProviderRegistry::new()
            .register(
                Box::new(LocalNodeProvider::new(
                    "local",
                    0,
                    MockChainSource::new().fail_with(ChainSourceError::Timeout),
                )),
                None,
                "local-node",
            )
            .register(
                Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
                None,
                "coinset.org",
            );

        // The trusted node errored; custody fails closed rather than reading the public source.
        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::Timeout)
        );
    }

    // ---- Test #5: opt-in pure-public quorum needs T=2 INDEPENDENT groups ----

    #[test]
    fn optin_two_independent_groups_agree_satisfies_custody() {
        let id = coin_id(0x05);
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new("mirror", 20, mock_with(id))),
                None,
                "mirror.example",
            );

        assert_eq!(
            registry.trusted().coin_record(id).unwrap(),
            Some(record_for(id))
        );
    }

    #[test]
    fn optin_single_group_fails_closed() {
        let id = coin_id(0x06);
        // Only ONE independent group qualifies -> below threshold -> fail closed.
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
                None,
                "coinset.org",
            );

        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
    }

    #[test]
    fn optin_two_providers_same_group_fails_closed() {
        let id = coin_id(0x07);
        // Two providers agreeing but in the SAME independence group count as ONE -> below T=2.
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new("coinset-a", 10, mock_with(id))),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CoinsetProvider::new("coinset-b", 20, mock_with(id))),
                None,
                "coinset.org", // SAME group
            );

        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
    }

    #[test]
    fn optin_two_groups_disagree_fails_closed() {
        let id = coin_id(0x08);
        // Two independent groups that DISAGREE (one knows the coin, one does not) -> no quorum.
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new("empty", 20, MockChainSource::new())),
                None,
                "mirror.example",
            );

        // coinset says Some(record), mirror says Ok(None) — disagreement -> fail closed.
        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
    }

    // ---- Order-insensitive quorum agreement (#1259 fix 1) ----

    /// A test source returning a fixed, caller-controlled ORDER of records for the list reads, so a
    /// quorum comparison can be exercised across sources that agree on the SET but differ in order.
    struct FixedListSource {
        records: Vec<CoinRecord>,
    }

    impl ChainSource for FixedListSource {
        type Error = ChainSourceError;

        fn coin_record(&self, _coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
            Ok(None)
        }

        fn coin_records_by_puzzle_hash(
            &self,
            _puzzle_hash: Bytes32,
            _include_spent: bool,
        ) -> Result<Vec<CoinRecord>, Self::Error> {
            Ok(self.records.clone())
        }

        fn coin_records_by_parent(
            &self,
            _parent_coin_id: Bytes32,
        ) -> Result<Vec<CoinRecord>, Self::Error> {
            Ok(self.records.clone())
        }

        fn coin_spend(&self, _coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
            Ok(None)
        }

        fn resolve_singleton_lineage(
            &self,
            _launcher_id: Bytes32,
        ) -> Result<Option<SingletonLineage>, Self::Error> {
            Ok(None)
        }

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

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

    fn list_source(records: Vec<CoinRecord>) -> FixedListSource {
        FixedListSource { records }
    }

    #[test]
    fn quorum_agrees_on_same_record_set_in_different_order() {
        let ph = Bytes32::new([0x22; 32]);
        let a = record_for(coin_id(0x0A));
        let b = record_for(coin_id(0x0B));

        // Two INDEPENDENT public sources return the SAME set of records in REVERSED order. With the
        // opt-in quorum, they must AGREE (order is not a source of disagreement).
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new(
                    "coinset",
                    10,
                    list_source(vec![a.clone(), b.clone()]),
                )),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new(
                    "mirror",
                    20,
                    list_source(vec![b.clone(), a.clone()]),
                )),
                None,
                "mirror.example",
            );

        let records = registry
            .trusted()
            .coin_records_by_puzzle_hash(ph, false)
            .expect("honest sources agreeing on a set must satisfy the quorum");
        assert_eq!(records.len(), 2);
        assert!(records.contains(&a) && records.contains(&b));
    }

    #[test]
    fn quorum_still_fails_closed_on_genuinely_different_record_sets() {
        let ph = Bytes32::new([0x22; 32]);
        let a = record_for(coin_id(0x0A));
        let b = record_for(coin_id(0x0B));
        let c = record_for(coin_id(0x0C));

        // Different SETS ({a,b} vs {a,c}) must still be treated as disagreement -> fail closed. The
        // order-insensitive comparison must not weaken the quorum into accepting different content.
        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new(
                    "coinset",
                    10,
                    list_source(vec![a.clone(), b]),
                )),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new("mirror", 20, list_source(vec![c, a]))),
                None,
                "mirror.example",
            );

        assert_eq!(
            registry.trusted().coin_records_by_puzzle_hash(ph, false),
            Err(ChainSourceError::NoProvider),
            "genuinely different record sets must fail closed"
        );
    }

    /// Builds an over-cap flood of records (all under puzzle hash `ph`) to exercise the record bound.
    fn oversized_flood(ph: Bytes32) -> Vec<CoinRecord> {
        let flood: Vec<CoinRecord> = (0..=MAX_QUORUM_RECORDS as u32)
            .map(|i| {
                let coin = Coin::new(Bytes32::new([0x01; 32]), ph, u64::from(i) + 1);
                let mut r = record_for(coin.coin_id());
                r.coin = coin;
                r
            })
            .collect();
        assert!(flood.len() > MAX_QUORUM_RECORDS);
        flood
    }

    /// #1341: an over-cap untrusted answer is DROPPED (loses its vote), never propagated. When every
    /// available source floods, no honest quorum can form -> fail closed (as a set of non-responders
    /// would), but the bound work is still avoided (the flood is never canonicalized).
    #[test]
    fn quorum_fails_closed_when_all_sources_exceed_the_record_cap() {
        let ph = Bytes32::new([0x22; 32]);
        let flood = oversized_flood(ph);

        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new(
                    "coinset",
                    10,
                    list_source(flood.clone()),
                )),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new("mirror", 20, list_source(flood))),
                None,
                "mirror.example",
            );

        // Both oversized answers are skipped -> no group votes -> no quorum -> fail closed.
        assert_eq!(
            registry.trusted().coin_records_by_puzzle_hash(ph, false),
            Err(ChainSourceError::NoProvider),
            "when every source floods, custody must fail closed"
        );
    }

    /// #1341 (in-PR security fix): a SINGLE hostile member returning an over-cap flood must NOT abort
    /// the whole quorum. It loses its vote (dropped before any canonicalization); the two honest,
    /// independent groups that agree still form the quorum, so availability is preserved while the
    /// DoS bound holds.
    #[test]
    fn oversized_quorum_member_is_skipped_not_fatal() {
        let ph = Bytes32::new([0x22; 32]);
        let a = record_for(coin_id(0x0A));
        let b = record_for(coin_id(0x0B));
        let flood = oversized_flood(ph);

        let registry = ProviderRegistry::new()
            .allow_public_quorum_custody(true)
            .register(
                Box::new(CoinsetProvider::new(
                    "coinset",
                    10,
                    list_source(vec![a.clone(), b.clone()]),
                )),
                None,
                "coinset.org",
            )
            .register(
                Box::new(CustomProvider::new(
                    "mirror",
                    20,
                    list_source(vec![b.clone(), a.clone()]),
                )),
                None,
                "mirror.example",
            )
            .register(
                Box::new(CustomProvider::new("flooder", 30, list_source(flood))),
                None,
                "flooder.example",
            );

        let records = registry
            .trusted()
            .coin_records_by_puzzle_hash(ph, false)
            .expect("an honest 2-group agreement must still satisfy the quorum");
        assert_eq!(records.len(), 2, "the flood must not enter the tally");
        assert!(records.contains(&a) && records.contains(&b));
    }

    // ---- Test #7: discovery view returns a single-provider answer, inert for custody ----

    #[test]
    fn discovery_view_returns_single_provider_answer() {
        let id = coin_id(0x09);
        let registry = ProviderRegistry::new().register(
            Box::new(CoinsetProvider::new("coinset", 10, mock_with(id))),
            None,
            "coinset.org",
        );

        // Discovery answers from the single public provider...
        assert_eq!(
            registry.any().coin_record(id).unwrap(),
            Some(record_for(id))
        );
        // ...but the SAME registry fails closed for custody (no trusted source, no opt-in).
        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
    }

    /// #1351: a discovery answer is untrusted too — an over-cap flood from the only provider must be
    /// rejected (`TooManyRecords`), never handed back to the caller unbounded.
    #[test]
    fn discovery_rejects_oversized_untrusted_response() {
        let ph = Bytes32::new([0x22; 32]);
        let flood = oversized_flood(ph);

        let registry = ProviderRegistry::new().register(
            Box::new(CoinsetProvider::new("coinset", 10, list_source(flood))),
            None,
            "coinset.org",
        );

        assert!(
            matches!(
                registry.any().coin_records_by_puzzle_hash(ph, false),
                Err(ChainSourceError::TooManyRecords { count, limit })
                    if count == MAX_QUORUM_RECORDS + 1 && limit == MAX_QUORUM_RECORDS
            ),
            "an over-cap discovery answer must be rejected as TooManyRecords"
        );
    }

    /// #1351: a within-cap discovery answer still passes through unchanged (the bound only rejects
    /// implausibly large responses).
    #[test]
    fn discovery_passes_within_cap_response() {
        let ph = Bytes32::new([0x22; 32]);
        let a = record_for(coin_id(0x0A));
        let b = record_for(coin_id(0x0B));

        let registry = ProviderRegistry::new().register(
            Box::new(CoinsetProvider::new(
                "coinset",
                10,
                list_source(vec![a.clone(), b.clone()]),
            )),
            None,
            "coinset.org",
        );

        let records = registry
            .any()
            .coin_records_by_puzzle_hash(ph, false)
            .expect("a within-cap discovery answer must pass through");
        assert_eq!(records.len(), 2);
        assert!(records.contains(&a) && records.contains(&b));
    }

    #[test]
    fn every_read_method_flows_through_both_views() {
        let ph = Bytes32::new([0x22; 32]);
        let parent = Coin::new(Bytes32::new([0x01; 32]), ph, 1);
        let parent_id = parent.coin_id();
        let child = Coin::new(parent_id, ph, 1);
        let launcher = Bytes32::new([0x77; 32]);

        let source = MockChainSource::new()
            .with_coin(parent_id, record_for(parent_id))
            .with_coin(child.coin_id(), {
                let mut r = record_for(child.coin_id());
                r.coin = child;
                r
            })
            .with_spend(
                parent_id,
                chia_protocol::CoinSpend::new(
                    parent,
                    chia_protocol::Program::from(vec![1]),
                    chia_protocol::Program::from(vec![0x80]),
                ),
            )
            .with_lineage(launcher, SingletonLineage::single(launcher))
            .with_timestamp(100, 1_700_000_000)
            .with_peak(555);

        let registry = ProviderRegistry::new().register(
            Box::new(LocalNodeProvider::new("local", 0, source)),
            None, // Trusted
            "local-node",
        );

        // Custody view — every method answers via the trusted source.
        let custody = registry.trusted();
        assert!(!custody
            .coin_records_by_puzzle_hash(ph, true)
            .unwrap()
            .is_empty());
        assert!(!custody
            .coin_records_by_parent(parent_id)
            .unwrap()
            .is_empty());
        assert!(custody.coin_spend(parent_id).unwrap().is_some());
        assert_eq!(custody.peak_height().unwrap(), Some(555));
        assert_eq!(custody.block_timestamp(100).unwrap(), Some(1_700_000_000));
        assert_eq!(
            custody.resolve_singleton_lineage(launcher).unwrap(),
            Some(SingletonLineage::single(launcher))
        );

        // Discovery view — same reads, single-provider, no trust guarantee.
        let discovery = registry.any();
        assert!(discovery.coin_record(parent_id).unwrap().is_some());
        assert!(!discovery
            .coin_records_by_puzzle_hash(ph, false)
            .unwrap()
            .is_empty());
        assert!(!discovery
            .coin_records_by_parent(parent_id)
            .unwrap()
            .is_empty());
        assert!(discovery.coin_spend(parent_id).unwrap().is_some());
        assert_eq!(discovery.peak_height().unwrap(), Some(555));
        assert_eq!(discovery.block_timestamp(100).unwrap(), Some(1_700_000_000));
        assert!(discovery
            .resolve_singleton_lineage(launcher)
            .unwrap()
            .is_some());
    }

    #[test]
    fn discovery_falls_through_failing_providers_to_a_responder() {
        let id = coin_id(0x0B);
        let registry = ProviderRegistry::new()
            .register(
                Box::new(CoinsetProvider::new(
                    "down",
                    0,
                    MockChainSource::new().fail_with(ChainSourceError::Timeout),
                )),
                None,
                "down",
            )
            .register(
                Box::new(CoinsetProvider::new("up", 10, mock_with(id))),
                None,
                "up",
            );
        assert_eq!(
            registry.any().coin_record(id).unwrap(),
            Some(record_for(id))
        );
    }

    #[test]
    fn empty_registry_fails_closed_everywhere() {
        let registry = ProviderRegistry::new();
        let id = coin_id(0x0A);
        assert_eq!(
            registry.trusted().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
        assert_eq!(
            registry.any().coin_record(id),
            Err(ChainSourceError::NoProvider)
        );
    }
}