chia-query 0.15.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
//! QueryRouter -- dispatches each request to the peer backend first (with one
//! retry on a different peer) and falls back to the coinset.org HTTP API if
//! both peer attempts fail.

use std::collections::HashMap;
use std::sync::Arc;

use chia_consensus::consensus_constants::ConsensusConstants;
use chia_consensus::flags::DONT_VALIDATE_SIGNATURE;
use serde_json::Value;

use crate::coinset::CoinsetClient;
use crate::peer::{OptAnswer, PeerBackend};
use crate::types::*;

#[cfg(test)]
mod absence_tests;
#[cfg(test)]
mod presence_tests;

// ---------------------------------------------------------------------------
// Puzzle condition extraction helper
// ---------------------------------------------------------------------------

/// Run a puzzle against its solution (from a CoinSpend) and extract the CLVM
/// output conditions.  Used by `get_puzzle_and_solution_with_conditions`.
fn run_puzzle_conditions(spend: &CoinSpend, constants: &ConsensusConstants) -> Vec<Condition> {
    let flags = DONT_VALIDATE_SIGNATURE;
    let Ok(puzzle_bytes) = crate::peer::translate::parse_hex(&spend.puzzle_reveal) else {
        return Vec::new();
    };
    let Ok(solution_bytes) = crate::peer::translate::parse_hex(&spend.solution) else {
        return Vec::new();
    };

    let mut allocator = chia_consensus::allocator::make_allocator(flags);

    let Ok(puzzle_node) = clvmr::serde::node_from_bytes(&mut allocator, &puzzle_bytes) else {
        return Vec::new();
    };
    let Ok(solution_node) = clvmr::serde::node_from_bytes(&mut allocator, &solution_bytes) else {
        return Vec::new();
    };

    let dialect = clvmr::chia_dialect::ChiaDialect::new(flags);
    match clvmr::run_program::run_program(
        &mut allocator,
        &dialect,
        puzzle_node,
        solution_node,
        constants.max_block_cost_clvm,
    ) {
        Ok(clvmr::reduction::Reduction(_, output)) => {
            crate::peer::block::parse_conditions_public(&allocator, output)
        }
        Err(_) => Vec::new(),
    }
}

/// Decide what one peer's uncorroborated absence becomes, given whatever the coinset tier said.
///
/// `coinset` is `None` when the coinset tier was not consulted at all because the fallback is
/// disabled — the distinction matters, since "nobody else was asked" and "somebody else was asked
/// and agreed" are the two facts this whole change exists to keep apart.
///
/// Absence is only ever reported when a SECOND source says it too. Everything else is an error,
/// and a contradiction is surfaced rather than broken in favour of either source: nothing in two
/// contradictory answers says which one to believe.
fn settle_uncorroborated_absence<T>(
    coinset: Option<Result<Option<T>, ChiaQueryError>>,
) -> Result<Option<T>, ChiaQueryError> {
    match coinset {
        None => Err(ChiaQueryError::UncorroboratedAbsence(
            "one peer reported absence, no second peer was available, and the coinset fallback is \
             disabled"
                .into(),
        )),
        Some(Ok(None)) => Ok(None),
        Some(Ok(Some(_))) => Err(ChiaQueryError::SourcesDisagree(
            "a peer reports absent, the coinset API reports present".into(),
        )),
        Some(Err(e)) => Err(ChiaQueryError::UncorroboratedAbsence(format!(
            "one peer reported absence and the coinset API could not corroborate it: {e}"
        ))),
    }
}

/// What a positive answer that only ONE source will vouch for becomes.
///
/// The mirror of [`settle_uncorroborated_absence`], and the more dangerous of the two: an absence
/// nobody can confirm leaves a caller polling, while a PRESENCE nobody can confirm makes it stop
/// and record a height. `coinset` is `Some` only when the fallback tier was consulted — `None`
/// means it is disabled, and a fact nobody could be brought to agree with is never returned as one
/// (dig_ecosystem#2462).
fn settle_uncorroborated_presence<T: ChainClaim>(
    found: T,
    coinset: Option<Result<Option<T>, ChiaQueryError>>,
) -> Result<Option<T>, ChiaQueryError> {
    match coinset {
        None => Err(ChiaQueryError::UncorroboratedPresence(
            "one peer produced a record, no second peer was available, and the coinset fallback \
             is disabled"
                .into(),
        )),
        Some(Ok(Some(other))) if other.chain_claim() == found.chain_claim() => Ok(Some(found)),
        Some(Ok(Some(other))) => Err(ChiaQueryError::SourcesDisagree(format!(
            "a peer claims `{}`, the coinset API claims `{}`",
            found.chain_claim(),
            other.chain_claim()
        ))),
        Some(Ok(None)) => Err(ChiaQueryError::SourcesDisagree(
            "a peer reports present, the coinset API reports absent".into(),
        )),
        Some(Err(e)) => Err(ChiaQueryError::UncorroboratedPresence(format!(
            "one peer produced a record and the coinset API could not corroborate it: {e}"
        ))),
    }
}

