Skip to main content

dig_rpc_protocol/
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///
415/// # Construction
416///
417/// Like [`FetchRangeParams`], this type is `#[non_exhaustive]`: build it with
418/// [`new`](Self::new) plus the `with_*` setters rather than a struct literal, so a
419/// future additive field is a PATCH for every consumer instead of a semver cascade.
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
421#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
422#[non_exhaustive]
423pub struct GetAvailabilityParams {
424    /// The items to check. Capped at 512 per batch (past-cap items are dropped).
425    pub items: Vec<AvailabilityQuery>,
426    /// The hop budget already consumed by this ask. Absent means zero — read it
427    /// through [`hops_consumed`](Self::hops_consumed), never directly.
428    ///
429    /// # What it means for an availability ask
430    ///
431    /// An availability answer is not only *this* node's holdings: on a miss it may
432    /// name the holders it located, in
433    /// [`AvailabilityAnswer::providers`](AvailabilityAnswer::providers) — the same
434    /// enrichment a [`RedirectInfo`] carries. A responder that cannot answer from
435    /// what it holds MAY ask its own peers, so one caller's question can walk
436    /// several hops, and each hop is a node spending someone else's bandwidth.
437    /// This field is what bounds that walk.
438    ///
439    /// It is the SAME budget, counted the SAME way, as
440    /// [`RedirectInfo::redirect_depth`] and as the `redirect_depth` that
441    /// [`GetContentParams`] and [`FetchRangeParams`] already echo: the number of
442    /// hops ALREADY CONSUMED when this ask arrives, counting UP from zero — never a
443    /// remaining allowance counting down. A responder that asks onward sends
444    /// `hops_consumed() + 1` (saturating at the type maximum), and MUST NOT ask
445    /// onward when that would reach the budget it advertises as
446    /// [`RedirectInfo::max_redirects`].
447    ///
448    /// Absent reads as a fresh, unhopped ask, so a client written before this field
449    /// existed is served unchanged.
450    #[serde(skip_serializing_if = "Option::is_none", default)]
451    pub redirect_depth: Option<u64>,
452    /// The wall-clock TIME this ask may still spend, in milliseconds. Absent means
453    /// unbudgeted — read it through [`budget_ms`](Self::budget_ms), never directly.
454    ///
455    /// # Why this is its OWN field and not the hop budget
456    ///
457    /// [`redirect_depth`](Self::redirect_depth) counts hops UP from zero toward a
458    /// ceiling; this counts milliseconds DOWN toward zero. The two move in opposite
459    /// directions along different axes, so one integer cannot carry both, and folding
460    /// them together would make "one more hop" and "more time" the same request.
461    ///
462    /// # The contract a relaying responder MUST honour
463    ///
464    /// A responder that asks its own peers onward MUST pass a value it has decremented
465    /// by the time it has itself already spent, and it MUST NOT grant a child less time
466    /// than the work it asks that child to do. Concretely: a parent that asks `n`
467    /// children SEQUENTIALLY must divide the remaining budget between them, and a
468    /// parent with less time left than one round trip needs MUST answer
469    /// [`ContentMissInconclusive`](crate::error::ErrorCode::ContentMissInconclusive)
470    /// rather than ask onward and then time out.
471    ///
472    /// This exists because the alternative is measurable: a FIXED per-ask bound with
473    /// sequential asks and a fan-out greater than one guarantees the second hop times
474    /// out, and a responder that reads that timeout as a miss reports a CONFIDENT
475    /// not-found for content it never looked for.
476    ///
477    /// Absent reads as unbudgeted, so a client written before this field existed is
478    /// served exactly as it was.
479    #[serde(skip_serializing_if = "Option::is_none", default)]
480    pub budget_ms: Option<u64>,
481    /// An opaque identity for this ask, for cross-path dedup. Absent means the caller
482    /// opted out of dedup — read it through [`ask_id`](Self::ask_id).
483    ///
484    /// # What it is for
485    ///
486    /// A recursive ask walks a graph, not a tree. Two disjoint paths can arrive at the
487    /// same responder, and without a shared identity that responder cannot tell a
488    /// re-walk from a fresh question — so a diamond in the peer graph does not
489    /// terminate. A responder that has already seen an `ask_id` MUST answer from what
490    /// it already knows instead of asking onward again.
491    ///
492    /// # What it is NOT
493    ///
494    /// It is **not** the JSON-RPC `id`. That field correlates one request with one
495    /// response on one connection; it is chosen per-connection, is commonly a small
496    /// constant, and says nothing about whether two arrivals are the same ask. An
497    /// implementation that reused the JSON-RPC `id` for dedup would either collide
498    /// every unrelated ask together or dedup nothing at all.
499    ///
500    /// # Requirements
501    ///
502    /// 32 lowercase hex characters: **16 unpredictable random bytes**, freshly drawn
503    /// by the ORIGINATOR and copied verbatim by every relaying hop. It MUST be
504    /// unpredictable, because a value an attacker can guess lets that attacker
505    /// pre-poison a responder dedup memo and suppress an ask that has not happened
506    /// yet. A responder MUST NOT derive anything from its value beyond EQUALITY — it
507    /// carries no structure, no origin, no timestamp and no ordering.
508    #[serde(skip_serializing_if = "Option::is_none", default)]
509    pub ask_id: Option<String>,
510}
511
512impl GetAvailabilityParams {
513    /// An availability batch for `items`, asked at hop zero.
514    pub fn new(items: Vec<AvailabilityQuery>) -> Self {
515        GetAvailabilityParams {
516            items,
517            redirect_depth: None,
518            budget_ms: None,
519            ask_id: None,
520        }
521    }
522
523    /// Echo the hop budget already consumed — from a `-32008` redirect, or from the
524    /// ask this one is being made on behalf of. See
525    /// [`redirect_depth`](Self::redirect_depth).
526    pub fn with_redirect_depth(mut self, redirect_depth: u64) -> Self {
527        self.redirect_depth = Some(redirect_depth);
528        self
529    }
530
531    /// The hops already consumed by this ask.
532    ///
533    /// The single home for the "absent means zero" rule. A responder that reached for
534    /// `redirect_depth.is_some()` instead would read every pre-0.8 client's ask as
535    /// budget-free and forward it without bound — the amplification the budget exists
536    /// to stop.
537    pub fn hops_consumed(&self) -> u64 {
538        self.redirect_depth.unwrap_or(0)
539    }
540
541    /// Set the remaining time budget for this ask. See [`budget_ms`](Self::budget_ms).
542    pub fn with_budget_ms(mut self, budget_ms: u64) -> Self {
543        self.budget_ms = Some(budget_ms);
544        self
545    }
546
547    /// The time this ask may still spend, or `None` when the caller sent no budget.
548    ///
549    /// Deliberately NOT collapsed to a number, unlike
550    /// [`hops_consumed`](Self::hops_consumed): there is no safe scalar default. Zero
551    /// would refuse every older caller ask outright, and any positive default would
552    /// silently impose one node idea of patience on another node question. A responder
553    /// that receives `None` applies its OWN policy and passes on what it granted.
554    pub fn budget_ms(&self) -> Option<u64> {
555        self.budget_ms
556    }
557
558    /// Set the cross-path dedup identity. See [`ask_id`](Self::ask_id).
559    pub fn with_ask_id(mut self, ask_id: impl Into<String>) -> Self {
560        self.ask_id = Some(ask_id.into());
561        self
562    }
563
564    /// The dedup identity, or `None` when the caller opted out of dedup.
565    pub fn ask_id(&self) -> Option<&str> {
566        self.ask_id.as_deref()
567    }
568}
569
570/// One availability answer. Only the fields relevant to the query's granularity
571/// are populated.
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
573#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
574pub struct AvailabilityAnswer {
575    /// Whether this node holds the queried item.
576    pub available: bool,
577    /// The roots held (store-granularity queries only).
578    #[serde(skip_serializing_if = "Option::is_none", default)]
579    pub roots: Option<Vec<HexId>>,
580    /// The full resource ciphertext length (resource-granularity only).
581    #[serde(skip_serializing_if = "Option::is_none", default)]
582    pub total_length: Option<u64>,
583    /// The chunk count (resource-granularity only).
584    #[serde(skip_serializing_if = "Option::is_none", default)]
585    pub chunk_count: Option<u64>,
586    /// Whether the whole item is held (root/resource-granularity only).
587    #[serde(skip_serializing_if = "Option::is_none", default)]
588    pub complete: Option<bool>,
589    /// Providers that hold the item — present on a miss when holders were
590    /// located (enriched answer).
591    #[serde(skip_serializing_if = "Option::is_none", default)]
592    pub providers: Option<Vec<Provider>>,
593    /// Whether this responder actually ESTABLISHED that nobody holds the item.
594    ///
595    /// Only meaningful beside `available: false`; on a hit the item is held and there
596    /// is nothing to establish.
597    ///
598    /// # Absent is a THIRD state, not `false`
599    ///
600    /// - `Some(true)` — the responder looked, reached everything it meant to reach,
601    ///   and asserts absence. A client MAY stop searching.
602    /// - `Some(false)` — the responder looked and could NOT establish absence: a hop
603    ///   timed out, was unreachable, or refused uninformatively. A client MUST keep
604    ///   looking. This is the in-band form of
605    ///   [`ContentMissInconclusive`](crate::error::ErrorCode::ContentMissInconclusive),
606    ///   for a batch where only SOME items were inconclusive and the call itself
607    ///   therefore succeeded.
608    /// - `None` — the responder predates this field and makes NO claim either way.
609    ///   It is NOT `Some(false)`: `Some(false)` is a responder telling you its search
610    ///   was incomplete, while `None` is a responder that cannot describe its search at
611    ///   all. Conflating them lets an older server every miss be read as a positive
612    ///   report of incompleteness; conflating it the other way (`unwrap_or(true)`)
613    ///   turns an unknown into an assertion of absence. Read it through
614    ///   [`absence_established_or_unknown`](AvailabilityAnswer::absence_established_or_unknown),
615    ///   which keeps the three states distinct.
616    #[serde(skip_serializing_if = "Option::is_none", default)]
617    pub absence_established: Option<bool>,
618}
619
620impl AvailabilityAnswer {
621    /// Whether absence was established, as a THREE-state answer: `Some(true)`
622    /// asserted, `Some(false)` explicitly not established, `None` unknown because the
623    /// responder predates the field.
624    ///
625    /// A pass-through, and that is the point — it is the named home for the rule that
626    /// there is no safe collapse to `bool`. A client that wants to stop searching MUST
627    /// require `Some(true)`.
628    pub fn absence_established_or_unknown(&self) -> Option<bool> {
629        self.absence_established
630    }
631}
632
633/// Result for [`dig.getAvailability`](crate::method::Method::GetAvailability) —
634/// one answer per query item, in order.
635#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
636#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
637pub struct AvailabilityBatch {
638    /// The per-item answers (index-aligned to the query items served).
639    pub items: Vec<AvailabilityAnswer>,
640}
641
642// ===========================================================================
643// dig.listInventory  (PEER)
644// ===========================================================================
645
646/// Params for [`dig.listInventory`](crate::method::Method::ListInventory).
647#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
648#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
649pub struct ListInventoryParams {
650    /// The store to list roots for (64-hex). Absent ⇒ list all stores served.
651    #[serde(skip_serializing_if = "Option::is_none", default)]
652    pub store_id: Option<HexId>,
653    /// The maximum number of entries to return.
654    #[serde(skip_serializing_if = "Option::is_none", default)]
655    pub limit: Option<u64>,
656}
657
658/// Result for [`dig.listInventory`](crate::method::Method::ListInventory).
659///
660/// With a `store_id` the node returns the roots it holds for that store; without
661/// one it returns the stores it serves. `#[serde(untagged)]` keeps the wire flat
662/// (`{"roots": …}` or `{"stores": …}`).
663#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
664#[serde(untagged)]
665#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
666pub enum Inventory {
667    /// The roots held for a specific store.
668    ForStore {
669        /// The store launcher id (echoed, 64-hex).
670        store_id: HexId,
671        /// The roots this node holds for the store.
672        roots: Vec<HexId>,
673    },
674    /// The stores this node serves (no `store_id` given).
675    AllStores {
676        /// The store launcher ids served.
677        stores: Vec<HexId>,
678    },
679}
680
681// ===========================================================================
682// dig.fetchRange  (PEER)
683// ===========================================================================
684
685/// Params for [`dig.fetchRange`](crate::method::Method::FetchRange) — a single
686/// range frame of a resource this node holds.
687///
688/// # Construction
689///
690/// Like [`RangeFrame`], this type is `#[non_exhaustive]`: build it with
691/// [`resource`](Self::resource) plus the `with_*` setters rather than a struct
692/// literal, so a future additive field is a PATCH for every consumer instead of a
693/// semver cascade.
694///
695/// # Cross-repo contract
696///
697/// [`skip_layout`](Self::skip_layout) is byte-identical to
698/// `dig_nat::mux::RangeRequest::skip_layout`, pinned in
699/// `tests/nat_wire_mirror.rs`. The two enclosing types deliberately differ in every
700/// other respect — dig-nat's `RangeRequest` is a length-prefixed stream preamble,
701/// this is a JSON-RPC params object with a `redirect_depth` dig-nat has no notion
702/// of — so the byte-identical contract here is the FIELD, not the object.
703#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
704#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
705#[non_exhaustive]
706pub struct FetchRangeParams {
707    /// The store launcher id (64-hex, required).
708    pub store_id: HexId,
709    /// The generation root (64-hex, required for a resource fetch).
710    pub root: HexId,
711    /// `SHA-256(urn)` (64-hex, required for a resource fetch).
712    pub retrieval_key: HexId,
713    /// The range start (default 0).
714    #[serde(skip_serializing_if = "Option::is_none", default)]
715    pub offset: Option<u64>,
716    /// The range length in bytes (> 0; clamped to the window cap).
717    pub length: u64,
718    /// Whole-capsule mode (default false). Capsule range fetch is not yet
719    /// served; a `true` here yields `-32004`.
720    #[serde(skip_serializing_if = "Option::is_none", default)]
721    pub capsule: Option<bool>,
722    /// The redirect budget already consumed (echoed from a `-32008` redirect).
723    #[serde(skip_serializing_if = "Option::is_none", default)]
724    pub redirect_depth: Option<u64>,
725    /// Suppress the resource-scaling layout metadata (`chunk_lens` +
726    /// `inclusion_proof`) on this stream's frames, because the client already holds
727    /// the commitment for this `root`.
728    ///
729    /// A client that has already read the layout once — a resumed download, a second
730    /// range of the same resource, a parallel fetch from another holder — does not
731    /// need it again, and re-sending it costs a whole paged prologue PER STREAM: a
732    /// 1,048,576-chunk layout is roughly 7.3 MB, which a 64-way parallel plan would
733    /// otherwise pay 64 times over. Suppressing it is the difference between a
734    /// bounded and an unbounded cost on the read path.
735    ///
736    /// Absent or `false` preserves the pre-0.6.0 behaviour, so an older holder that
737    /// ignores this field is never broken by it — it simply sends metadata the client
738    /// discards. Read the rule through
739    /// [`suppresses_layout`](Self::suppresses_layout) rather than re-deriving it.
740    ///
741    /// The fixed-size identity fields ([`root`](RangeFrame::root),
742    /// [`total_length`](RangeFrame::total_length),
743    /// [`chunk_count`](RangeFrame::chunk_count),
744    /// [`chunk_index`](RangeFrame::chunk_index)) are NOT suppressed: they are what
745    /// detects a wrong-generation holder on arrival, and a client that stopped
746    /// receiving them would lose that check on exactly the streams it fetches most.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub skip_layout: Option<bool>,
749}
750
751impl FetchRangeParams {
752    /// A range request for one content resource: `length` bytes of
753    /// `retrieval_key`'s ciphertext at the generation `root`.
754    pub fn resource(
755        store_id: impl Into<HexId>,
756        root: impl Into<HexId>,
757        retrieval_key: impl Into<HexId>,
758        length: u64,
759    ) -> Self {
760        FetchRangeParams {
761            store_id: store_id.into(),
762            root: root.into(),
763            retrieval_key: retrieval_key.into(),
764            offset: None,
765            length,
766            capsule: None,
767            redirect_depth: None,
768            skip_layout: None,
769        }
770    }
771
772    /// Start the range at `offset` rather than at 0.
773    pub fn with_offset(mut self, offset: u64) -> Self {
774        self.offset = Some(offset);
775        self
776    }
777
778    /// Request whole-capsule mode. Capsule range fetch is not yet served — a `true`
779    /// here yields
780    /// [`ResourceUnavailable`](crate::error::ErrorCode::ResourceUnavailable).
781    pub fn with_capsule(mut self, capsule: bool) -> Self {
782        self.capsule = Some(capsule);
783        self
784    }
785
786    /// Echo the redirect budget already consumed, from a `-32008` redirect.
787    pub fn with_redirect_depth(mut self, redirect_depth: u64) -> Self {
788        self.redirect_depth = Some(redirect_depth);
789        self
790    }
791
792    /// Ask the holder to omit the resource-scaling layout metadata, because this
793    /// client already holds the commitment for this `root`. See
794    /// [`skip_layout`](Self::skip_layout).
795    pub fn with_skip_layout(mut self, skip_layout: bool) -> Self {
796        self.skip_layout = Some(skip_layout);
797        self
798    }
799
800    /// Whether this request suppresses the resource-scaling layout metadata.
801    ///
802    /// The single home for the "absent or `false` means SEND the layout" rule. A
803    /// serve path that reached for `skip_layout.is_some()` instead would suppress the
804    /// layout for a client that had explicitly asked for it — unrecoverable for that
805    /// client, since the layout is a decrypt input it cannot obtain any other way on
806    /// that stream.
807    pub fn suppresses_layout(&self) -> bool {
808        self.skip_layout.unwrap_or(false)
809    }
810}
811
812/// One range frame of a resource: a byte window, plus the per-resource
813/// verification metadata that makes the window independently checkable.
814///
815/// The metadata splits in two by whether it scales with the resource, and the
816/// split decides which frames carry it:
817///
818/// - **The identity set — [`root`](Self::root),
819///   [`total_length`](Self::total_length), [`chunk_count`](Self::chunk_count),
820///   plus [`chunk_index`](Self::chunk_index) when the window begins on a chunk
821///   boundary — rides EVERY frame.** It is fixed-size, so carrying it everywhere
822///   costs a bounded number of bytes, and it is what lets a client fetching in
823///   parallel from many holders reject a wrong-generation or wrong-layout source
824///   the moment a frame arrives, rather than after paying for the whole resource
825///   in bandwidth.
826/// - **The resource-scaling set — [`chunk_lens`](Self::chunk_lens) and
827///   [`inclusion_proof`](Self::inclusion_proof) — rides the first frame, or a
828///   paged prologue, once per range stream.** Repeating it per frame would cost
829///   proportionally to the resource against a frame budget with no slack; a layout
830///   too large to state on one frame is paged instead, each page stamped with the
831///   [`chunk_lens_offset`](Self::chunk_lens_offset) it begins at.
832///
833/// The window is exactly the span the caller requested — never widened.
834///
835/// # Construction
836///
837/// This type is [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html):
838/// build it with [`data`](Self::data) and the `with_*` setters rather than a struct
839/// literal. That is deliberate — the wire form grows as the protocol does, and
840/// routing construction through named setters means a future additive field is a
841/// PATCH release for every consumer instead of another semver cascade. It also
842/// makes the two frame shapes different call chains rather than one call with a
843/// pile of `None`s, so a continuation frame cannot accidentally claim a layout it
844/// is not stating.
845///
846/// # Cross-repo contract
847///
848/// The wire form is **byte-identical** to `dig_nat::mux::RangeFrame`, the
849/// streaming implementation of this frame (`SYSTEM.md` → "Canonical DIG-node RPC
850/// interface"). Field names, encodings, and the population rule above are pinned
851/// against dig-nat's actual output in `tests/nat_wire_mirror.rs`; a change to any
852/// of them lands in both crates in the same unit of work or not at all.
853#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
854#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
855#[non_exhaustive]
856pub struct RangeFrame {
857    /// The window start offset (echoed).
858    pub offset: u64,
859    /// This window's byte length.
860    pub length: u64,
861    /// This window's ciphertext, base64.
862    pub bytes: String,
863    /// Whether this frame ends the resource.
864    pub complete: bool,
865    /// The full resource ciphertext length. Part of the fixed-size **identity
866    /// set**, so it rides EVERY frame.
867    #[serde(skip_serializing_if = "Option::is_none", default)]
868    pub total_length: Option<u64>,
869    /// Per-chunk ciphertext lengths of the full resource, in order — the layout a
870    /// reader needs before it can decrypt (per-chunk AEAD needs the WHOLE array,
871    /// and a reader rejects an array whose sum differs from
872    /// [`total_length`](Self::total_length)).
873    ///
874    /// Resource-scaling, so it rides the first frame or a **paged prologue**, once
875    /// per range stream — never repeated on continuation frames. When paged, this
876    /// is one page of the array and
877    /// [`chunk_lens_offset`](Self::chunk_lens_offset) states the entry it begins
878    /// at.
879    #[serde(skip_serializing_if = "Option::is_none", default)]
880    pub chunk_lens: Option<Vec<u64>>,
881    /// This frame's first chunk index — the pre-existing alias of
882    /// [`first_chunk_index`](Self::first_chunk_index), carrying the same value, and
883    /// the name dig-nat emits.
884    ///
885    /// Part of the **identity set**: it rides every frame whose window begins on a
886    /// chunk boundary, and is OMITTED (rather than guessed) on a mid-chunk window.
887    /// Being fixed-size, it is settable on its own — see
888    /// [`with_chunk_index`](Self::with_chunk_index) — precisely so a continuation
889    /// frame can state it without dragging along the once-per-stream
890    /// [`inclusion_proof`](Self::inclusion_proof).
891    #[serde(skip_serializing_if = "Option::is_none", default)]
892    pub chunk_index: Option<u64>,
893    /// Whole-resource merkle proof against [`root`](Self::root), base64, relayed
894    /// verbatim.
895    ///
896    /// Resource-scaling, so it rides the first frame or the paged prologue, once
897    /// per range stream. A holder MUST NOT repeat it per frame: it is bounded at
898    /// 4,096 base64 bytes, which against the frame budget leaves no slack for the
899    /// payload the frame exists to carry.
900    #[serde(skip_serializing_if = "Option::is_none", default)]
901    pub inclusion_proof: Option<String>,
902    /// The chain-anchored root (64-hex) this frame's resource verified against.
903    /// Part of the fixed-size **identity set**, so it rides EVERY frame.
904    ///
905    /// NOT A TRUST ANCHOR BY ITSELF. The client resolves the resource's root from
906    /// the URN (chain-anchored) and PINS it before fetching; a peer-declared value
907    /// never replaces that pinned root. What this field provides is a
908    /// generation-CONSISTENCY check: a frame declaring a root other than the pinned
909    /// one is REJECTED and attributed to the offending peer (NC-9 fail-closed). So
910    /// a declared root can only ever cause rejection — it can never move the pinned
911    /// root, and never makes an unverified frame acceptable.
912    #[serde(skip_serializing_if = "Option::is_none", default)]
913    pub root: Option<HexId>,
914    /// **RESERVED — not currently derivable; a server MUST NOT emit it.**
915    ///
916    /// Per-chunk merkle inclusion proofs for the chunks a frame covers. No such
917    /// proof exists in the current store format: the generation root's merkle
918    /// leaves are per-RESOURCE (a leaf is the SHA-256 of a resource's WHOLE
919    /// ciphertext), so a single chunk has no leaf to prove. A client MUST NOT
920    /// require this field, and per-range verification instead uses the
921    /// whole-resource [`inclusion_proof`](Self::inclusion_proof) together with the
922    /// per-frame [`root`](Self::root)/[`chunk_lens`](Self::chunk_lens) metadata.
923    ///
924    /// Making it derivable requires a per-resource chunk-level commitment in the
925    /// store format first (tracked as `dig_ecosystem#1601`). The field is kept in
926    /// the wire type, unused, so populating it later is additive (§5.1); each entry
927    /// would be an opaque base64 proof blob, since this pure level-00 wire type
928    /// MUST NOT depend on the merkle primitive.
929    #[serde(skip_serializing_if = "Option::is_none", default)]
930    pub range_proof: Option<Vec<String>>,
931    /// The chunk index of the first chunk in this frame (0-based, into the
932    /// resource's chunk sequence described by [`chunk_lens`](Self::chunk_lens)).
933    ///
934    /// Present only when the frame's window begins EXACTLY on a chunk boundary; a
935    /// mid-chunk window omits it rather than assert an index the caller's own
936    /// alignment check would contradict. The served window is exactly the requested
937    /// span — a server MUST NOT widen a range to a chunk boundary — so a frame is
938    /// chunk-aligned only when the caller asked for an aligned span.
939    #[serde(skip_serializing_if = "Option::is_none", default)]
940    pub first_chunk_index: Option<u64>,
941    /// The resource's TOTAL chunk count — how many entries the fully reassembled
942    /// [`chunk_lens`](Self::chunk_lens) array has.
943    ///
944    /// Fixed-size, so it belongs to the **identity set** and rides EVERY frame.
945    /// Together with [`root`](Self::root) and
946    /// [`total_length`](Self::total_length) it is what lets a reader detect a
947    /// wrong-generation or wrong-layout holder on the first frame it receives. It is
948    /// also how a reader sizes the array it is paging in, and therefore how it knows
949    /// a **paged prologue** is complete: the prologue ends when the reader holds
950    /// `chunk_count` entries, which no single page can tell it.
951    #[serde(default, skip_serializing_if = "Option::is_none")]
952    pub chunk_count: Option<u64>,
953    /// The index into the resource's [`chunk_lens`](Self::chunk_lens) array at which
954    /// THIS frame's page begins — how a **paged prologue** is located and
955    /// reassembled.
956    ///
957    /// A resource whose layout exceeds the per-frame entry cap cannot state it on
958    /// one frame, so the sender pages it: successive frames each carry up to that
959    /// many entries, stamped with the offset they start at. A reader places each page
960    /// at its offset and holds the whole array once it has
961    /// [`chunk_count`](Self::chunk_count) entries.
962    ///
963    /// Absent means "this frame's `chunk_lens`, if any, begins at entry 0" — the
964    /// single-frame layout, which is the shape every pre-0.6.0 producer emits. So an
965    /// older frame decodes with exactly its original meaning (§5.1).
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub chunk_lens_offset: Option<u64>,
968}
969
970impl RangeFrame {
971    /// A **data frame**: `length` bytes of base64 ciphertext at `offset`, carrying
972    /// no metadata — the bare shape every continuation frame starts from.
973    ///
974    /// `length` is stated rather than derived because [`bytes`](Self::bytes) is
975    /// already base64 on this type, and recovering the raw window length from it
976    /// would need a base64 codec this pure level-00 wire crate deliberately does not
977    /// depend on. A serve path passes the length it served.
978    pub fn data(offset: u64, length: u64, bytes: impl Into<String>) -> Self {
979        RangeFrame {
980            offset,
981            length,
982            bytes: bytes.into(),
983            complete: false,
984            total_length: None,
985            chunk_lens: None,
986            chunk_index: None,
987            inclusion_proof: None,
988            root: None,
989            range_proof: None,
990            first_chunk_index: None,
991            chunk_count: None,
992            chunk_lens_offset: None,
993        }
994    }
995
996    /// Mark this as the final frame of the range.
997    pub fn with_complete(mut self, complete: bool) -> Self {
998        self.complete = complete;
999        self
1000    }
1001
1002    /// The fixed-size **identity set** every frame of a range carries: the
1003    /// generation `root` (64-hex) the range is served from, the resource's
1004    /// ciphertext `total_length`, and its `chunk_count`.
1005    ///
1006    /// These three are what let a reader reject a wrong-generation or wrong-layout
1007    /// holder the moment a frame arrives — which the resource-scaling metadata never
1008    /// could, since it arrives once. Call this on every frame.
1009    pub fn with_identity(
1010        mut self,
1011        root: impl Into<HexId>,
1012        total_length: u64,
1013        chunk_count: u64,
1014    ) -> Self {
1015        self.root = Some(root.into());
1016        self.total_length = Some(total_length);
1017        self.chunk_count = Some(chunk_count);
1018        self
1019    }
1020
1021    /// State [`chunk_index`](Self::chunk_index) — the chunk this frame's window
1022    /// begins on — for a chunk-aligned window.
1023    ///
1024    /// Separate from [`with_inclusion_proof`](Self::with_inclusion_proof) on purpose:
1025    /// the index is fixed-size identity metadata that rides every aligned frame,
1026    /// while the proof is once-per-stream, so binding them together would force a
1027    /// producer to either repeat a proof it MUST NOT repeat or bypass this API. Omit
1028    /// the call entirely for a mid-chunk window.
1029    pub fn with_chunk_index(mut self, chunk_index: u64) -> Self {
1030        self.chunk_index = Some(chunk_index);
1031        self
1032    }
1033
1034    /// Additionally state [`first_chunk_index`](Self::first_chunk_index), this
1035    /// crate's v0.4.0 alias of [`chunk_index`](Self::chunk_index).
1036    ///
1037    /// Both names carry the same value. dig-nat emits only `chunk_index`, so
1038    /// [`with_chunk_index`](Self::with_chunk_index) alone is the interoperable
1039    /// choice; a producer serving readers that expect the newer name states both.
1040    pub fn with_first_chunk_index(mut self, first_chunk_index: u64) -> Self {
1041        self.first_chunk_index = Some(first_chunk_index);
1042        self
1043    }
1044
1045    /// One page of the resource's `chunk_lens` array, beginning at entry
1046    /// `chunk_lens_offset`.
1047    ///
1048    /// Call it once with offset `0` for a layout that fits a single frame, or once
1049    /// per page of a **paged prologue**. A page is only ever useful as part of a
1050    /// complete set: `chunk_lens` is a decrypt input, and a reader needs all
1051    /// [`chunk_count`](Self::chunk_count) entries before it can decrypt anything.
1052    pub fn with_chunk_lens_page(mut self, chunk_lens_offset: u64, chunk_lens: Vec<u64>) -> Self {
1053        self.chunk_lens_offset = Some(chunk_lens_offset);
1054        self.chunk_lens = Some(chunk_lens);
1055        self
1056    }
1057
1058    /// The whole-resource merkle inclusion proof against
1059    /// [`root`](Self::root) (base64, relayed verbatim).
1060    ///
1061    /// Resource-scaling: state it on the first frame or the prologue, once per range
1062    /// stream, never per frame.
1063    pub fn with_inclusion_proof(mut self, inclusion_proof: impl Into<String>) -> Self {
1064        self.inclusion_proof = Some(inclusion_proof.into());
1065        self
1066    }
1067
1068    /// State the **RESERVED** [`range_proof`](Self::range_proof) field.
1069    ///
1070    /// A server MUST NOT emit it — no per-chunk proof is derivable from the current
1071    /// store format (see the field's own documentation). The setter exists so the
1072    /// shape stays constructible for the conformance vectors that pin it, and so no
1073    /// field of this `#[non_exhaustive]` type is unreachable; it is not a serve-path
1074    /// call.
1075    pub fn with_range_proof(mut self, range_proof: Vec<String>) -> Self {
1076        self.range_proof = Some(range_proof);
1077        self
1078    }
1079}
1080
1081// ===========================================================================
1082// dig.getModuleInfo / dig.fetchModuleRange  (PEER — whole-module pull, #1576)
1083// ===========================================================================
1084
1085/// Params for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
1086/// handshake a peer reads before range-pulling a whole `.dig` module for
1087/// `(store, root)`.
1088#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1089#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1090pub struct GetModuleInfoParams {
1091    /// The store launcher id (64-hex, required).
1092    pub store_id: HexId,
1093    /// The generation root whose `.dig` module is being pulled (64-hex, required).
1094    pub root: HexId,
1095}
1096
1097/// Result for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
1098/// transfer descriptor of a whole `.dig` module.
1099///
1100/// The whole-module blob is content-addressed + immutable (the `.dig` container
1101/// is byte-identical by construction). [`module_hash`](Self::module_hash) is the
1102/// content id of the assembled blob; a puller verifies each pulled range against
1103/// [`chunk_hashes`](Self::chunk_hashes) (per-peer attribution on a multi-source
1104/// pull) and the fully-assembled blob against `module_hash`, THEN verifies the
1105/// assembled module against its chain-anchored root before admitting + resharing
1106/// (NC-9 verified-content-not-safe-content).
1107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1108#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1109pub struct ModuleInfo {
1110    /// The total byte length of the whole `.dig` module blob.
1111    pub total_size: u64,
1112    /// The content id of the fully-assembled module blob (64-hex `SHA-256` of the
1113    /// module bytes). The puller checks the assembled blob against this.
1114    pub module_hash: HexId,
1115    /// Per-chunk content hashes (64-hex each) in ascending chunk order, covering
1116    /// the blob in [`total_size`](Self::total_size)-spanning fixed-size chunks
1117    /// (the trailing chunk may be short). A puller checks each pulled
1118    /// [`RangeFrame`] against the covering entries for per-source attribution on a
1119    /// multi-source pull (a tampered range fails closed before assembly).
1120    pub chunk_hashes: Vec<HexId>,
1121    /// Per-chunk byte lengths (in the same order as [`chunk_hashes`](Self::chunk_hashes)).
1122    /// MUST have the same length as `chunk_hashes` and MUST sum to `total_size`.
1123    /// A puller uses these to map a fetched byte range to the covering chunk hash(es).
1124    pub chunk_lens: Vec<u64>,
1125}
1126
1127/// Params for [`dig.fetchModuleRange`](crate::method::Method::FetchModuleRange) —
1128/// a single range frame of the whole `.dig` module blob for `(store, root)`.
1129///
1130/// The response reuses [`RangeFrame`]: [`bytes`](RangeFrame::bytes) carries the
1131/// window of the module blob (base64), [`total_length`](RangeFrame::total_length)
1132/// echoes the whole-module size on the first frame, and
1133/// [`complete`](RangeFrame::complete) ends the stream.
1134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1135#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1136pub struct FetchModuleRangeParams {
1137    /// The store launcher id (64-hex, required).
1138    pub store_id: HexId,
1139    /// The generation root whose `.dig` module is being pulled (64-hex, required).
1140    pub root: HexId,
1141    /// The range start into the module blob (default 0).
1142    #[serde(skip_serializing_if = "Option::is_none", default)]
1143    pub offset: Option<u64>,
1144    /// The range length in bytes (> 0; clamped to the window cap).
1145    pub length: u64,
1146}
1147
1148// ===========================================================================
1149// dig.stage  (CONTROL — loopback / in-process only)
1150// ===========================================================================
1151
1152/// Params for [`dig.stage`](crate::method::Method::Stage) — compile a local
1153/// folder into a capsule `.dig` module in-process.
1154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1155#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1156pub struct StageParams {
1157    /// The absolute path to the folder to compile.
1158    pub dir: String,
1159    /// The target store launcher id (64-hex). Absent ⇒ an ephemeral,
1160    /// content-derived id (a preview).
1161    #[serde(skip_serializing_if = "Option::is_none", default)]
1162    pub store_id: Option<HexId>,
1163    /// The store salt (64-hex). Present ⇒ a private store.
1164    #[serde(skip_serializing_if = "Option::is_none", default)]
1165    pub salt: Option<HexId>,
1166    /// Optional DIGHub-style manifest metadata to embed.
1167    #[serde(skip_serializing_if = "Option::is_none", default)]
1168    pub metadata: Option<serde_json::Value>,
1169}
1170
1171/// Result for [`dig.stage`](crate::method::Method::Stage) — the compiled capsule.
1172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1173#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1174pub struct StageResult {
1175    /// The canonical capsule identity, `storeId:rootHash`.
1176    pub capsule: String,
1177    /// The store launcher id (64-hex).
1178    pub store_id: HexId,
1179    /// The compiled generation root (64-hex).
1180    pub root: HexId,
1181    /// The filesystem path to the compiled `.dig` module.
1182    pub module_path: String,
1183    /// The module size in bytes.
1184    pub size: u64,
1185    /// The `chia://storeId:rootHash/` content address.
1186    #[serde(skip_serializing_if = "Option::is_none", default)]
1187    pub content_address: Option<String>,
1188    /// The relative paths compiled into the capsule.
1189    #[serde(default)]
1190    pub files: Vec<String>,
1191    /// Whether this is an ephemeral preview (not advancing a real store).
1192    #[serde(skip_serializing_if = "Option::is_none", default)]
1193    pub ephemeral: Option<bool>,
1194}
1195
1196// ===========================================================================
1197// cache.*  (CONTROL — loopback / in-process only)
1198// ===========================================================================
1199
1200/// Result for [`cache.getConfig`](crate::method::Method::CacheGetConfig).
1201///
1202/// The canonical field name for the cache path is `cache_dir` everywhere (the
1203/// shell's historical `dir` is unified onto this name).
1204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1205#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1206pub struct CacheConfig {
1207    /// The on-disk cache size cap in bytes (floored at 64 MiB).
1208    pub cap_bytes: u64,
1209    /// The bytes currently used.
1210    pub used_bytes: u64,
1211    /// The effective resolved cache directory.
1212    pub cache_dir: String,
1213    /// Whether that directory is the canonical shared location (vs a
1214    /// process-private fallback).
1215    pub shared: bool,
1216}
1217
1218/// Params for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
1219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1220#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1221pub struct SetCapBytesParams {
1222    /// The requested cap in bytes (floored at 64 MiB by the node).
1223    pub cap_bytes: u64,
1224}
1225
1226/// Result for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
1227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1228#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1229pub struct SetCapBytesResult {
1230    /// The effective cap after flooring.
1231    pub cap_bytes: u64,
1232}
1233
1234/// One durable cached-module entry.
1235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1236#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1237pub struct CachedCapsule {
1238    /// The canonical capsule identity, `storeId:rootHash`.
1239    pub capsule: String,
1240    /// The store launcher id (64-hex).
1241    pub store_id: HexId,
1242    /// The generation root (64-hex).
1243    pub root: HexId,
1244    /// The module size in bytes.
1245    pub size_bytes: u64,
1246    /// When the module was last used (unix ms).
1247    pub last_used_unix_ms: u64,
1248}
1249
1250/// Result for [`cache.listCached`](crate::method::Method::CacheListCached).
1251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1252#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1253pub struct CachedList {
1254    /// The cached capsules.
1255    pub cached: Vec<CachedCapsule>,
1256}
1257
1258/// Params for a capsule-keyed cache op
1259/// ([`cache.removeCached`](crate::method::Method::CacheRemoveCached),
1260/// [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache)).
1261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1262#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1263pub struct CapsuleKey {
1264    /// The store launcher id (64-hex).
1265    pub store_id: HexId,
1266    /// The generation root (64-hex).
1267    pub root: HexId,
1268}
1269
1270/// Result for [`cache.removeCached`](crate::method::Method::CacheRemoveCached).
1271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1272#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1273pub struct RemoveCachedResult {
1274    /// Whether an entry was removed.
1275    pub removed: bool,
1276}
1277
1278/// Result for [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache).
1279///
1280/// A failed fetch is reported in-band (`status = "failed"` + `message`) so the
1281/// caller can show it without treating it as a transport error.
1282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1283#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1284pub struct FetchAndCacheResult {
1285    /// `"cached"`, `"already_cached"`, or `"failed"`.
1286    pub status: String,
1287    /// The fetched module size in bytes (on success).
1288    #[serde(skip_serializing_if = "Option::is_none", default)]
1289    pub size_bytes: Option<u64>,
1290    /// The served generation root (64-hex, on success).
1291    #[serde(skip_serializing_if = "Option::is_none", default)]
1292    pub served_root: Option<HexId>,
1293    /// The failure message (on `status = "failed"`).
1294    #[serde(skip_serializing_if = "Option::is_none", default)]
1295    pub message: Option<String>,
1296}
1297
1298// ===========================================================================
1299// control.peerStatus  (CONTROL — loopback / in-process only)
1300// ===========================================================================
1301
1302/// Result for [`control.peerStatus`](crate::method::Method::ControlPeerStatus) —
1303/// a snapshot of the node's L7 peer network. Always safe to call; reports
1304/// `running: false` on the FFI path.
1305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1306#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1307pub struct PeerStatusSnapshot {
1308    /// Whether a peer network is currently active.
1309    pub running: bool,
1310    /// This node's `peer_id` (64-hex), if a peer network is running.
1311    #[serde(skip_serializing_if = "Option::is_none", default)]
1312    pub peer_id: Option<HexId>,
1313    /// The DIG network id.
1314    pub network_id: String,
1315    /// The relay reservation posture.
1316    pub relay: RelayStatus,
1317    /// The number of currently connected peers.
1318    pub connected_peers: u64,
1319    /// The last peer-network error, if any.
1320    #[serde(skip_serializing_if = "Option::is_none", default)]
1321    pub last_error: Option<String>,
1322}
1323
1324// ===========================================================================
1325// cache.stats  (CONTROL — loopback / in-process only)
1326// ===========================================================================
1327
1328/// The decoded-content cache hit/miss counters carried in
1329/// [`CacheStats`](CacheStats::content_cache).
1330#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1331#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1332pub struct ContentCacheCounters {
1333    /// Session decoded-content cache hits.
1334    pub hits: u64,
1335    /// Session decoded-content cache misses.
1336    pub misses: u64,
1337}
1338
1339/// Result for [`cache.stats`](crate::method::Method::CacheStats) — cache
1340/// telemetry beside [`cache.getConfig`](crate::method::Method::CacheGetConfig):
1341/// the reserved cap + live usage, the cached-capsule count + total on-disk
1342/// bytes, and the session eviction + content-cache counters.
1343#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1344#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1345pub struct CacheStats {
1346    /// The on-disk cache size cap in bytes.
1347    pub cap_bytes: u64,
1348    /// The bytes currently used on disk.
1349    pub used_bytes: u64,
1350    /// The number of durable cached capsules.
1351    pub entry_count: u64,
1352    /// The total on-disk bytes across the cached capsules.
1353    pub total_bytes: u64,
1354    /// Capsules evicted this session.
1355    pub evicted_count: u64,
1356    /// Bytes evicted this session.
1357    pub evicted_bytes: u64,
1358    /// The decoded-content cache hit/miss counters.
1359    pub content_cache: ContentCacheCounters,
1360}
1361
1362// ===========================================================================
1363// control.subscribe / control.unsubscribe / control.listSubscriptions
1364// (CONTROL — loopback / in-process only)
1365// ===========================================================================
1366
1367/// Params for [`control.subscribe`](crate::method::Method::ControlSubscribe) and
1368/// [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
1369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1370#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1371pub struct SubscribeParams {
1372    /// The store launcher id to (un)subscribe (64-hex).
1373    pub store_id: HexId,
1374}
1375
1376/// Result for [`control.subscribe`](crate::method::Method::ControlSubscribe).
1377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1378#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1379pub struct SubscribeResult {
1380    /// Always `true` — the store is subscribed after this call.
1381    pub subscribed: bool,
1382    /// Whether this call ADDED the subscription (`false` ⇒ already subscribed).
1383    pub added: bool,
1384    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
1385    pub store_id: HexId,
1386}
1387
1388/// Result for [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
1389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1390#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1391pub struct UnsubscribeResult {
1392    /// Always `false` — the store is not subscribed after this call.
1393    pub subscribed: bool,
1394    /// Whether this call REMOVED a subscription (`false` ⇒ was not subscribed).
1395    pub removed: bool,
1396    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
1397    pub store_id: HexId,
1398}
1399
1400/// Result for
1401/// [`control.listSubscriptions`](crate::method::Method::ControlListSubscriptions).
1402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1403#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1404pub struct SubscriptionsList {
1405    /// The persisted subscribed store ids (64-hex each).
1406    pub subscriptions: Vec<HexId>,
1407    /// The subscription count (`subscriptions.len()`).
1408    pub count: u64,
1409}
1410
1411// ===========================================================================
1412// control.peers.connect / control.peers.disconnect
1413// (CONTROL — loopback / in-process only)
1414// ===========================================================================
1415
1416/// Params for [`control.peers.connect`](crate::method::Method::ControlPeersConnect)
1417/// and [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
1418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1419#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1420pub struct PeerConnectParams {
1421    /// The peer to dial/drop — a dialable address, or a known peer's `peer_id`
1422    /// (64-hex) to resolve an already-connected peer.
1423    pub peer: String,
1424}
1425
1426/// Result for
1427/// [`control.peers.connect`](crate::method::Method::ControlPeersConnect).
1428#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1429#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1430pub struct PeerConnectResult {
1431    /// Always `true` on success — the peer is a counted, connected pool member.
1432    pub connected: bool,
1433    /// The connected peer's stable `peer_id` (64-hex).
1434    pub peer_id: HexId,
1435}
1436
1437/// Result for
1438/// [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
1439///
1440/// Idempotent: disconnecting a peer that is not connected succeeds as a no-op.
1441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1442#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1443pub struct PeerDisconnectResult {
1444    /// Always `true` — the peer is not in the pool after this call.
1445    pub disconnected: bool,
1446    /// The dropped peer's `peer_id` (trimmed + lower-cased, 64-hex).
1447    pub peer_id: HexId,
1448}
1449
1450// ===========================================================================
1451// dig.health / dig.methods / rpc.discover  (discovery)
1452// ===========================================================================
1453
1454/// Result for [`dig.health`](crate::method::Method::Health) — liveness + a
1455/// capability summary.
1456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1457#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1458pub struct Health {
1459    /// Liveness — `"ok"` when the node can serve.
1460    pub status: String,
1461    /// The node's software version.
1462    #[serde(skip_serializing_if = "Option::is_none", default)]
1463    pub version: Option<String>,
1464    /// The DIG network id the node serves.
1465    #[serde(skip_serializing_if = "Option::is_none", default)]
1466    pub network_id: Option<String>,
1467    /// The method names this node implements (its profile).
1468    #[serde(default)]
1469    pub methods: Vec<String>,
1470}
1471
1472/// Result for [`dig.methods`](crate::method::Method::Methods) — the method names
1473/// this node implements (agent self-describe).
1474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1475#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1476pub struct Methods {
1477    /// The implemented method names.
1478    pub methods: Vec<String>,
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483    use super::*;
1484    use serde_json::json;
1485
1486    /// **Proves:** `ContentChunk` round-trips a node-profile window (no
1487    /// network-profile fields) without inventing keys.
1488    /// **Catches:** a missing `skip_serializing_if` that would leak `null`
1489    /// network-profile fields onto the node profile.
1490    #[test]
1491    fn content_chunk_node_profile_is_lean() {
1492        let c = ContentChunk {
1493            ciphertext: "AAA=".into(),
1494            root: "ab".repeat(32),
1495            complete: false,
1496            next_offset: Some(3_145_728),
1497            inclusion_proof: Some("cHJvb2Y=".into()),
1498            chunk_lens: Some(vec![10, 20]),
1499            source: Some("local".into()),
1500            total_length: None,
1501            length: None,
1502            offset: None,
1503            program_hash: None,
1504        };
1505        let v = serde_json::to_value(&c).unwrap();
1506        assert_eq!(v["source"], "local");
1507        assert!(
1508            v.get("total_length").is_none(),
1509            "node profile must omit total_length"
1510        );
1511        assert!(v.get("program_hash").is_none());
1512        assert_eq!(serde_json::from_value::<ContentChunk>(v).unwrap(), c);
1513    }
1514
1515    /// **Proves:** the network-profile fields serialize when present.
1516    #[test]
1517    fn content_chunk_network_profile_carries_extras() {
1518        let c = ContentChunk {
1519            ciphertext: "AAA=".into(),
1520            root: "cd".repeat(32),
1521            complete: true,
1522            next_offset: None,
1523            inclusion_proof: None,
1524            chunk_lens: None,
1525            source: None,
1526            total_length: Some(100),
1527            length: Some(100),
1528            offset: Some(0),
1529            program_hash: Some("ef".repeat(32)),
1530        };
1531        let v = serde_json::to_value(&c).unwrap();
1532        assert_eq!(v["total_length"], 100);
1533        assert_eq!(v["length"], 100);
1534        assert!(v.get("source").is_none());
1535    }
1536
1537    /// **Proves:** the untagged `Inventory` picks `ForStore` vs `AllStores` by
1538    /// shape.
1539    /// **Catches:** a lost `#[serde(untagged)]` that would tag the variant.
1540    #[test]
1541    fn inventory_untagged_by_shape() {
1542        let for_store = Inventory::ForStore {
1543            store_id: "ab".repeat(32),
1544            roots: vec!["cd".repeat(32)],
1545        };
1546        let s = serde_json::to_string(&for_store).unwrap();
1547        assert!(s.contains("\"roots\""));
1548        assert!(!s.contains("ForStore"));
1549        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), for_store);
1550
1551        let all = Inventory::AllStores {
1552            stores: vec!["ef".repeat(32)],
1553        };
1554        let s = serde_json::to_string(&all).unwrap();
1555        assert!(s.contains("\"stores\""));
1556        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), all);
1557    }
1558
1559    /// **Proves:** `RedirectInfo` serializes the full redirect payload the
1560    /// `-32008` envelope carries.
1561    #[test]
1562    fn redirect_info_shape() {
1563        let r = RedirectInfo {
1564            content: ContentRef {
1565                store_id: "ab".repeat(32),
1566                root: Some("cd".repeat(32)),
1567                retrieval_key: Some("ef".repeat(32)),
1568            },
1569            providers: vec![Provider {
1570                peer_id: "12".repeat(32),
1571                addresses: vec![PeerAddress {
1572                    host: "::1".into(),
1573                    port: 9444,
1574                    kind: "direct".into(),
1575                }],
1576            }],
1577            redirect_depth: 1,
1578            max_redirects: 4,
1579        };
1580        let v = serde_json::to_value(&r).unwrap();
1581        assert_eq!(v["redirect_depth"], 1);
1582        assert_eq!(v["max_redirects"], 4);
1583        assert_eq!(v["providers"][0]["addresses"][0]["host"], "::1");
1584        assert_eq!(serde_json::from_value::<RedirectInfo>(v).unwrap(), r);
1585    }
1586
1587    /// **Proves:** `cache.stats` models the live dig-node result field-for-field
1588    /// (the nested `content_cache{hits,misses}` object included).
1589    /// **Catches:** a drift from the node's `cache.stats` wire shape (#1075).
1590    #[test]
1591    fn cache_stats_wire_shape() {
1592        let s = CacheStats {
1593            cap_bytes: 1 << 30,
1594            used_bytes: 2048,
1595            entry_count: 3,
1596            total_bytes: 2048,
1597            evicted_count: 1,
1598            evicted_bytes: 512,
1599            content_cache: ContentCacheCounters { hits: 7, misses: 2 },
1600        };
1601        let v = serde_json::to_value(s).unwrap();
1602        assert_eq!(v["cap_bytes"], 1 << 30);
1603        assert_eq!(v["entry_count"], 3);
1604        assert_eq!(v["content_cache"]["hits"], 7);
1605        assert_eq!(v["content_cache"]["misses"], 2);
1606        assert_eq!(serde_json::from_value::<CacheStats>(v).unwrap(), s);
1607    }
1608
1609    /// **Proves:** the subscription-management results carry the exact
1610    /// `{subscribed, added|removed, store_id}` / `{subscriptions, count}` shapes
1611    /// the live node returns.
1612    #[test]
1613    fn subscription_result_shapes() {
1614        let sub = SubscribeResult {
1615            subscribed: true,
1616            added: true,
1617            store_id: "ab".repeat(32),
1618        };
1619        let v = serde_json::to_value(&sub).unwrap();
1620        assert_eq!(v["subscribed"], true);
1621        assert_eq!(v["added"], true);
1622        assert_eq!(serde_json::from_value::<SubscribeResult>(v).unwrap(), sub);
1623
1624        let unsub = UnsubscribeResult {
1625            subscribed: false,
1626            removed: true,
1627            store_id: "cd".repeat(32),
1628        };
1629        let v = serde_json::to_value(&unsub).unwrap();
1630        assert_eq!(v["subscribed"], false);
1631        assert_eq!(v["removed"], true);
1632        assert_eq!(
1633            serde_json::from_value::<UnsubscribeResult>(v).unwrap(),
1634            unsub
1635        );
1636
1637        let list = SubscriptionsList {
1638            subscriptions: vec!["ef".repeat(32)],
1639            count: 1,
1640        };
1641        let v = serde_json::to_value(&list).unwrap();
1642        assert_eq!(v["count"], 1);
1643        assert_eq!(
1644            serde_json::from_value::<SubscriptionsList>(v).unwrap(),
1645            list
1646        );
1647    }
1648
1649    /// **Proves:** `ModuleInfo` carries `chunk_lens` covering every chunk, and
1650    /// round-trips with unknown future fields.
1651    /// **Catches:** a missing `chunk_lens` field that would leave a puller unable
1652    /// to map a fetched byte range to its covering chunk hash.
1653    /// **Invariants enforced by docs:** `chunk_lens` must have the same length as
1654    /// `chunk_hashes` and must sum to `total_size`.
1655    #[test]
1656    fn module_info_chunk_lens_shape() {
1657        let info = ModuleInfo {
1658            total_size: 1024,
1659            module_hash: "ab".repeat(32),
1660            chunk_hashes: vec!["cd".repeat(32), "ef".repeat(32)],
1661            chunk_lens: vec![512, 512],
1662        };
1663        let v = serde_json::to_value(&info).unwrap();
1664        assert_eq!(v["total_size"], 1024);
1665        assert_eq!(v["chunk_hashes"].as_array().unwrap().len(), 2);
1666        assert_eq!(v["chunk_lens"].as_array().unwrap().len(), 2);
1667        assert_eq!(v["chunk_lens"][0], 512);
1668        assert_eq!(v["chunk_lens"][1], 512);
1669        assert_eq!(serde_json::from_value::<ModuleInfo>(v).unwrap(), info);
1670    }
1671
1672    /// **Proves:** `ModuleInfo` deserialization REJECTS missing `chunk_lens` field.
1673    /// This is a REQUIRED field (not optional) — omitting it from the wire is a
1674    /// protocol violation and must fail-closed.
1675    #[test]
1676    fn module_info_rejects_missing_chunk_lens() {
1677        let json_str = r#"{"total_size": 2048, "module_hash": "1122334455667788990011223344556677889900112233445566778899001122", "chunk_hashes": []}"#;
1678        let result: Result<ModuleInfo, _> = serde_json::from_str(json_str);
1679        assert!(
1680            result.is_err(),
1681            "ModuleInfo must reject JSON missing the required chunk_lens field"
1682        );
1683        let err = result.unwrap_err();
1684        assert!(
1685            err.to_string().contains("chunk_lens"),
1686            "error message should mention chunk_lens: {}",
1687            err
1688        );
1689    }
1690
1691    /// **Proves:** the peer connect/disconnect params + results round-trip and
1692    /// match the node's `{connected|disconnected, peer_id}` shapes.
1693    #[test]
1694    fn peer_connect_disconnect_shapes() {
1695        let p = PeerConnectParams {
1696            peer: "12".repeat(32),
1697        };
1698        let v = serde_json::to_value(&p).unwrap();
1699        assert_eq!(serde_json::from_value::<PeerConnectParams>(v).unwrap(), p);
1700
1701        let c = PeerConnectResult {
1702            connected: true,
1703            peer_id: "12".repeat(32),
1704        };
1705        let v = serde_json::to_value(&c).unwrap();
1706        assert_eq!(v["connected"], true);
1707        assert_eq!(serde_json::from_value::<PeerConnectResult>(v).unwrap(), c);
1708
1709        let d = PeerDisconnectResult {
1710            disconnected: true,
1711            peer_id: "34".repeat(32),
1712        };
1713        let v = serde_json::to_value(&d).unwrap();
1714        assert_eq!(v["disconnected"], true);
1715        assert_eq!(
1716            serde_json::from_value::<PeerDisconnectResult>(v).unwrap(),
1717            d
1718        );
1719    }
1720
1721    /// **Proves:** `cache.getConfig` uses the canonical `cache_dir` field name.
1722    /// **Catches:** a regression to the shell's historical `dir` name.
1723    #[test]
1724    fn cache_config_field_name_is_cache_dir() {
1725        let c = CacheConfig {
1726            cap_bytes: 1 << 30,
1727            used_bytes: 0,
1728            cache_dir: "/var/cache/dig".into(),
1729            shared: true,
1730        };
1731        let v = serde_json::to_value(&c).unwrap();
1732        assert!(v.get("cache_dir").is_some());
1733        assert!(v.get("dir").is_none(), "must not use the legacy `dir` name");
1734    }
1735
1736    /// **Proves:** an OLDER client's `dig.getAvailability` params — written
1737    /// before the hop budget existed — still deserialize, and read as a fresh,
1738    /// unhopped ask.
1739    /// **Catches:** a `redirect_depth` declared as a required `u64`, which
1740    /// rejects exactly these params with `missing field redirect_depth` and would
1741    /// make every pre-0.8 caller's ask a parse error at the peer boundary.
1742    /// **Guarded by:** the field's `Option` TYPE. `serde`'s derive already reads a
1743    /// missing `Option` field as `None`, so the `#[serde(default)]` beside it is
1744    /// parity with the sibling params types rather than the live guard — removing
1745    /// it alone leaves this test green (mutant-tested). Do not cite the attribute
1746    /// as the thing that keeps older clients working.
1747    #[test]
1748    fn get_availability_params_accepts_an_older_clients_params() {
1749        let older = json!({
1750            "items": [ { "store_id": "ab".repeat(32) } ]
1751        });
1752        let p: GetAvailabilityParams = serde_json::from_value(older).unwrap();
1753        assert_eq!(p.items.len(), 1);
1754        assert_eq!(p.redirect_depth, None, "an absent budget stays absent");
1755        assert_eq!(p.hops_consumed(), 0, "absent means zero hops consumed");
1756    }
1757
1758    /// **Proves:** a hop-zero ask serializes to exactly the pre-0.8 bytes — the
1759    /// `redirect_depth` key is absent, not `null`.
1760    /// **Catches:** a bare `#[serde(default)]` without `skip_serializing_if`,
1761    /// which would add `"redirect_depth": null` to every existing caller's
1762    /// frame and change the wire for callers that never opted in.
1763    #[test]
1764    fn get_availability_params_omits_an_absent_hop_budget() {
1765        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
1766            store_id: "ab".repeat(32),
1767            root: None,
1768            retrieval_key: None,
1769        }]);
1770        let v = serde_json::to_value(&p).unwrap();
1771        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
1772        assert_eq!(keys, vec!["items"], "hop-zero params carry only `items`");
1773    }
1774
1775    /// **Proves:** a hopped ask round-trips its budget under the `redirect_depth`
1776    /// key, and reads back through `hops_consumed`.
1777    #[test]
1778    fn get_availability_params_round_trips_the_hop_budget() {
1779        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
1780            store_id: "cd".repeat(32),
1781            root: Some("ef".repeat(32)),
1782            retrieval_key: None,
1783        }])
1784        .with_redirect_depth(2);
1785        let v = serde_json::to_value(&p).unwrap();
1786        assert_eq!(v["redirect_depth"], 2);
1787        assert_eq!(p.hops_consumed(), 2);
1788        assert_eq!(
1789            serde_json::from_value::<GetAvailabilityParams>(v).unwrap(),
1790            p
1791        );
1792    }
1793
1794    /// **Proves:** an older client params object — written before ANY of the
1795    /// recursive-ask fields existed — still deserializes, and every new field reads
1796    /// as its documented absent value.
1797    /// **Catches:** any of the three declared as required, which would turn every
1798    /// pre-0.9 caller ask into `missing field` at the peer boundary.
1799    #[test]
1800    fn get_availability_params_accepts_a_client_older_than_the_recursive_ask() {
1801        let older = json!({ "items": [ { "store_id": "ab".repeat(32) } ] });
1802        let p: GetAvailabilityParams = serde_json::from_value(older).unwrap();
1803
1804        assert_eq!(p.budget_ms(), None, "absent budget_ms means unbudgeted");
1805        assert_eq!(p.ask_id(), None, "absent ask_id means dedup opted out");
1806        assert_eq!(p.hops_consumed(), 0);
1807    }
1808
1809    /// **Proves:** a params object carrying no recursive-ask fields serializes to
1810    /// exactly the pre-0.9 bytes — the three new keys are ABSENT, not `null`.
1811    /// **Catches:** a bare `#[serde(default)]` without `skip_serializing_if`, which
1812    /// would add `"budget_ms": null` and `"ask_id": null` to the frame of every
1813    /// caller that never opted in.
1814    #[test]
1815    fn get_availability_params_omits_absent_recursive_ask_fields() {
1816        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
1817            store_id: "ab".repeat(32),
1818            root: None,
1819            retrieval_key: None,
1820        }]);
1821        let v = serde_json::to_value(&p).unwrap();
1822        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
1823        assert_eq!(keys, vec!["items"], "a plain ask carries only `items`");
1824    }
1825
1826    /// **Proves:** the time budget and the hop budget are two INDEPENDENT fields
1827    /// under two distinct keys, each round-tripping its own value.
1828    /// **Catches:** the shape defect this addition exists to prevent — folding the
1829    /// time budget into `redirect_depth`. The fixture sets them to DIFFERENT values
1830    /// (2 hops, 9000 ms) precisely so a single backing integer cannot satisfy both
1831    /// assertions; equal values would pass under either shape.
1832    #[test]
1833    fn the_time_budget_is_a_separate_field_from_the_hop_budget() {
1834        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
1835            store_id: "cd".repeat(32),
1836            root: None,
1837            retrieval_key: None,
1838        }])
1839        .with_redirect_depth(2)
1840        .with_budget_ms(9_000);
1841
1842        let v = serde_json::to_value(&p).unwrap();
1843        assert_eq!(v["redirect_depth"], 2, "hops counted UP from zero");
1844        assert_eq!(v["budget_ms"], 9_000, "milliseconds counted DOWN to zero");
1845        assert_eq!(p.hops_consumed(), 2);
1846        assert_eq!(p.budget_ms(), Some(9_000));
1847        assert_eq!(
1848            serde_json::from_value::<GetAvailabilityParams>(v).unwrap(),
1849            p
1850        );
1851    }
1852
1853    /// **Proves:** a zero time budget survives the wire as `Some(0)` and is NOT
1854    /// erased into `None`.
1855    /// **Catches:** a `skip_serializing_if` written over the VALUE rather than the
1856    /// Option (`is_zero`-style), which would make "you have no time left, do not ask
1857    /// onward" indistinguishable from "unbudgeted, use your own policy" — exactly
1858    /// inverting the field on the one hop where it matters most.
1859    #[test]
1860    fn a_zero_time_budget_is_not_the_same_as_an_absent_one() {
1861        let exhausted = GetAvailabilityParams::new(vec![]).with_budget_ms(0);
1862        let v = serde_json::to_value(&exhausted).unwrap();
1863
1864        assert_eq!(v["budget_ms"], 0, "an exhausted budget stays on the wire");
1865        assert_eq!(
1866            serde_json::from_value::<GetAvailabilityParams>(v)
1867                .unwrap()
1868                .budget_ms(),
1869            Some(0)
1870        );
1871        assert_eq!(
1872            GetAvailabilityParams::new(vec![]).budget_ms(),
1873            None,
1874            "unbudgeted is a different state from budget zero"
1875        );
1876    }
1877
1878    /// **Proves:** `ask_id` round-trips verbatim under its own key, and is NOT the
1879    /// JSON-RPC `id`.
1880    /// **Catches:** an implementation that reuses the envelope correlator for dedup.
1881    /// The fixture puts a hardcoded `"id": 1` — the exact value dig-node was sending
1882    /// — beside a real 16-byte ask id in one envelope, so a reader that took the
1883    /// correlator would see `1` and disagree with both assertions.
1884    #[test]
1885    fn the_ask_id_is_not_the_jsonrpc_correlator() {
1886        const ASK_ID: &str = "3f9c1a04b7e25d68f0a1c3b5d7e9f012";
1887        assert_eq!(ASK_ID.len(), 32, "16 random bytes as lowercase hex");
1888
1889        let envelope = json!({
1890            "jsonrpc": "2.0",
1891            "id": 1,
1892            "method": "dig.getAvailability",
1893            "params": {
1894                "items": [ { "store_id": "ab".repeat(32) } ],
1895                "ask_id": ASK_ID,
1896            }
1897        });
1898
1899        let p: GetAvailabilityParams = serde_json::from_value(envelope["params"].clone()).unwrap();
1900        assert_eq!(p.ask_id(), Some(ASK_ID));
1901        assert_ne!(
1902            p.ask_id(),
1903            Some("1"),
1904            "the dedup identity must not be read from the envelope `id`"
1905        );
1906        assert_eq!(envelope["id"], 1, "the correlator is untouched beside it");
1907    }
1908
1909    /// **Proves:** `absence_established` distinguishes THREE states on the wire —
1910    /// asserted, explicitly-not-established, and unknown-because-older-server — and
1911    /// that the unknown state serializes as an ABSENT key rather than `false`.
1912    /// **Catches:** the collapse this field exists to prevent. The fixture carries
1913    /// all three answers in ONE batch, so a `bool` with `#[serde(default)]` (which
1914    /// would read the old server answer as `false`) makes the second and third
1915    /// answers compare EQUAL and the test fails; a fixture with only one answer
1916    /// could not see that.
1917    #[test]
1918    fn absence_established_keeps_absent_distinct_from_false() {
1919        let asserted = AvailabilityAnswer {
1920            available: false,
1921            absence_established: Some(true),
1922            ..Default::default()
1923        };
1924        let inconclusive = AvailabilityAnswer {
1925            available: false,
1926            absence_established: Some(false),
1927            ..Default::default()
1928        };
1929        let older_server = AvailabilityAnswer {
1930            available: false,
1931            ..Default::default()
1932        };
1933
1934        assert_ne!(
1935            inconclusive, older_server,
1936            "an explicit `false` is a claim; an absent field is not"
1937        );
1938        assert_eq!(asserted.absence_established_or_unknown(), Some(true));
1939        assert_eq!(inconclusive.absence_established_or_unknown(), Some(false));
1940        assert_eq!(
1941            older_server.absence_established_or_unknown(),
1942            None,
1943            "an older server makes no claim either way"
1944        );
1945
1946        let batch = serde_json::to_value(AvailabilityBatch {
1947            items: vec![asserted, inconclusive, older_server],
1948        })
1949        .unwrap();
1950        assert_eq!(batch["items"][0]["absence_established"], true);
1951        assert_eq!(batch["items"][1]["absence_established"], false);
1952        assert!(
1953            batch["items"][2].get("absence_established").is_none(),
1954            "the unknown state is an absent key, never `false` and never `null`"
1955        );
1956    }
1957
1958    /// **Proves:** an OLDER client can still read a NEWER answer — the added field
1959    /// does not break the shipped shape (§5.1).
1960    #[test]
1961    fn an_answer_carrying_the_new_field_still_parses_as_the_shipped_shape() {
1962        let newer = json!({
1963            "items": [ { "available": false, "absence_established": true } ]
1964        });
1965        let b: AvailabilityBatch = serde_json::from_value(newer).unwrap();
1966        assert_eq!(b.items.len(), 1);
1967        assert!(!b.items[0].available);
1968        assert_eq!(b.items[0].absence_established_or_unknown(), Some(true));
1969    }
1970
1971    /// **Proves:** the hop budget an availability ask carries is the SAME field,
1972    /// with the same key, type and value, that a `-32008` redirect hands back and
1973    /// that `dig.getContent` / `dig.fetchRange` already echo — one field, one
1974    /// interpretation, counted UP toward `max_redirects`.
1975    /// **Catches:** a second reading of the budget in this crate (a remaining
1976    /// allowance counting DOWN, a differently-named key, a differently-typed
1977    /// value) — the byte-drift the shipped redirect contract exists to prevent.
1978    #[test]
1979    fn availability_hop_budget_mirrors_the_redirect_budget() {
1980        let handed_back = RedirectInfo {
1981            content: ContentRef {
1982                store_id: "ab".repeat(32),
1983                root: None,
1984                retrieval_key: None,
1985            },
1986            providers: vec![],
1987            redirect_depth: 3,
1988            max_redirects: 4,
1989        };
1990        let echoed = handed_back.redirect_depth;
1991
1992        let availability = serde_json::to_value(
1993            GetAvailabilityParams::new(vec![AvailabilityQuery {
1994                store_id: "ab".repeat(32),
1995                root: None,
1996                retrieval_key: None,
1997            }])
1998            .with_redirect_depth(echoed),
1999        )
2000        .unwrap();
2001        let content = serde_json::to_value(GetContentParams {
2002            store_id: "ab".repeat(32),
2003            retrieval_key: "cd".repeat(32),
2004            root: None,
2005            offset: None,
2006            mode: None,
2007            redirect_depth: Some(echoed),
2008        })
2009        .unwrap();
2010        let range = serde_json::to_value(
2011            FetchRangeParams::resource("ab".repeat(32), "cd".repeat(32), "ef".repeat(32), 1)
2012                .with_redirect_depth(echoed),
2013        )
2014        .unwrap();
2015
2016        for (method, params) in [
2017            ("dig.getAvailability", &availability),
2018            ("dig.getContent", &content),
2019            ("dig.fetchRange", &range),
2020        ] {
2021            assert_eq!(
2022                params["redirect_depth"], 3,
2023                "{method} must carry the echoed depth under `redirect_depth`"
2024            );
2025        }
2026        assert!(
2027            handed_back.redirect_depth < handed_back.max_redirects,
2028            "the budget counts UP toward `max_redirects`"
2029        );
2030    }
2031
2032    /// **Proves:** a NEWER client's params — carrying a field this build does not
2033    /// know — still deserialize, so a hop-bearing ask is never refused outright by
2034    /// an older responder that simply ignores the budget.
2035    /// **Catches:** a `#[serde(deny_unknown_fields)]` added to the params type,
2036    /// which would turn every forward-compatible extension into a hard parse
2037    /// failure at the peer boundary.
2038    #[test]
2039    fn get_availability_params_tolerates_an_unknown_field() {
2040        let newer = json!({
2041            "items": [ { "store_id": "ab".repeat(32) } ],
2042            "redirect_depth": 1,
2043            "a_field_this_build_does_not_know": true
2044        });
2045        let p: GetAvailabilityParams = serde_json::from_value(newer).unwrap();
2046        assert_eq!(p.hops_consumed(), 1);
2047    }
2048}