chia-query 0.6.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
//! # chia-query
//!
//! Query the Chia blockchain through decentralized peer connections with
//! automatic fallback to the [coinset.org](https://api.coinset.org) HTTP API.
//!
//! No Chia installation is required. The peer TLS client identity is generated in
//! memory by default ([`TlsIdentity::Generated`]), so a client works from a service
//! account with no home directory of its own.
//!
//! ```rust,no_run
//! use chia_query::{ChiaQuery, ChiaQueryConfig};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = ChiaQuery::new(ChiaQueryConfig::default()).await?;
//!     let record = client.get_coin_record_by_name("0xabc...").await?;
//!     println!("{:?}", record);
//!     Ok(())
//! }
//! ```

pub mod coinset;
pub mod drift;
pub mod types;

// The `@dignetwork/chia-query-wasm` bindings — only for the wasm coinset build.
#[cfg(all(target_arch = "wasm32", feature = "coinset", not(feature = "native")))]
pub mod wasm_api;

// The peer WebSocket backend + the routing/CLVM layer are native-only: they
// pull in `chia-wallet-sdk` (native-tls), `clvmr`, and tokio networking, none
// of which belong in the wasm coinset-only build.
#[cfg(feature = "native")]
pub mod peer;
#[cfg(feature = "native")]
pub mod provider_registry;
#[cfg(feature = "native")]
pub mod router;

pub use types::*;

// Everything below — the full `ChiaQuery` client that races peers against the
// coinset fallback — is the native surface. A wasm consumer uses
// [`coinset::CoinsetClient`] directly with an injected `fetch` transport.
#[cfg(feature = "native")]
mod native_client {
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::time::Duration;

    use serde_json::Value;

    use crate::types::*;
    use crate::{coinset, peer, router};

    // ---------------------------------------------------------------------------
    // NetworkType
    // ---------------------------------------------------------------------------

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum NetworkType {
        Mainnet,
        Testnet11,
    }