pub struct QueryRouter {
    /// The peer tier, SHARED.
    ///
    /// Held behind an `Arc` so a [`ChiaLightClient`](crate::peer::ChiaLightClient) built from the
    /// same client borrows this pool rather than dialling one of its own — the unification
    /// dig_ecosystem#2761 exists to make. Two pools would mean two peaks and two sets of held
    /// peers inside one process, which is the state this replaces.
    pub(crate) peer: Arc<PeerBackend>,
    pub(crate) coinset: CoinsetClient,
    pub(crate) coinset_fallback_enabled: bool,
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

impl QueryRouter {
    /// Try `peer_fn` twice (each call will select a different peer because the
    /// first failure ejects the peer).  If both fail, fall back to `coinset_fn`.
    async fn peer_then_coinset<T>(
        &self,
        peer_fn: impl std::future::Future<Output = Result<T, ChiaQueryError>>,
        peer_retry: impl std::future::Future<Output = Result<T, ChiaQueryError>>,
        coinset_fn: impl std::future::Future<Output = Result<T, ChiaQueryError>>,
    ) -> Result<T, ChiaQueryError> {
        // First peer attempt
        match peer_fn.await {
            Ok(v) => return Ok(v),
            Err(e) => log::debug!("peer attempt 1 failed: {e}"),
        }

        // Retry on a different peer
        match peer_retry.await {
            Ok(v) => Ok(v),
            Err(peer_err) => {
                if !self.coinset_fallback_enabled {
                    return Err(peer_err);
                }
                // Fall back to coinset
                coinset_fn
                    .await
                    .map_err(|ce| ChiaQueryError::AllSourcesFailed {
                        peer_error: Box::new(peer_err),
                        coinset_error: Some(Box::new(ce)),
                    })
            }
        }
    }

    /// Absence-aware variant of [`peer_then_coinset`](Self::peer_then_coinset).
    ///
    /// `Ok(None)` from this router means **corroborated absence**: two independent sources were
    /// asked and both said the thing does not exist. Absence that only one source will vouch for
    /// is [`UncorroboratedAbsence`](ChiaQueryError::UncorroboratedAbsence) — an error, because a
    /// caller reading `None` as "the chain provably does not have this" would otherwise be told a
    /// falsehood by one anonymous peer's empty list (dig_ecosystem#2456).
    ///
    /// The peer tier grades its own answer (see
    /// [`PeerBackend::read_opt_corroborated`](crate::peer::PeerBackend)); this method decides what
    /// an ungraded absence becomes once the coinset tier is available to be a second voice:
    ///
    /// | peer tier | coinset | result |
    /// |---|---|---|
    /// | found | not asked | `Ok(Some)` — presence is self-verifying |
    /// | both peers absent | not asked | `Ok(None)` |
    /// | one peer absent | absent | `Ok(None)` — two independent sources agree |
    /// | one peer absent | found | [`SourcesDisagree`](ChiaQueryError::SourcesDisagree) |
    /// | one peer absent | unreachable or disabled | [`UncorroboratedAbsence`](ChiaQueryError::UncorroboratedAbsence) |
    /// | peer read failed | any | the retry, then the coinset fallback, as before |
    ///
    /// **The stated limit.** When no peer answers at all, the coinset tier is the only source
    /// there is, and its absence is returned as `Ok(None)` on its own — the behaviour a
    /// coinset-only client has always had. That is one source, so it is one source's word; what
    /// this method removes is absence resting on an *anonymous, unauthenticated* peer, not the
    /// weaker claim that a single named HTTPS endpoint is infallible.
    async fn peer_then_coinset_opt<T: ChainClaim>(
        &self,
        peer_fn: impl std::future::Future<Output = Result<OptAnswer<T>, ChiaQueryError>>,
        peer_retry: impl std::future::Future<Output = Result<OptAnswer<T>, ChiaQueryError>>,
        coinset_fn: impl std::future::Future<Output = Result<Option<T>, ChiaQueryError>>,
    ) -> Result<Option<T>, ChiaQueryError> {
        let first = match peer_fn.await {
            Ok(answer) => Some(answer),
            Err(e) => {
                log::debug!("peer opt attempt 1 failed: {e}");
                None
            }
        };

        if let Some(answer) = first {
            return self.settle_peer_answer(answer, coinset_fn).await;
        }

        match peer_retry.await {
            Ok(answer) => self.settle_peer_answer(answer, coinset_fn).await,
            Err(peer_err) => {
                if !self.coinset_fallback_enabled {
                    return Err(peer_err);
                }
                coinset_fn
                    .await
                    .map_err(|ce| ChiaQueryError::AllSourcesFailed {
                        peer_error: Box::new(peer_err),
                        coinset_error: Some(Box::new(ce)),
                    })
            }
        }
    }

