Skip to main content

dig_rpc_types/
types.rs

1//! Request/response wire types for every DIG-node RPC method.
2//!
3//! Each type is `serde`-derived and models a method's params or result
4//! field-for-field with the canonical implementation (the digstore `dig-node`
5//! crate). Fields that appear only in one profile or only on the first window of
6//! a paged stream are `Option` and doc-flagged.
7//!
8//! Hex-encoded identifiers (`store_id`, `root`, `retrieval_key`, `peer_id`) are
9//! carried as `String` on the wire — lower-case 64-hex — because the interface
10//! crate does no crypto and imposes no byte-array dependency. Callers validate
11//! length/charset at their boundary.
12//!
13//! # Two content profiles, one chunk type
14//!
15//! [`ContentChunk`] models both the node profile (`dig.getContent` on the local
16//! dig-node) and the network profile (`rpc.dig.net`). The network-profile-only
17//! fields — [`total_length`](ContentChunk::total_length),
18//! [`length`](ContentChunk::length), [`program_hash`](ContentChunk::program_hash),
19//! [`offset`](ContentChunk::offset) — are `Option` so one type serves both
20//! surfaces with no silent split.
21
22use serde::{Deserialize, Serialize};
23
24/// A lower-case 64-hex identifier on the wire (e.g. a `store_id`, `root`,
25/// `retrieval_key`, or `peer_id`). A type alias for documentation; validation is
26/// the boundary's job.
27pub type HexId = String;
28
29// ===========================================================================
30// Shared value objects
31// ===========================================================================
32
33/// A peer's dialable network endpoint.
34///
35/// IPv6-first per the ecosystem networking rule: an address list orders
36/// global-unicast IPv6 ahead of IPv4 fallback, and a wildcard bind
37/// (`[::]`/`0.0.0.0`) is never advertised.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
40pub struct PeerAddress {
41    /// The host — an IPv6 or IPv4 literal (never a wildcard).
42    pub host: String,
43    /// The TCP port.
44    pub port: u16,
45    /// How the address was discovered: `direct`, `reflexive`, `mapped`, or
46    /// `relay`.
47    pub kind: String,
48}
49
50/// A content provider: a holder's stable `peer_id` plus its candidate addresses.
51///
52/// The address list is byte-compatible with [`dig.getPeers`](crate::method::Method::GetPeers)
53/// and the DHT provider shape.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
56pub struct Provider {
57    /// The holder's stable `peer_id` = `SHA-256(TLS SPKI DER)`, 64-hex.
58    pub peer_id: HexId,
59    /// The holder's candidate addresses (IPv6-first).
60    pub addresses: Vec<PeerAddress>,
61}
62
63/// The content item a redirect points at: `store_id` [+ `root` [+
64/// `retrieval_key`]], each lower-case 64-hex — the exact item to re-request.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
66#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
67pub struct ContentRef {
68    /// The store launcher id (always present).
69    pub store_id: HexId,
70    /// The generation root (present for capsule/resource granularity).
71    #[serde(skip_serializing_if = "Option::is_none", default)]
72    pub root: Option<HexId>,
73    /// The resource retrieval key (present for resource granularity).
74    #[serde(skip_serializing_if = "Option::is_none", default)]
75    pub retrieval_key: Option<HexId>,
76}
77
78/// The `error.data.redirect` payload of a
79/// [`ContentRedirect`](crate::error::ErrorCode::ContentRedirect) (`-32008`).
80///
81/// The node does not hold the content but located peers that do; the caller
82/// re-requests against one of `providers`, echoing `redirect_depth` in its
83/// params so the hop budget stays bounded (stop at `max_redirects`).
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
86pub struct RedirectInfo {
87    /// The content the caller should re-request.
88    pub content: ContentRef,
89    /// The holders (peer_id + candidate addresses) to re-request against.
90    pub providers: Vec<Provider>,
91    /// The hop count the caller must echo on its re-request.
92    pub redirect_depth: u64,
93    /// The redirect budget — stop redirecting when `redirect_depth` reaches this.
94    pub max_redirects: u64,
95}
96
97// ===========================================================================
98// dig.getContent  (PUBLIC-READ, also peer-reachable)
99// ===========================================================================
100
101/// Params for [`dig.getContent`](crate::method::Method::GetContent) — a verified
102/// resource-window read.
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
105pub struct GetContentParams {
106    /// The CHIP-0035 singleton launcher id (64-hex).
107    pub store_id: HexId,
108    /// `SHA-256(urn)` — the only URN-derived value sent to a node (64-hex).
109    pub retrieval_key: HexId,
110    /// The generation root (64-hex). Empty / `"latest"` / absent ⇒ resolve the
111    /// chain tip.
112    #[serde(skip_serializing_if = "Option::is_none", default)]
113    pub root: Option<HexId>,
114    /// The window start offset (default 0).
115    #[serde(skip_serializing_if = "Option::is_none", default)]
116    pub offset: Option<u64>,
117    /// Retrieval mode: `"speed"` (default) or `"privacy"` (onion — target).
118    #[serde(skip_serializing_if = "Option::is_none", default)]
119    pub mode: Option<String>,
120    /// The redirect budget already consumed (echoed from a `-32008` redirect).
121    #[serde(skip_serializing_if = "Option::is_none", default)]
122    pub redirect_depth: Option<u64>,
123}
124
125/// One window of a resource's ciphertext — the chunk wire object.
126///
127/// Serves BOTH the node profile (`dig.getContent` on the local dig-node) and the
128/// network profile (`rpc.dig.net`). Node-profile responses omit the
129/// network-profile-only fields; the doc on each field says which profile
130/// populates it.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
133pub struct ContentChunk {
134    /// This window's bytes, base64. Both profiles.
135    pub ciphertext: String,
136    /// The resolved generation root (64-hex). Both profiles.
137    pub root: HexId,
138    /// Whether this window ends the resource. Both profiles.
139    pub complete: bool,
140    /// The next offset; present iff not complete. Both profiles.
141    #[serde(skip_serializing_if = "Option::is_none", default)]
142    pub next_offset: Option<u64>,
143    /// Whole-resource merkle proof, base64. First window only (`offset == 0`).
144    /// Both profiles.
145    #[serde(skip_serializing_if = "Option::is_none", default)]
146    pub inclusion_proof: Option<String>,
147    /// Per-chunk ciphertext lengths of the full resource. First window only;
148    /// empty ⇒ single chunk. Both profiles.
149    #[serde(skip_serializing_if = "Option::is_none", default)]
150    pub chunk_lens: Option<Vec<u64>>,
151    /// Where the window was served from: `"local"` (this device's cache) or
152    /// `"remote"` (freshly fetched). **Node profile only** — additive tag the
153    /// in-process node sets; absent on the network profile.
154    #[serde(skip_serializing_if = "Option::is_none", default)]
155    pub source: Option<String>,
156    /// The full resource ciphertext length (pre-windowing). **Network profile
157    /// only.**
158    #[serde(skip_serializing_if = "Option::is_none", default)]
159    pub total_length: Option<u64>,
160    /// This window's byte length. **Network profile only** (the node profile's
161    /// length is implicit in `ciphertext`).
162    #[serde(skip_serializing_if = "Option::is_none", default)]
163    pub length: Option<u64>,
164    /// The window start offset (echoed). **Network profile only.**
165    #[serde(skip_serializing_if = "Option::is_none", default)]
166    pub offset: Option<u64>,
167    /// `SHA-256(.dig bytes)` — the on-chain program identity (64-hex).
168    /// **Network profile only.**
169    #[serde(skip_serializing_if = "Option::is_none", default)]
170    pub program_hash: Option<HexId>,
171}
172
173// ===========================================================================
174// dig.getAnchoredRoot  (PUBLIC-READ, also peer-reachable)
175// ===========================================================================
176
177/// Params for [`dig.getAnchoredRoot`](crate::method::Method::GetAnchoredRoot).
178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
179#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
180pub struct GetAnchoredRootParams {
181    /// The store launcher id (64-hex).
182    pub store_id: HexId,
183}
184
185/// Result for [`dig.getAnchoredRoot`](crate::method::Method::GetAnchoredRoot) —
186/// the store's current chain-anchored tip root.
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
189pub struct AnchoredRoot {
190    /// The store launcher id (echoed, 64-hex).
191    pub store_id: HexId,
192    /// The chain-anchored tip root (64-hex).
193    pub root: HexId,
194}
195
196// ===========================================================================
197// dig.getCollection / dig.listCollectionItems  (PUBLIC-READ, also peer)
198// ===========================================================================
199
200/// Params for [`dig.getCollection`](crate::method::Method::GetCollection).
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
203pub struct GetCollectionParams {
204    /// The NFT launcher ids to resolve. Capped at 10,000 (over-cap ⇒ `-32602`).
205    pub launcher_ids: Vec<HexId>,
206    /// The optional collection creator DID (64-hex).
207    #[serde(skip_serializing_if = "Option::is_none", default)]
208    pub did: Option<HexId>,
209}
210
211/// Result for [`dig.getCollection`](crate::method::Method::GetCollection) —
212/// collection-level facts computed from DIG's own coinset data.
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
215pub struct Collection {
216    /// The resolved creator DID (64-hex), if any.
217    #[serde(skip_serializing_if = "Option::is_none", default)]
218    pub did: Option<HexId>,
219    /// The DID declared by the caller / metadata (64-hex), if any.
220    #[serde(skip_serializing_if = "Option::is_none", default)]
221    pub declared_did: Option<HexId>,
222    /// The number of launcher ids requested.
223    pub item_count: u64,
224    /// How many resolved to live NFTs.
225    pub resolved_count: u64,
226    /// The uniform royalty in basis points, if resolvable.
227    #[serde(skip_serializing_if = "Option::is_none", default)]
228    pub royalty_basis_points: Option<u64>,
229}
230
231/// Params for
232/// [`dig.listCollectionItems`](crate::method::Method::ListCollectionItems).
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
235pub struct ListCollectionItemsParams {
236    /// The NFT launcher ids. Capped at 10,000 (over-cap ⇒ `-32602`).
237    pub launcher_ids: Vec<HexId>,
238    /// Page start (default 0).
239    #[serde(skip_serializing_if = "Option::is_none", default)]
240    pub offset: Option<u64>,
241    /// Page size (default 50, capped at 200).
242    #[serde(skip_serializing_if = "Option::is_none", default)]
243    pub limit: Option<u64>,
244}
245
246/// CHIP-0007 NFT metadata for one collection item.
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
248#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
249pub struct NftMetadata {
250    /// Edition ordinal, if any.
251    #[serde(skip_serializing_if = "Option::is_none", default)]
252    pub edition_number: Option<u64>,
253    /// Edition total, if any.
254    #[serde(skip_serializing_if = "Option::is_none", default)]
255    pub edition_total: Option<u64>,
256    /// Data URIs.
257    #[serde(default)]
258    pub data_uris: Vec<String>,
259    /// `SHA-256` of the data (64-hex), if any.
260    #[serde(skip_serializing_if = "Option::is_none", default)]
261    pub data_hash: Option<HexId>,
262    /// Metadata URIs.
263    #[serde(default)]
264    pub metadata_uris: Vec<String>,
265    /// `SHA-256` of the metadata document (64-hex), if any.
266    #[serde(skip_serializing_if = "Option::is_none", default)]
267    pub metadata_hash: Option<HexId>,
268    /// License URIs.
269    #[serde(default)]
270    pub license_uris: Vec<String>,
271    /// `SHA-256` of the license (64-hex), if any.
272    #[serde(skip_serializing_if = "Option::is_none", default)]
273    pub license_hash: Option<HexId>,
274}
275
276/// One resolved collection item — its current on-chain owner, royalty, and
277/// CHIP-0007 metadata.
278#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
279#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
280pub struct CollectionItem {
281    /// The NFT launcher id (64-hex).
282    pub launcher_id: HexId,
283    /// The current coin id (64-hex).
284    pub coin_id: HexId,
285    /// The current owner DID (64-hex), if any.
286    #[serde(skip_serializing_if = "Option::is_none", default)]
287    pub owner_did: Option<HexId>,
288    /// The royalty puzzle hash (64-hex).
289    pub royalty_puzzle_hash: HexId,
290    /// The royalty in basis points.
291    pub royalty_basis_points: u64,
292    /// The current owner puzzle hash (64-hex).
293    pub owner_puzzle_hash: HexId,
294    /// The CHIP-0007 metadata, if resolvable.
295    #[serde(skip_serializing_if = "Option::is_none", default)]
296    pub metadata: Option<NftMetadata>,
297}
298
299/// Result for
300/// [`dig.listCollectionItems`](crate::method::Method::ListCollectionItems) — a
301/// page of resolved items.
302#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
303#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
304pub struct CollectionItemsPage {
305    /// This page's items.
306    pub items: Vec<CollectionItem>,
307    /// The page start (echoed).
308    pub offset: u64,
309    /// The page size (echoed).
310    pub limit: u64,
311    /// The total item count across the whole (capped) launcher set.
312    pub total: u64,
313    /// The next page's offset, or `null` when exhausted.
314    #[serde(skip_serializing_if = "Option::is_none", default)]
315    pub next_offset: Option<u64>,
316}
317
318// ===========================================================================
319// dig.getNetworkInfo  (PEER)
320// ===========================================================================
321
322/// The node's relay reservation posture.
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
325pub struct RelayStatus {
326    /// The relay endpoint URL (e.g. `wss://relay.dig.net:9450`).
327    pub url: String,
328    /// Whether a relay reservation is currently held.
329    pub reserved: bool,
330}
331
332/// Result for [`dig.getNetworkInfo`](crate::method::Method::GetNetworkInfo) —
333/// this node's own peer-network posture.
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
335#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
336pub struct NetworkInfo {
337    /// This node's stable `peer_id` = `SHA-256(TLS SPKI DER)` (64-hex), or
338    /// `null` when no identity is configured.
339    #[serde(skip_serializing_if = "Option::is_none", default)]
340    pub peer_id: Option<HexId>,
341    /// The DIG network id (e.g. `DIG_MAINNET`).
342    pub network_id: String,
343    /// The first advertised (dialable) candidate address, `host:port`.
344    pub listen_addr: String,
345    /// The STUN-discovered reflexive address, if known.
346    #[serde(skip_serializing_if = "Option::is_none", default)]
347    pub reflexive_addr: Option<String>,
348    /// All advertised candidate addresses (IPv6-first).
349    pub candidate_addresses: Vec<String>,
350    /// Reachability posture: `"direct"` or `"relayed"`.
351    pub reachability: String,
352    /// The relay reservation posture.
353    pub relay: RelayStatus,
354}
355
356// ===========================================================================
357// dig.getPeers  (PEER)
358// ===========================================================================
359
360/// Result for [`dig.getPeers`](crate::method::Method::GetPeers) — the peers this
361/// node currently knows (peer exchange over RPC).
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
363#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
364pub struct PeersList {
365    /// The known peers (peer_id + candidate addresses).
366    pub peers: Vec<Provider>,
367}
368
369// ===========================================================================
370// dig.announce  (PEER)
371// ===========================================================================
372
373/// Params for [`dig.announce`](crate::method::Method::Announce).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
376pub struct AnnounceParams {
377    /// The announcing peer's `peer_id` (64-hex).
378    pub peer_id: HexId,
379    /// The announcing peer's candidate addresses.
380    pub addresses: Vec<PeerAddress>,
381}
382
383/// Result for [`dig.announce`](crate::method::Method::Announce).
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
385#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
386pub struct AnnounceAck {
387    /// Whether the announcement was accepted.
388    pub accepted: bool,
389    /// How many peers this node now knows.
390    pub known_peers: u64,
391}
392
393// ===========================================================================
394// dig.getAvailability  (PEER)
395// ===========================================================================
396
397/// One availability query item. Granularity is inferred from which fields are
398/// present: `store_id` only ⇒ which roots are held; `+root` ⇒ a capsule; `+root
399/// +retrieval_key` ⇒ a resource.
400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
401#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
402pub struct AvailabilityQuery {
403    /// The store launcher id (64-hex, required).
404    pub store_id: HexId,
405    /// The generation root (64-hex), for capsule/resource granularity.
406    #[serde(skip_serializing_if = "Option::is_none", default)]
407    pub root: Option<HexId>,
408    /// The resource retrieval key (64-hex), for resource granularity.
409    #[serde(skip_serializing_if = "Option::is_none", default)]
410    pub retrieval_key: Option<HexId>,
411}
412
413/// Params for [`dig.getAvailability`](crate::method::Method::GetAvailability).
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
415#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
416pub struct GetAvailabilityParams {
417    /// The items to check. Capped at 512 per batch (past-cap items are dropped).
418    pub items: Vec<AvailabilityQuery>,
419}
420
421/// One availability answer. Only the fields relevant to the query's granularity
422/// are populated.
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
424#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
425pub struct AvailabilityAnswer {
426    /// Whether this node holds the queried item.
427    pub available: bool,
428    /// The roots held (store-granularity queries only).
429    #[serde(skip_serializing_if = "Option::is_none", default)]
430    pub roots: Option<Vec<HexId>>,
431    /// The full resource ciphertext length (resource-granularity only).
432    #[serde(skip_serializing_if = "Option::is_none", default)]
433    pub total_length: Option<u64>,
434    /// The chunk count (resource-granularity only).
435    #[serde(skip_serializing_if = "Option::is_none", default)]
436    pub chunk_count: Option<u64>,
437    /// Whether the whole item is held (root/resource-granularity only).
438    #[serde(skip_serializing_if = "Option::is_none", default)]
439    pub complete: Option<bool>,
440    /// Providers that hold the item — present on a miss when holders were
441    /// located (enriched answer).
442    #[serde(skip_serializing_if = "Option::is_none", default)]
443    pub providers: Option<Vec<Provider>>,
444}
445
446/// Result for [`dig.getAvailability`](crate::method::Method::GetAvailability) —
447/// one answer per query item, in order.
448#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
449#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
450pub struct AvailabilityBatch {
451    /// The per-item answers (index-aligned to the query items served).
452    pub items: Vec<AvailabilityAnswer>,
453}
454
455// ===========================================================================
456// dig.listInventory  (PEER)
457// ===========================================================================
458
459/// Params for [`dig.listInventory`](crate::method::Method::ListInventory).
460#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
461#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
462pub struct ListInventoryParams {
463    /// The store to list roots for (64-hex). Absent ⇒ list all stores served.
464    #[serde(skip_serializing_if = "Option::is_none", default)]
465    pub store_id: Option<HexId>,
466    /// The maximum number of entries to return.
467    #[serde(skip_serializing_if = "Option::is_none", default)]
468    pub limit: Option<u64>,
469}
470
471/// Result for [`dig.listInventory`](crate::method::Method::ListInventory).
472///
473/// With a `store_id` the node returns the roots it holds for that store; without
474/// one it returns the stores it serves. `#[serde(untagged)]` keeps the wire flat
475/// (`{"roots": …}` or `{"stores": …}`).
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(untagged)]
478#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
479pub enum Inventory {
480    /// The roots held for a specific store.
481    ForStore {
482        /// The store launcher id (echoed, 64-hex).
483        store_id: HexId,
484        /// The roots this node holds for the store.
485        roots: Vec<HexId>,
486    },
487    /// The stores this node serves (no `store_id` given).
488    AllStores {
489        /// The store launcher ids served.
490        stores: Vec<HexId>,
491    },
492}
493
494// ===========================================================================
495// dig.fetchRange  (PEER)
496// ===========================================================================
497
498/// Params for [`dig.fetchRange`](crate::method::Method::FetchRange) — a single
499/// range frame of a resource this node holds.
500#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
501#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
502pub struct FetchRangeParams {
503    /// The store launcher id (64-hex, required).
504    pub store_id: HexId,
505    /// The generation root (64-hex, required for a resource fetch).
506    pub root: HexId,
507    /// `SHA-256(urn)` (64-hex, required for a resource fetch).
508    pub retrieval_key: HexId,
509    /// The range start (default 0).
510    #[serde(skip_serializing_if = "Option::is_none", default)]
511    pub offset: Option<u64>,
512    /// The range length in bytes (> 0; clamped to the window cap).
513    pub length: u64,
514    /// Whole-capsule mode (default false). Capsule range fetch is not yet
515    /// served; a `true` here yields `-32004`.
516    #[serde(skip_serializing_if = "Option::is_none", default)]
517    pub capsule: Option<bool>,
518    /// The redirect budget already consumed (echoed from a `-32008` redirect).
519    #[serde(skip_serializing_if = "Option::is_none", default)]
520    pub redirect_depth: Option<u64>,
521}
522
523/// One range frame of a resource. The first frame (`offset == 0`) carries the
524/// per-resource verification metadata; later frames carry only the window.
525#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
526#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
527pub struct RangeFrame {
528    /// The window start offset (echoed).
529    pub offset: u64,
530    /// This window's byte length.
531    pub length: u64,
532    /// This window's ciphertext, base64.
533    pub bytes: String,
534    /// Whether this frame ends the resource.
535    pub complete: bool,
536    /// The full resource ciphertext length. First frame only.
537    #[serde(skip_serializing_if = "Option::is_none", default)]
538    pub total_length: Option<u64>,
539    /// Per-chunk ciphertext lengths of the full resource. First frame only.
540    #[serde(skip_serializing_if = "Option::is_none", default)]
541    pub chunk_lens: Option<Vec<u64>>,
542    /// This frame's chunk index. First frame only (`0`).
543    #[serde(skip_serializing_if = "Option::is_none", default)]
544    pub chunk_index: Option<u64>,
545    /// Whole-resource merkle proof, base64. First frame only.
546    #[serde(skip_serializing_if = "Option::is_none", default)]
547    pub inclusion_proof: Option<String>,
548    /// The chain-anchored root (64-hex). First frame only.
549    #[serde(skip_serializing_if = "Option::is_none", default)]
550    pub root: Option<HexId>,
551}
552
553// ===========================================================================
554// dig.stage  (CONTROL — loopback / in-process only)
555// ===========================================================================
556
557/// Params for [`dig.stage`](crate::method::Method::Stage) — compile a local
558/// folder into a capsule `.dig` module in-process.
559#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
560#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
561pub struct StageParams {
562    /// The absolute path to the folder to compile.
563    pub dir: String,
564    /// The target store launcher id (64-hex). Absent ⇒ an ephemeral,
565    /// content-derived id (a preview).
566    #[serde(skip_serializing_if = "Option::is_none", default)]
567    pub store_id: Option<HexId>,
568    /// The store salt (64-hex). Present ⇒ a private store.
569    #[serde(skip_serializing_if = "Option::is_none", default)]
570    pub salt: Option<HexId>,
571    /// Optional DIGHub-style manifest metadata to embed.
572    #[serde(skip_serializing_if = "Option::is_none", default)]
573    pub metadata: Option<serde_json::Value>,
574}
575
576/// Result for [`dig.stage`](crate::method::Method::Stage) — the compiled capsule.
577#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
578#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
579pub struct StageResult {
580    /// The canonical capsule identity, `storeId:rootHash`.
581    pub capsule: String,
582    /// The store launcher id (64-hex).
583    pub store_id: HexId,
584    /// The compiled generation root (64-hex).
585    pub root: HexId,
586    /// The filesystem path to the compiled `.dig` module.
587    pub module_path: String,
588    /// The module size in bytes.
589    pub size: u64,
590    /// The `chia://storeId:rootHash/` content address.
591    #[serde(skip_serializing_if = "Option::is_none", default)]
592    pub content_address: Option<String>,
593    /// The relative paths compiled into the capsule.
594    #[serde(default)]
595    pub files: Vec<String>,
596    /// Whether this is an ephemeral preview (not advancing a real store).
597    #[serde(skip_serializing_if = "Option::is_none", default)]
598    pub ephemeral: Option<bool>,
599}
600
601// ===========================================================================
602// cache.*  (CONTROL — loopback / in-process only)
603// ===========================================================================
604
605/// Result for [`cache.getConfig`](crate::method::Method::CacheGetConfig).
606///
607/// The canonical field name for the cache path is `cache_dir` everywhere (the
608/// shell's historical `dir` is unified onto this name).
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
611pub struct CacheConfig {
612    /// The on-disk cache size cap in bytes (floored at 64 MiB).
613    pub cap_bytes: u64,
614    /// The bytes currently used.
615    pub used_bytes: u64,
616    /// The effective resolved cache directory.
617    pub cache_dir: String,
618    /// Whether that directory is the canonical shared location (vs a
619    /// process-private fallback).
620    pub shared: bool,
621}
622
623/// Params for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
625#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
626pub struct SetCapBytesParams {
627    /// The requested cap in bytes (floored at 64 MiB by the node).
628    pub cap_bytes: u64,
629}
630
631/// Result for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
633#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
634pub struct SetCapBytesResult {
635    /// The effective cap after flooring.
636    pub cap_bytes: u64,
637}
638
639/// One durable cached-module entry.
640#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
641#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
642pub struct CachedCapsule {
643    /// The canonical capsule identity, `storeId:rootHash`.
644    pub capsule: String,
645    /// The store launcher id (64-hex).
646    pub store_id: HexId,
647    /// The generation root (64-hex).
648    pub root: HexId,
649    /// The module size in bytes.
650    pub size_bytes: u64,
651    /// When the module was last used (unix ms).
652    pub last_used_unix_ms: u64,
653}
654
655/// Result for [`cache.listCached`](crate::method::Method::CacheListCached).
656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
657#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
658pub struct CachedList {
659    /// The cached capsules.
660    pub cached: Vec<CachedCapsule>,
661}
662
663/// Params for a capsule-keyed cache op
664/// ([`cache.removeCached`](crate::method::Method::CacheRemoveCached),
665/// [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache)).
666#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
667#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
668pub struct CapsuleKey {
669    /// The store launcher id (64-hex).
670    pub store_id: HexId,
671    /// The generation root (64-hex).
672    pub root: HexId,
673}
674
675/// Result for [`cache.removeCached`](crate::method::Method::CacheRemoveCached).
676#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
677#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
678pub struct RemoveCachedResult {
679    /// Whether an entry was removed.
680    pub removed: bool,
681}
682
683/// Result for [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache).
684///
685/// A failed fetch is reported in-band (`status = "failed"` + `message`) so the
686/// caller can show it without treating it as a transport error.
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
688#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
689pub struct FetchAndCacheResult {
690    /// `"cached"`, `"already_cached"`, or `"failed"`.
691    pub status: String,
692    /// The fetched module size in bytes (on success).
693    #[serde(skip_serializing_if = "Option::is_none", default)]
694    pub size_bytes: Option<u64>,
695    /// The served generation root (64-hex, on success).
696    #[serde(skip_serializing_if = "Option::is_none", default)]
697    pub served_root: Option<HexId>,
698    /// The failure message (on `status = "failed"`).
699    #[serde(skip_serializing_if = "Option::is_none", default)]
700    pub message: Option<String>,
701}
702
703// ===========================================================================
704// control.peerStatus  (CONTROL — loopback / in-process only)
705// ===========================================================================
706
707/// Result for [`control.peerStatus`](crate::method::Method::ControlPeerStatus) —
708/// a snapshot of the node's L7 peer network. Always safe to call; reports
709/// `running: false` on the FFI path.
710#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
711#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
712pub struct PeerStatusSnapshot {
713    /// Whether a peer network is currently active.
714    pub running: bool,
715    /// This node's `peer_id` (64-hex), if a peer network is running.
716    #[serde(skip_serializing_if = "Option::is_none", default)]
717    pub peer_id: Option<HexId>,
718    /// The DIG network id.
719    pub network_id: String,
720    /// The relay reservation posture.
721    pub relay: RelayStatus,
722    /// The number of currently connected peers.
723    pub connected_peers: u64,
724    /// The last peer-network error, if any.
725    #[serde(skip_serializing_if = "Option::is_none", default)]
726    pub last_error: Option<String>,
727}
728
729// ===========================================================================
730// dig.health / dig.methods / rpc.discover  (discovery)
731// ===========================================================================
732
733/// Result for [`dig.health`](crate::method::Method::Health) — liveness + a
734/// capability summary.
735#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
736#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
737pub struct Health {
738    /// Liveness — `"ok"` when the node can serve.
739    pub status: String,
740    /// The node's software version.
741    #[serde(skip_serializing_if = "Option::is_none", default)]
742    pub version: Option<String>,
743    /// The DIG network id the node serves.
744    #[serde(skip_serializing_if = "Option::is_none", default)]
745    pub network_id: Option<String>,
746    /// The method names this node implements (its profile).
747    #[serde(default)]
748    pub methods: Vec<String>,
749}
750
751/// Result for [`dig.methods`](crate::method::Method::Methods) — the method names
752/// this node implements (agent self-describe).
753#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
754#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
755pub struct Methods {
756    /// The implemented method names.
757    pub methods: Vec<String>,
758}
759
760#[cfg(test)]
761mod tests {
762    use super::*;
763
764    /// **Proves:** `ContentChunk` round-trips a node-profile window (no
765    /// network-profile fields) without inventing keys.
766    /// **Catches:** a missing `skip_serializing_if` that would leak `null`
767    /// network-profile fields onto the node profile.
768    #[test]
769    fn content_chunk_node_profile_is_lean() {
770        let c = ContentChunk {
771            ciphertext: "AAA=".into(),
772            root: "ab".repeat(32),
773            complete: false,
774            next_offset: Some(3_145_728),
775            inclusion_proof: Some("cHJvb2Y=".into()),
776            chunk_lens: Some(vec![10, 20]),
777            source: Some("local".into()),
778            total_length: None,
779            length: None,
780            offset: None,
781            program_hash: None,
782        };
783        let v = serde_json::to_value(&c).unwrap();
784        assert_eq!(v["source"], "local");
785        assert!(
786            v.get("total_length").is_none(),
787            "node profile must omit total_length"
788        );
789        assert!(v.get("program_hash").is_none());
790        assert_eq!(serde_json::from_value::<ContentChunk>(v).unwrap(), c);
791    }
792
793    /// **Proves:** the network-profile fields serialize when present.
794    #[test]
795    fn content_chunk_network_profile_carries_extras() {
796        let c = ContentChunk {
797            ciphertext: "AAA=".into(),
798            root: "cd".repeat(32),
799            complete: true,
800            next_offset: None,
801            inclusion_proof: None,
802            chunk_lens: None,
803            source: None,
804            total_length: Some(100),
805            length: Some(100),
806            offset: Some(0),
807            program_hash: Some("ef".repeat(32)),
808        };
809        let v = serde_json::to_value(&c).unwrap();
810        assert_eq!(v["total_length"], 100);
811        assert_eq!(v["length"], 100);
812        assert!(v.get("source").is_none());
813    }
814
815    /// **Proves:** the untagged `Inventory` picks `ForStore` vs `AllStores` by
816    /// shape.
817    /// **Catches:** a lost `#[serde(untagged)]` that would tag the variant.
818    #[test]
819    fn inventory_untagged_by_shape() {
820        let for_store = Inventory::ForStore {
821            store_id: "ab".repeat(32),
822            roots: vec!["cd".repeat(32)],
823        };
824        let s = serde_json::to_string(&for_store).unwrap();
825        assert!(s.contains("\"roots\""));
826        assert!(!s.contains("ForStore"));
827        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), for_store);
828
829        let all = Inventory::AllStores {
830            stores: vec!["ef".repeat(32)],
831        };
832        let s = serde_json::to_string(&all).unwrap();
833        assert!(s.contains("\"stores\""));
834        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), all);
835    }
836
837    /// **Proves:** `RedirectInfo` serializes the full redirect payload the
838    /// `-32008` envelope carries.
839    #[test]
840    fn redirect_info_shape() {
841        let r = RedirectInfo {
842            content: ContentRef {
843                store_id: "ab".repeat(32),
844                root: Some("cd".repeat(32)),
845                retrieval_key: Some("ef".repeat(32)),
846            },
847            providers: vec![Provider {
848                peer_id: "12".repeat(32),
849                addresses: vec![PeerAddress {
850                    host: "::1".into(),
851                    port: 9444,
852                    kind: "direct".into(),
853                }],
854            }],
855            redirect_depth: 1,
856            max_redirects: 4,
857        };
858        let v = serde_json::to_value(&r).unwrap();
859        assert_eq!(v["redirect_depth"], 1);
860        assert_eq!(v["max_redirects"], 4);
861        assert_eq!(v["providers"][0]["addresses"][0]["host"], "::1");
862        assert_eq!(serde_json::from_value::<RedirectInfo>(v).unwrap(), r);
863    }
864
865    /// **Proves:** `cache.getConfig` uses the canonical `cache_dir` field name.
866    /// **Catches:** a regression to the shell's historical `dir` name.
867    #[test]
868    fn cache_config_field_name_is_cache_dir() {
869        let c = CacheConfig {
870            cap_bytes: 1 << 30,
871            used_bytes: 0,
872            cache_dir: "/var/cache/dig".into(),
873            shared: true,
874        };
875        let v = serde_json::to_value(&c).unwrap();
876        assert!(v.get("cache_dir").is_some());
877        assert!(v.get("dir").is_none(), "must not use the legacy `dir` name");
878    }
879}