    impl NetworkType {
        pub fn network_id(self) -> &'static str {
            match self {
                Self::Mainnet => "mainnet",
                Self::Testnet11 => "testnet11",
            }
        }
    }

    // ---------------------------------------------------------------------------
    // Configuration
    // ---------------------------------------------------------------------------

    /// Where the peer-protocol TLS client identity comes from.
    ///
    /// Modelled as one choice rather than a pair of optional paths so a half-configured
    /// identity — a certificate without its key — cannot be expressed.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum TlsIdentity {
        /// Generate a fresh self-signed certificate in memory (the default).
        ///
        /// Chia full nodes accept any well-formed client certificate, so nothing is
        /// gained by requiring one on disk and a great deal is lost: a service account
        /// has no populated `~/.chia`, which is what made every balance read fail in
        /// dig_ecosystem#2210. See [`peer::connect::create_generated_tls`] for why the
        /// certificate is not persisted.
        Generated,

        /// Load an existing certificate/key pair, e.g. a real Chia node's wallet cert.
        Files {
            cert_path: PathBuf,
            key_path: PathBuf,
        },
    }

    pub struct ChiaQueryConfig {
        pub network: NetworkType,
        pub max_peers: usize,
        pub coinset_base_url: String,
        pub coinset_fallback_enabled: bool,
        pub tls_identity: TlsIdentity,
        pub peer_connect_timeout: Duration,
        pub peer_request_timeout: Duration,
        pub coinset_request_timeout: Duration,
    }

    impl Default for ChiaQueryConfig {
        fn default() -> Self {
            Self {
                network: NetworkType::Mainnet,
                max_peers: 5,
                coinset_base_url: "https://api.coinset.org".into(),
                coinset_fallback_enabled: true,
                tls_identity: TlsIdentity::Generated,
                peer_connect_timeout: Duration::from_secs(8),
                peer_request_timeout: Duration::from_secs(30),
                coinset_request_timeout: Duration::from_secs(30),
            }
        }
    }

    // ---------------------------------------------------------------------------
    // ChiaQuery -- the public entry-point
    // ---------------------------------------------------------------------------

    pub struct ChiaQuery {
        router: router::QueryRouter,
    }

    impl ChiaQuery {
        /// Create a new client.  This will:
        /// 1. Establish the peer TLS identity (generated by default — no files needed).
        /// 2. Discover peers via DNS and connect up to `max_peers` concurrently.
        /// 3. Initialise the coinset.org HTTP client.
        ///
        /// Peer discovery failing is fatal ([`ChiaQueryError::PeerDiscoveryFailed`])
        /// ONLY when the coinset fallback is disabled; with the fallback enabled the
        /// client is usable immediately and the peer pool refills in the background.
        pub async fn new(cfg: ChiaQueryConfig) -> Result<Self, ChiaQueryError> {
            let tls = match &cfg.tls_identity {
                TlsIdentity::Generated => peer::connect::create_generated_tls()?,
                TlsIdentity::Files {
                    cert_path,
                    key_path,
                } => peer::connect::create_tls(cert_path, key_path)?,
            };

            // The coinset tier is plain HTTP and needs neither a credential nor a peer,
            // so a peer-tier problem must not deny a reader the fallback that exists
            // for exactly that case (dig_ecosystem#2210).
            let peer_requirement = if cfg.coinset_fallback_enabled {
                peer::PeerRequirement::Optional
            } else {
                peer::PeerRequirement::Required
            };

            let peer_backend = peer::PeerBackend::new(
                cfg.network,
                tls,
                cfg.max_peers,
                peer_requirement,
                cfg.peer_connect_timeout,
                cfg.peer_request_timeout,
            )
            .await?;

            let coinset_client =
                coinset::CoinsetClient::new(&cfg.coinset_base_url, cfg.coinset_request_timeout)?;

            Ok(Self {
                router: router::QueryRouter {
                    peer: peer_backend,
                    coinset: coinset_client,
                    coinset_fallback_enabled: cfg.coinset_fallback_enabled,
                },
            })
        }

        // =======================================================================
        // Blocks
        // =======================================================================

        pub async fn get_additions_and_removals(
            &self,
            header_hash: &str,
        ) -> Result<AdditionsAndRemovals, ChiaQueryError> {
            self.router.get_additions_and_removals(header_hash).await
        }

        pub async fn get_block(&self, header_hash: &str) -> Result<FullBlock, ChiaQueryError> {
            self.router.get_block(header_hash).await
        }

        /// Fetch a full block by height.  Peer-backed via `RequestBlock`.
        pub async fn get_block_by_height(&self, height: u32) -> Result<FullBlock, ChiaQueryError> {
            self.router.get_block_by_height(height).await
        }

        pub async fn get_block_count_metrics(&self) -> Result<BlockCountMetrics, ChiaQueryError> {
            self.router.get_block_count_metrics().await
        }

        pub async fn get_block_record(
            &self,
            header_hash: &str,
        ) -> Result<BlockRecord, ChiaQueryError> {
            self.router.get_block_record(header_hash).await
        }

        pub async fn get_block_record_by_height(
            &self,
            height: u32,
        ) -> Result<BlockRecord, ChiaQueryError> {
            self.router.get_block_record_by_height(height).await
        }

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

        pub async fn get_block_spends(
            &self,
            header_hash: &str,
        ) -> Result<Vec<CoinSpend>, ChiaQueryError> {
            self.router.get_block_spends(header_hash).await
        }

        pub async fn get_block_spends_with_conditions(
            &self,
            header_hash: &str,
        ) -> Result<Vec<CoinSpendWithConditions>, ChiaQueryError> {
            self.router
                .get_block_spends_with_conditions(header_hash)
                .await
        }

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

        pub async fn get_unfinished_block_headers(
            &self,
        ) -> Result<Vec<UnfinishedBlockHeader>, ChiaQueryError> {
            self.router.get_unfinished_block_headers().await
        }

        // =======================================================================
        // Coins
        // =======================================================================

        pub async fn get_coin_record_by_name(
            &self,
            name: &str,
        ) -> Result<CoinRecord, ChiaQueryError> {
            self.router.get_coin_record_by_name(name).await
        }

        /// Absence-aware [`get_coin_record_by_name`](Self::get_coin_record_by_name): `Ok(None)` when
        /// the coin provably does not exist, `Err` when the read could not be completed. Used by the
        /// [`ChainSource`](dig_chainsource_interface::ChainSource) facade to honour the fail-closed
        /// `Ok(None)`-vs-`Err` contract.
        pub async fn get_coin_record_by_name_opt(
            &self,
            name: &str,
        ) -> Result<Option<CoinRecord>, ChiaQueryError> {
            self.router.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` on failure.
        pub async fn get_coin_spend_opt(
            &self,
            coin_id: &str,
        ) -> Result<Option<CoinSpend>, ChiaQueryError> {
            self.router.get_coin_spend_opt(coin_id).await
        }

        /// The current peak height (`Ok(None)` when unavailable), `Err` on failure.
        pub async fn peak_height_opt(&self) -> Result<Option<u32>, ChiaQueryError> {
            self.router.peak_height_opt().await
        }

        /// The Unix timestamp of the block at `height` (`Ok(None)` when absent), `Err` on failure.
        pub async fn block_timestamp_opt(
            &self,
            height: u32,
        ) -> Result<Option<u64>, ChiaQueryError> {
            self.router.block_timestamp_opt(height).await
        }

        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.router
                .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.router
                .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.router
                .get_coin_records_by_names(names, start_height, end_height, include_spent_coins)
                .await
        }

        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> {
            self.router
                .get_coin_records_by_parent_ids(
                    parent_ids,
                    start_height,
                    end_height,
                    include_spent_coins,
                )
                .await
        }

        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.router
                .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.router
                .get_coin_records_by_puzzle_hashes(
                    puzzle_hashes,
                    start_height,
                    end_height,
                    include_spent_coins,
                )
                .await
        }

        pub async fn get_memos_by_coin_name(&self, name: &str) -> Result<Value, ChiaQueryError> {
            self.router.get_memos_by_coin_name(name).await
        }

        pub async fn get_puzzle_and_solution(
            &self,
            coin_id: &str,
            height: Option<u32>,
        ) -> Result<CoinSpend, ChiaQueryError> {
            self.router.get_puzzle_and_solution(coin_id, height).await
        }

        pub async fn get_puzzle_and_solution_with_conditions(
            &self,
            coin_id: &str,
            height: Option<u32>,
        ) -> Result<CoinSpendWithConditions, ChiaQueryError> {
            self.router
                .get_puzzle_and_solution_with_conditions(coin_id, height)
                .await
        }

        pub async fn push_tx(
            &self,
            spend_bundle: &SpendBundle,
        ) -> Result<TxStatus, ChiaQueryError> {
            self.router.push_tx(spend_bundle).await
        }

        // =======================================================================
        // Fees
        // =======================================================================

        pub async fn get_fee_estimate(
            &self,
            spend_bundle: Option<&SpendBundle>,
            target_times: Option<&[u64]>,
            spend_count: Option<u64>,
        ) -> Result<FeeEstimate, ChiaQueryError> {
            self.router
                .get_fee_estimate(spend_bundle, target_times, spend_count)
                .await
        }

        // =======================================================================
        // Full node / network
        // =======================================================================

        pub async fn get_aggsig_additional_data(&self) -> Result<String, ChiaQueryError> {
            self.router.get_aggsig_additional_data().await
        }

        pub async fn get_network_info(&self) -> Result<NetworkInfo, ChiaQueryError> {
            self.router.get_network_info().await
        }

        pub async fn get_blockchain_state(&self) -> Result<BlockchainState, ChiaQueryError> {
            self.router.get_blockchain_state().await
        }

        pub async fn get_network_space(
            &self,
            newer_block_header_hash: &str,
            older_block_header_hash: &str,
        ) -> Result<u64, ChiaQueryError> {
            self.router
                .get_network_space(newer_block_header_hash, older_block_header_hash)
                .await
        }

        // =======================================================================
        // Mempool
        // =======================================================================

        pub async fn get_all_mempool_items(
            &self,
        ) -> Result<HashMap<String, MempoolItem>, ChiaQueryError> {
            self.router.get_all_mempool_items().await
        }

        pub async fn get_all_mempool_tx_ids(&self) -> Result<Vec<String>, ChiaQueryError> {
            self.router.get_all_mempool_tx_ids().await
        }

        pub async fn get_mempool_item_by_tx_id(
            &self,
            tx_id: &str,
        ) -> Result<MempoolItem, ChiaQueryError> {
            self.router.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.router
                .get_mempool_items_by_coin_name(coin_name, include_spent_coins)
                .await
        }

        // =======================================================================
        // Convenience helpers
        // =======================================================================

        /// Poll the blockchain until a coin appears on-chain (confirmed) or the
        /// timeout elapses.
        ///
        /// Returns the [`CoinRecord`] once the coin is found with a non-zero
        /// `confirmed_block_index`.  Returns an error if the timeout expires
        /// before the coin is confirmed.
        ///
        /// ```rust,no_run
        /// # use chia_query::{ChiaQuery, ChiaQueryConfig};
        /// # use std::time::Duration;
        /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
        /// let client = ChiaQuery::new(ChiaQueryConfig::default()).await?;
        /// let record = client.wait_for_confirmation(
        ///     "0xabc...",
        ///     Duration::from_secs(5),   // poll every 5 seconds
        ///     Duration::from_secs(300), // give up after 5 minutes
        /// ).await?;
        /// println!("confirmed at height {}", record.confirmed_block_index);
        /// # Ok(())
        /// # }
        /// ```
        pub async fn wait_for_confirmation(
            &self,
            coin_id: &str,
            poll_interval: Duration,
            timeout: Duration,
        ) -> Result<CoinRecord, ChiaQueryError> {
            let deadline = tokio::time::Instant::now() + timeout;

            loop {
                match self.get_coin_record_by_name(coin_id).await {
                    Ok(record) if record.confirmed_block_index > 0 => {
                        return Ok(record);
                    }
                    Ok(_) => {
                        // Coin exists but confirmed_block_index is 0 -- not
                        // confirmed yet, keep polling.
                    }
                    Err(ChiaQueryError::PeerRejection(_))
                    | Err(ChiaQueryError::CoinsetApiError(_)) => {
                        // Coin not found yet -- keep polling.
                    }
                    Err(e) => {
                        // Transient connection errors -- log and keep trying.
                        log::debug!("wait_for_confirmation poll error: {e}");
                    }
                }

                if tokio::time::Instant::now() + poll_interval > deadline {
                    return Err(ChiaQueryError::PeerConnection(format!(
                        "coin {coin_id} not confirmed within {timeout:?}"
                    )));
                }

                tokio::time::sleep(poll_interval).await;
            }
        }
    }
} // mod native_client

#[cfg(feature = "native")]
pub use native_client::{ChiaQuery, ChiaQueryConfig, NetworkType, TlsIdentity};