    /// Turn the peer tier's graded answer into the router's contract, consulting coinset as a
    /// second voice when — and only when — the peer tier could not find one itself.
    async fn settle_peer_answer<T: ChainClaim>(
        &self,
        answer: OptAnswer<T>,
        coinset_fn: impl std::future::Future<Output = Result<Option<T>, ChiaQueryError>>,
    ) -> Result<Option<T>, ChiaQueryError> {
        match answer {
            OptAnswer::Found(v) => Ok(Some(v)),
            OptAnswer::CorroboratedAbsent => Ok(None),
            OptAnswer::UncorroboratedFound(v) => {
                let coinset = if self.coinset_fallback_enabled {
                    Some(coinset_fn.await)
                } else {
                    None
                };
                settle_uncorroborated_presence(v, coinset)
            }
            OptAnswer::UncorroboratedAbsent => {
                let coinset = if self.coinset_fallback_enabled {
                    Some(coinset_fn.await)
                } else {
                    None
                };
                settle_uncorroborated_absence(coinset)
            }
        }
    }

    /// For endpoints that have no peer protocol equivalent.
    fn require_coinset(&self, endpoint: &str) -> Result<(), ChiaQueryError> {
        if !self.coinset_fallback_enabled {
            Err(ChiaQueryError::UnsupportedWithoutCoinset(endpoint.into()))
        } else {
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// Blocks (all coinset-only)
// ---------------------------------------------------------------------------

impl QueryRouter {
    /// Peer-backed: fetches the full block by header_hash (via coinset to
    /// resolve the height), then parses additions/removals from the CLVM
    /// generator.  Falls back to the coinset endpoint on failure.
    pub async fn get_additions_and_removals(
        &self,
        header_hash: &str,
    ) -> Result<AdditionsAndRemovals, ChiaQueryError> {
        // The peer protocol needs a height.  Resolve it from the block record.
        if let Ok(record) = self.get_block_record(header_hash).await {
            // Try parsing via peer + CLVM.
            match self
                .peer
                .try_get_additions_and_removals_from_block(record.height)
                .await
            {
                Ok(r) => return Ok(r),
                Err(e) => log::debug!("peer additions_and_removals failed: {e}"),
            }
        }
        // Fallback to coinset.
        if self.coinset_fallback_enabled {
            self.coinset.get_additions_and_removals(header_hash).await
        } else {
            Err(ChiaQueryError::UnsupportedWithoutCoinset(
                "get_additions_and_removals".into(),
            ))
        }
    }

    pub async fn get_block(&self, header_hash: &str) -> Result<FullBlock, ChiaQueryError> {
        // Resolve height from block record, try peer first.
        if let Ok(record) = self.get_block_record(header_hash).await {
            match self.peer.try_get_block_by_height(record.height).await {
                Ok(b) => return Ok(b),
                Err(e) => log::debug!("peer get_block failed: {e}"),
            }
        }
        if self.coinset_fallback_enabled {
            self.coinset.get_block(header_hash).await
        } else {
            Err(ChiaQueryError::UnsupportedWithoutCoinset(
                "get_block".into(),
            ))
        }
    }

    /// Fetch a full block by height.  Peer-backed via `RequestBlock`.
    pub async fn get_block_by_height(&self, height: u32) -> Result<FullBlock, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_block_by_height(height),
            self.peer.try_get_block_by_height(height),
            async {
                // Coinset has no direct by-height endpoint for full blocks, so
                // resolve the header_hash first.
                let record = self.coinset.get_block_record_by_height(height).await?;
                self.coinset.get_block(&record.header_hash).await
            },
        )
        .await
    }

    pub async fn get_block_count_metrics(&self) -> Result<BlockCountMetrics, ChiaQueryError> {
        self.require_coinset("get_block_count_metrics")?;
        self.coinset.get_block_count_metrics().await
    }

    pub async fn get_block_record(&self, header_hash: &str) -> Result<BlockRecord, ChiaQueryError> {
        self.require_coinset("get_block_record")?;
        self.coinset.get_block_record(header_hash).await
    }

    /// Peer-backed via `RequestBlockHeader` / `RespondBlockHeader` (pattern
    /// from chia-block-listener).
    pub async fn get_block_record_by_height(
        &self,
        height: u32,
    ) -> Result<BlockRecord, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_block_record_by_height(height),
            self.peer.try_get_block_record_by_height(height),
            self.coinset.get_block_record_by_height(height),
        )
        .await
    }

    pub async fn get_block_records(
        &self,
        start: u32,
        end: u32,
    ) -> Result<Vec<BlockRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_block_records(start, end),
            self.peer.try_get_block_records(start, end),
            self.coinset.get_block_records(start, end),
        )
        .await
    }

    /// Peer-backed: fetches the full block, then runs the CLVM generator to
    /// extract every coin spend with its puzzle_reveal and solution.
    pub async fn get_block_spends(
        &self,
        header_hash: &str,
    ) -> Result<Vec<CoinSpend>, ChiaQueryError> {
        // Resolve height from block record.
        if let Ok(record) = self.get_block_record(header_hash).await {
            match self
                .peer
                .try_get_block_spends_by_height(record.height)
                .await
            {
                Ok(r) => return Ok(r),
                Err(e) => log::debug!("peer block_spends failed: {e}"),
            }
        }
        if self.coinset_fallback_enabled {
            self.coinset.get_block_spends(header_hash).await
        } else {
            Err(ChiaQueryError::UnsupportedWithoutCoinset(
                "get_block_spends".into(),
            ))
        }
    }

    /// Peer-backed: fetches full block, runs CLVM generator, then runs each
    /// puzzle(solution) to extract parsed conditions.
    pub async fn get_block_spends_with_conditions(
        &self,
        header_hash: &str,
    ) -> Result<Vec<CoinSpendWithConditions>, ChiaQueryError> {
        if let Ok(record) = self.get_block_record(header_hash).await {
            match self
                .peer
                .try_get_block_spends_with_conditions(record.height)
                .await
            {
                Ok(r) => return Ok(r),
                Err(e) => log::debug!("peer block_spends_with_conditions failed: {e}"),
            }
        }
        if self.coinset_fallback_enabled {
            self.coinset
                .get_block_spends_with_conditions(header_hash)
                .await
        } else {
            Err(ChiaQueryError::UnsupportedWithoutCoinset(
                "get_block_spends_with_conditions".into(),
            ))
        }
    }

    pub async fn get_blocks(
        &self,
        start: u32,
        end: u32,
        exclude_header_hash: bool,
        exclude_reorged: bool,
    ) -> Result<Vec<FullBlock>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_blocks_range(start, end),
            self.peer.try_get_blocks_range(start, end),
            self.coinset
                .get_blocks(start, end, exclude_header_hash, exclude_reorged),
        )
        .await
    }

    pub async fn get_unfinished_block_headers(
        &self,
    ) -> Result<Vec<UnfinishedBlockHeader>, ChiaQueryError> {
        self.require_coinset("get_unfinished_block_headers")?;
        self.coinset.get_unfinished_block_headers().await
    }
}

// ---------------------------------------------------------------------------
// Coins (peer-backed with coinset fallback)
// ---------------------------------------------------------------------------

impl QueryRouter {
    pub async fn get_coin_record_by_name(&self, name: &str) -> Result<CoinRecord, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_record_by_name(name),
            self.peer.try_get_coin_record_by_name(name),
            self.coinset.get_coin_record_by_name(name),
        )
        .await
    }

    /// Absence-aware [`get_coin_record_by_name`](Self::get_coin_record_by_name): a PROVABLE absence
    /// is `Ok(None)`, every transport/rejection/parse failure is `Err`. A successful peer or coinset
    /// response that reports no such coin is the authoritative absence; only when the peer read
    /// itself fails does the router fall back to coinset (SPEC §3).
    pub async fn get_coin_record_by_name_opt(
        &self,
        name: &str,
    ) -> Result<Option<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset_opt(
            self.peer.try_get_coin_record_by_name_opt(name),
            self.peer.try_get_coin_record_by_name_opt(name),
            self.coinset.get_coin_record_by_name_opt(name),
        )
        .await
    }

    /// Absence-aware read of the spend that spent `coin_id`: `Ok(None)` when the coin is provably
    /// unspent/unknown, `Err` when the read could not be completed.
    pub async fn get_coin_spend_opt(
        &self,
        coin_id: &str,
    ) -> Result<Option<CoinSpend>, ChiaQueryError> {
        self.peer_then_coinset_opt(
            self.peer.try_get_coin_spend_opt(coin_id),
            self.peer.try_get_coin_spend_opt(coin_id),
            self.coinset.get_puzzle_and_solution_opt(coin_id, None),
        )
        .await
    }

    /// The current peak height, or `Ok(None)` when no source exposes a peak; `Err` on failure.
    pub async fn peak_height_opt(&self) -> Result<Option<u32>, ChiaQueryError> {
        let state = self.get_blockchain_state().await?;
        Ok(state.peak.map(|p| p.height))
    }

    /// The Unix timestamp of the block at `height`: `Ok(None)` when no such block exists or the
    /// block carries no timestamp; `Err` on failure.
    pub async fn block_timestamp_opt(&self, height: u32) -> Result<Option<u64>, ChiaQueryError> {
        let record = self.get_block_record_by_height_opt(height).await?;
        Ok(record.and_then(|r| r.timestamp))
    }

    /// Absence-aware block-record read used by [`block_timestamp_opt`](Self::block_timestamp_opt).
    async fn get_block_record_by_height_opt(
        &self,
        height: u32,
    ) -> Result<Option<BlockRecord>, ChiaQueryError> {
        // NOT corroborated, and deliberately narrower than the rest of this crate: a successful
        // peer read is taken on ONE peer's word here, and only a peer FAILURE falls through to
        // coinset, whose null block_record is provable absence. Corroboration currently covers the
        // two absence-aware coin reads only (`read_opt_corroborated`); this endpoint, the
        // puzzle-hash / hint / names reads and `try_get_puzzle_and_solution` are still
        // single-peer and UNGRADED (dig_ecosystem#2761).
        if let Ok(record) = self.peer.try_get_block_record_by_height(height).await {
            return Ok(Some(record));
        }
        match self.peer.try_get_block_record_by_height(height).await {
            Ok(record) => Ok(Some(record)),
            Err(peer_err) => {
                if self.coinset_fallback_enabled {
                    self.coinset
                        .get_block_record_by_height_opt(height)
                        .await
                        .map_err(|ce| ChiaQueryError::AllSourcesFailed {
                            peer_error: Box::new(peer_err),
                            coinset_error: Some(Box::new(ce)),
                        })
                } else {
                    Err(peer_err)
                }
            }
        }
    }

    pub async fn get_coin_records_by_hint(
        &self,
        hint: &str,
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_records_by_hint(
                hint,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.peer.try_get_coin_records_by_hint(
                hint,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.coinset.get_coin_records_by_hint(
                hint,
                start_height,
                end_height,
                include_spent_coins,
            ),
        )
        .await
    }

    pub async fn get_coin_records_by_hints(
        &self,
        hints: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_records_by_hints(
                hints,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.peer.try_get_coin_records_by_hints(
                hints,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.coinset.get_coin_records_by_hints(
                hints,
                start_height,
                end_height,
                include_spent_coins,
            ),
        )
        .await
    }

    pub async fn get_coin_records_by_names(
        &self,
        names: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_records_by_names(names),
            self.peer.try_get_coin_records_by_names(names),
            self.coinset.get_coin_records_by_names(
                names,
                start_height,
                end_height,
                include_spent_coins,
            ),
        )
        .await
    }

    /// Peer-backed via `RequestChildren` / `RespondChildren` which returns
    /// child coin states for a given parent coin ID.  Falls back to coinset
    /// for batched queries or when peers fail.
    pub async fn get_coin_records_by_parent_ids(
        &self,
        parent_ids: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        // Try peer: query each parent ID via RequestChildren, combine results.
        let peer_attempt = async {
            let mut all_records = Vec::new();
            for parent_id in parent_ids {
                let children = self.peer.try_get_children(parent_id).await?;
                all_records.extend(children);
            }
            // Apply client-side height and spent filters.
            all_records.retain(|r| {
                let height_ok = match (start_height, end_height) {
                    (Some(s), Some(e)) => {
                        r.confirmed_block_index >= s && r.confirmed_block_index <= e
                    }
                    (Some(s), None) => r.confirmed_block_index >= s,
                    (None, Some(e)) => r.confirmed_block_index <= e,
                    (None, None) => true,
                };
                let spent_ok = include_spent_coins || !r.spent;
                height_ok && spent_ok
            });
            Ok(all_records)
        };

        match peer_attempt.await {
            Ok(r) => Ok(r),
            Err(peer_err) => {
                if self.coinset_fallback_enabled {
                    self.coinset
                        .get_coin_records_by_parent_ids(
                            parent_ids,
                            start_height,
                            end_height,
                            include_spent_coins,
                        )
                        .await
                        .map_err(|ce| ChiaQueryError::AllSourcesFailed {
                            peer_error: Box::new(peer_err),
                            coinset_error: Some(Box::new(ce)),
                        })
                } else {
                    Err(peer_err)
                }
            }
        }
    }

    pub async fn get_coin_records_by_puzzle_hash(
        &self,
        puzzle_hash: &str,
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_records_by_puzzle_hash(
                puzzle_hash,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.peer.try_get_coin_records_by_puzzle_hash(
                puzzle_hash,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.coinset.get_coin_records_by_puzzle_hash(
                puzzle_hash,
                start_height,
                end_height,
                include_spent_coins,
            ),
        )
        .await
    }

    pub async fn get_coin_records_by_puzzle_hashes(
        &self,
        puzzle_hashes: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_get_coin_records_by_puzzle_hashes(
                puzzle_hashes,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.peer.try_get_coin_records_by_puzzle_hashes(
                puzzle_hashes,
                start_height,
                end_height,
                include_spent_coins,
            ),
            self.coinset.get_coin_records_by_puzzle_hashes(
                puzzle_hashes,
                start_height,
                end_height,
                include_spent_coins,
            ),
        )
        .await
    }

    /// No peer equivalent -- always coinset.
    pub async fn get_memos_by_coin_name(&self, name: &str) -> Result<Value, ChiaQueryError> {
        self.require_coinset("get_memos_by_coin_name")?;
        self.coinset.get_memos_by_coin_name(name).await
    }

    pub async fn get_puzzle_and_solution(
        &self,
        coin_id: &str,
        height: Option<u32>,
    ) -> Result<CoinSpend, ChiaQueryError> {
        if let Some(h) = height {
            self.peer_then_coinset(
                self.peer.try_get_puzzle_and_solution(coin_id, h),
                self.peer.try_get_puzzle_and_solution(coin_id, h),
                self.coinset.get_puzzle_and_solution(coin_id, height),
            )
            .await
        } else {
            // No height provided -- peer can resolve it via coin state.
            self.peer_then_coinset(
                self.peer.try_get_puzzle_and_solution_auto(coin_id),
                self.peer.try_get_puzzle_and_solution_auto(coin_id),
                self.coinset.get_puzzle_and_solution(coin_id, None),
            )
            .await
        }
    }

    /// Peer-backed: get puzzle & solution, then run puzzle(solution) to extract
    /// parsed conditions.
    pub async fn get_puzzle_and_solution_with_conditions(
        &self,
        coin_id: &str,
        height: Option<u32>,
    ) -> Result<CoinSpendWithConditions, ChiaQueryError> {
        // Try to get the spend via peer first.
        let spend = match self.get_puzzle_and_solution(coin_id, height).await {
            Ok(s) => s,
            Err(_) => {
                if self.coinset_fallback_enabled {
                    return self
                        .coinset
                        .get_puzzle_and_solution_with_conditions(coin_id, height)
                        .await;
                }
                return Err(ChiaQueryError::PeerRejection(
                    "could not retrieve puzzle and solution".into(),
                ));
            }
        };

        // Run puzzle(solution) to extract conditions.
        let conditions = run_puzzle_conditions(&spend, self.peer.constants());
        Ok(CoinSpendWithConditions {
            coin_spend: spend,
            conditions,
        })
    }

    pub async fn push_tx(&self, bundle: &SpendBundle) -> Result<TxStatus, ChiaQueryError> {
        self.peer_then_coinset(
            self.peer.try_push_tx(bundle),
            self.peer.try_push_tx(bundle),
            self.coinset.push_tx(bundle),
        )
        .await
    }
}

// ---------------------------------------------------------------------------
// Fees (peer-backed with coinset fallback)
// ---------------------------------------------------------------------------

impl QueryRouter {
    pub async fn get_fee_estimate(
        &self,
        spend_bundle: Option<&SpendBundle>,
        target_times: Option<&[u64]>,
        spend_count: Option<u64>,
    ) -> Result<FeeEstimate, ChiaQueryError> {
        let times = target_times.unwrap_or(&[60, 120, 300]);
        self.peer_then_coinset(
            self.peer.try_get_fee_estimate(times),
            self.peer.try_get_fee_estimate(times),
            self.coinset
                .get_fee_estimate(spend_bundle, target_times, spend_count),
        )
        .await
    }
}

// ---------------------------------------------------------------------------
// Full node / network (all coinset-only)
// ---------------------------------------------------------------------------

impl QueryRouter {
    /// Peer-backed: derived from the chia consensus constants for the
    /// configured network.
    pub async fn get_aggsig_additional_data(&self) -> Result<String, ChiaQueryError> {
        Ok(self.peer.aggsig_additional_data())
    }

    /// Peer-backed: derived from the chia consensus constants for the
    /// configured network.
    pub async fn get_network_info(&self) -> Result<NetworkInfo, ChiaQueryError> {
        Ok(self.peer.network_info())
    }

    /// Peer-backed partially: peak height is tracked from `NewPeakWallet`
    /// messages received from peers.  Full state comes from coinset.
    pub async fn get_blockchain_state(&self) -> Result<BlockchainState, ChiaQueryError> {
        // Try coinset first for full state.
        if self.coinset_fallback_enabled {
            if let Ok(state) = self.coinset.get_blockchain_state().await {
                return Ok(state);
            }
        }
        // Fallback: return a minimal state from the peer-tracked peak.
        let peak = self.peer.peak_height();
        if peak == 0 {
            return Err(ChiaQueryError::PeerConnection(
                "no peak observed from peers yet".into(),
            ));
        }
        Ok(BlockchainState {
            peak: Some(BlockRecord {
                height: peak,
                ..Default::default()
            }),
            sync: Some(SyncState {
                synced: true,
                sync_mode: false,
                sync_progress_height: peak,
                sync_tip_height: peak,
            }),
            ..Default::default()
        })
    }

    pub async fn get_network_space(
        &self,
        newer_block_header_hash: &str,
        older_block_header_hash: &str,
    ) -> Result<u64, ChiaQueryError> {
        self.require_coinset("get_network_space")?;
        self.coinset
            .get_network_space(newer_block_header_hash, older_block_header_hash)
            .await
    }
}

// ---------------------------------------------------------------------------
// Mempool (all coinset-only)
// ---------------------------------------------------------------------------

impl QueryRouter {
    pub async fn get_all_mempool_items(
        &self,
    ) -> Result<HashMap<String, MempoolItem>, ChiaQueryError> {
        self.require_coinset("get_all_mempool_items")?;
        self.coinset.get_all_mempool_items().await
    }

    pub async fn get_all_mempool_tx_ids(&self) -> Result<Vec<String>, ChiaQueryError> {
        self.require_coinset("get_all_mempool_tx_ids")?;
        self.coinset.get_all_mempool_tx_ids().await
    }

    pub async fn get_mempool_item_by_tx_id(
        &self,
        tx_id: &str,
    ) -> Result<MempoolItem, ChiaQueryError> {
        self.require_coinset("get_mempool_item_by_tx_id")?;
        self.coinset.get_mempool_item_by_tx_id(tx_id).await
    }

    pub async fn get_mempool_items_by_coin_name(
        &self,
        coin_name: &str,
        include_spent_coins: Option<bool>,
    ) -> Result<Vec<MempoolItem>, ChiaQueryError> {
        self.require_coinset("get_mempool_items_by_coin_name")?;
        self.coinset
            .get_mempool_items_by_coin_name(coin_name, include_spent_coins)
            .await
    }
}