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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
415#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
416pub struct GetAvailabilityParams {
417    /// The items to check. Capped at 512 per batch (past-cap items are dropped).
418    pub items: Vec<AvailabilityQuery>,
419}
420
421/// One availability answer. Only the fields relevant to the query's granularity
422/// are populated.
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
424#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
425pub struct AvailabilityAnswer {
426    /// Whether this node holds the queried item.
427    pub available: bool,
428    /// The roots held (store-granularity queries only).
429    #[serde(skip_serializing_if = "Option::is_none", default)]
430    pub roots: Option<Vec<HexId>>,
431    /// The full resource ciphertext length (resource-granularity only).
432    #[serde(skip_serializing_if = "Option::is_none", default)]
433    pub total_length: Option<u64>,
434    /// The chunk count (resource-granularity only).
435    #[serde(skip_serializing_if = "Option::is_none", default)]
436    pub chunk_count: Option<u64>,
437    /// Whether the whole item is held (root/resource-granularity only).
438    #[serde(skip_serializing_if = "Option::is_none", default)]
439    pub complete: Option<bool>,
440    /// Providers that hold the item — present on a miss when holders were
441    /// located (enriched answer).
442    #[serde(skip_serializing_if = "Option::is_none", default)]
443    pub providers: Option<Vec<Provider>>,
444}
445
446/// Result for [`dig.getAvailability`](crate::method::Method::GetAvailability) —
447/// one answer per query item, in order.
448#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
449#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
450pub struct AvailabilityBatch {
451    /// The per-item answers (index-aligned to the query items served).
452    pub items: Vec<AvailabilityAnswer>,
453}
454
455// ===========================================================================
456// dig.listInventory  (PEER)
457// ===========================================================================
458
459/// Params for [`dig.listInventory`](crate::method::Method::ListInventory).
460#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
461#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
462pub struct ListInventoryParams {
463    /// The store to list roots for (64-hex). Absent ⇒ list all stores served.
464    #[serde(skip_serializing_if = "Option::is_none", default)]
465    pub store_id: Option<HexId>,
466    /// The maximum number of entries to return.
467    #[serde(skip_serializing_if = "Option::is_none", default)]
468    pub limit: Option<u64>,
469}
470
471/// Result for [`dig.listInventory`](crate::method::Method::ListInventory).
472///
473/// With a `store_id` the node returns the roots it holds for that store; without
474/// one it returns the stores it serves. `#[serde(untagged)]` keeps the wire flat
475/// (`{"roots": …}` or `{"stores": …}`).
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(untagged)]
478#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
479pub enum Inventory {
480    /// The roots held for a specific store.
481    ForStore {
482        /// The store launcher id (echoed, 64-hex).
483        store_id: HexId,
484        /// The roots this node holds for the store.
485        roots: Vec<HexId>,
486    },
487    /// The stores this node serves (no `store_id` given).
488    AllStores {
489        /// The store launcher ids served.
490        stores: Vec<HexId>,
491    },
492}
493
494// ===========================================================================
495// dig.fetchRange  (PEER)
496// ===========================================================================
497
498/// Params for [`dig.fetchRange`](crate::method::Method::FetchRange) — a single
499/// range frame of a resource this node holds.
500#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
501#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
502pub struct FetchRangeParams {
503    /// The store launcher id (64-hex, required).
504    pub store_id: HexId,
505    /// The generation root (64-hex, required for a resource fetch).
506    pub root: HexId,
507    /// `SHA-256(urn)` (64-hex, required for a resource fetch).
508    pub retrieval_key: HexId,
509    /// The range start (default 0).
510    #[serde(skip_serializing_if = "Option::is_none", default)]
511    pub offset: Option<u64>,
512    /// The range length in bytes (> 0; clamped to the window cap).
513    pub length: u64,
514    /// Whole-capsule mode (default false). Capsule range fetch is not yet
515    /// served; a `true` here yields `-32004`.
516    #[serde(skip_serializing_if = "Option::is_none", default)]
517    pub capsule: Option<bool>,
518    /// The redirect budget already consumed (echoed from a `-32008` redirect).
519    #[serde(skip_serializing_if = "Option::is_none", default)]
520    pub redirect_depth: Option<u64>,
521}
522
523/// One range frame of a resource: a byte window, plus the per-resource
524/// verification metadata that makes the window independently checkable.
525///
526/// EVERY frame may carry that metadata, and a server SHOULD attach it to every
527/// frame rather than only the first: a client fetching ranges in parallel from
528/// many holders cannot check a frame that declares no
529/// [`root`](Self::root), so a wrong-generation source would be detectable only
530/// after the whole resource had been paid for in bandwidth. The window is exactly
531/// the span the caller requested — never widened.
532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
533#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
534pub struct RangeFrame {
535    /// The window start offset (echoed).
536    pub offset: u64,
537    /// This window's byte length.
538    pub length: u64,
539    /// This window's ciphertext, base64.
540    pub bytes: String,
541    /// Whether this frame ends the resource.
542    pub complete: bool,
543    /// The full resource ciphertext length. MAY appear on any frame.
544    #[serde(skip_serializing_if = "Option::is_none", default)]
545    pub total_length: Option<u64>,
546    /// Per-chunk ciphertext lengths of the full resource. MAY appear on any frame.
547    #[serde(skip_serializing_if = "Option::is_none", default)]
548    pub chunk_lens: Option<Vec<u64>>,
549    /// This frame's first chunk index — the pre-existing alias of
550    /// [`first_chunk_index`](Self::first_chunk_index), carrying the same value.
551    /// OMITTED when the frame's window does not begin on a chunk boundary.
552    #[serde(skip_serializing_if = "Option::is_none", default)]
553    pub chunk_index: Option<u64>,
554    /// Whole-resource merkle proof, base64. MAY appear on any frame — and SHOULD,
555    /// so a frame fetched from any holder is independently checkable on arrival.
556    #[serde(skip_serializing_if = "Option::is_none", default)]
557    pub inclusion_proof: Option<String>,
558    /// The chain-anchored root (64-hex) this frame's resource verified against.
559    /// MAY appear on any frame.
560    ///
561    /// NOT A TRUST ANCHOR BY ITSELF. The client resolves the resource's root from
562    /// the URN (chain-anchored) and PINS it before fetching; a peer-declared value
563    /// never replaces that pinned root. What this field provides is a
564    /// generation-CONSISTENCY check: a frame declaring a root other than the pinned
565    /// one is REJECTED and attributed to the offending peer (NC-9 fail-closed). So
566    /// a declared root can only ever cause rejection — it can never move the pinned
567    /// root, and never makes an unverified frame acceptable.
568    #[serde(skip_serializing_if = "Option::is_none", default)]
569    pub root: Option<HexId>,
570    /// **RESERVED — not currently derivable; a server MUST NOT emit it.**
571    ///
572    /// Per-chunk merkle inclusion proofs for the chunks a frame covers. No such
573    /// proof exists in the current store format: the generation root's merkle
574    /// leaves are per-RESOURCE (a leaf is the SHA-256 of a resource's WHOLE
575    /// ciphertext), so a single chunk has no leaf to prove. A client MUST NOT
576    /// require this field, and per-range verification instead uses the
577    /// whole-resource [`inclusion_proof`](Self::inclusion_proof) together with the
578    /// per-frame [`root`](Self::root)/[`chunk_lens`](Self::chunk_lens) metadata.
579    ///
580    /// Making it derivable requires a per-resource chunk-level commitment in the
581    /// store format first (tracked as `dig_ecosystem#1601`). The field is kept in
582    /// the wire type, unused, so populating it later is additive (§5.1); each entry
583    /// would be an opaque base64 proof blob, since this pure level-00 wire type
584    /// MUST NOT depend on the merkle primitive.
585    #[serde(skip_serializing_if = "Option::is_none", default)]
586    pub range_proof: Option<Vec<String>>,
587    /// The chunk index of the first chunk in this frame (0-based, into the
588    /// resource's chunk sequence described by [`chunk_lens`](Self::chunk_lens)).
589    ///
590    /// Present only when the frame's window begins EXACTLY on a chunk boundary; a
591    /// mid-chunk window omits it rather than assert an index the caller's own
592    /// alignment check would contradict. The served window is exactly the requested
593    /// span — a server MUST NOT widen a range to a chunk boundary — so a frame is
594    /// chunk-aligned only when the caller asked for an aligned span.
595    #[serde(skip_serializing_if = "Option::is_none", default)]
596    pub first_chunk_index: Option<u64>,
597}
598
599// ===========================================================================
600// dig.getModuleInfo / dig.fetchModuleRange  (PEER — whole-module pull, #1576)
601// ===========================================================================
602
603/// Params for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
604/// handshake a peer reads before range-pulling a whole `.dig` module for
605/// `(store, root)`.
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
607#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
608pub struct GetModuleInfoParams {
609    /// The store launcher id (64-hex, required).
610    pub store_id: HexId,
611    /// The generation root whose `.dig` module is being pulled (64-hex, required).
612    pub root: HexId,
613}
614
615/// Result for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
616/// transfer descriptor of a whole `.dig` module.
617///
618/// The whole-module blob is content-addressed + immutable (the `.dig` container
619/// is byte-identical by construction). [`module_hash`](Self::module_hash) is the
620/// content id of the assembled blob; a puller verifies each pulled range against
621/// [`chunk_hashes`](Self::chunk_hashes) (per-peer attribution on a multi-source
622/// pull) and the fully-assembled blob against `module_hash`, THEN verifies the
623/// assembled module against its chain-anchored root before admitting + resharing
624/// (NC-9 verified-content-not-safe-content).
625#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
626#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
627pub struct ModuleInfo {
628    /// The total byte length of the whole `.dig` module blob.
629    pub total_size: u64,
630    /// The content id of the fully-assembled module blob (64-hex `SHA-256` of the
631    /// module bytes). The puller checks the assembled blob against this.
632    pub module_hash: HexId,
633    /// Per-chunk content hashes (64-hex each) in ascending chunk order, covering
634    /// the blob in [`total_size`](Self::total_size)-spanning fixed-size chunks
635    /// (the trailing chunk may be short). A puller checks each pulled
636    /// [`RangeFrame`] against the covering entries for per-source attribution on a
637    /// multi-source pull (a tampered range fails closed before assembly).
638    pub chunk_hashes: Vec<HexId>,
639    /// Per-chunk byte lengths (in the same order as [`chunk_hashes`](Self::chunk_hashes)).
640    /// MUST have the same length as `chunk_hashes` and MUST sum to `total_size`.
641    /// A puller uses these to map a fetched byte range to the covering chunk hash(es).
642    pub chunk_lens: Vec<u64>,
643}
644
645/// Params for [`dig.fetchModuleRange`](crate::method::Method::FetchModuleRange) —
646/// a single range frame of the whole `.dig` module blob for `(store, root)`.
647///
648/// The response reuses [`RangeFrame`]: [`bytes`](RangeFrame::bytes) carries the
649/// window of the module blob (base64), [`total_length`](RangeFrame::total_length)
650/// echoes the whole-module size on the first frame, and
651/// [`complete`](RangeFrame::complete) ends the stream.
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
654pub struct FetchModuleRangeParams {
655    /// The store launcher id (64-hex, required).
656    pub store_id: HexId,
657    /// The generation root whose `.dig` module is being pulled (64-hex, required).
658    pub root: HexId,
659    /// The range start into the module blob (default 0).
660    #[serde(skip_serializing_if = "Option::is_none", default)]
661    pub offset: Option<u64>,
662    /// The range length in bytes (> 0; clamped to the window cap).
663    pub length: u64,
664}
665
666// ===========================================================================
667// dig.stage  (CONTROL — loopback / in-process only)
668// ===========================================================================
669
670/// Params for [`dig.stage`](crate::method::Method::Stage) — compile a local
671/// folder into a capsule `.dig` module in-process.
672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
673#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
674pub struct StageParams {
675    /// The absolute path to the folder to compile.
676    pub dir: String,
677    /// The target store launcher id (64-hex). Absent ⇒ an ephemeral,
678    /// content-derived id (a preview).
679    #[serde(skip_serializing_if = "Option::is_none", default)]
680    pub store_id: Option<HexId>,
681    /// The store salt (64-hex). Present ⇒ a private store.
682    #[serde(skip_serializing_if = "Option::is_none", default)]
683    pub salt: Option<HexId>,
684    /// Optional DIGHub-style manifest metadata to embed.
685    #[serde(skip_serializing_if = "Option::is_none", default)]
686    pub metadata: Option<serde_json::Value>,
687}
688
689/// Result for [`dig.stage`](crate::method::Method::Stage) — the compiled capsule.
690#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
691#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
692pub struct StageResult {
693    /// The canonical capsule identity, `storeId:rootHash`.
694    pub capsule: String,
695    /// The store launcher id (64-hex).
696    pub store_id: HexId,
697    /// The compiled generation root (64-hex).
698    pub root: HexId,
699    /// The filesystem path to the compiled `.dig` module.
700    pub module_path: String,
701    /// The module size in bytes.
702    pub size: u64,
703    /// The `chia://storeId:rootHash/` content address.
704    #[serde(skip_serializing_if = "Option::is_none", default)]
705    pub content_address: Option<String>,
706    /// The relative paths compiled into the capsule.
707    #[serde(default)]
708    pub files: Vec<String>,
709    /// Whether this is an ephemeral preview (not advancing a real store).
710    #[serde(skip_serializing_if = "Option::is_none", default)]
711    pub ephemeral: Option<bool>,
712}
713
714// ===========================================================================
715// cache.*  (CONTROL — loopback / in-process only)
716// ===========================================================================
717
718/// Result for [`cache.getConfig`](crate::method::Method::CacheGetConfig).
719///
720/// The canonical field name for the cache path is `cache_dir` everywhere (the
721/// shell's historical `dir` is unified onto this name).
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
723#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
724pub struct CacheConfig {
725    /// The on-disk cache size cap in bytes (floored at 64 MiB).
726    pub cap_bytes: u64,
727    /// The bytes currently used.
728    pub used_bytes: u64,
729    /// The effective resolved cache directory.
730    pub cache_dir: String,
731    /// Whether that directory is the canonical shared location (vs a
732    /// process-private fallback).
733    pub shared: bool,
734}
735
736/// Params for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
737#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
738#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
739pub struct SetCapBytesParams {
740    /// The requested cap in bytes (floored at 64 MiB by the node).
741    pub cap_bytes: u64,
742}
743
744/// Result for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
745#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
746#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
747pub struct SetCapBytesResult {
748    /// The effective cap after flooring.
749    pub cap_bytes: u64,
750}
751
752/// One durable cached-module entry.
753#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
754#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
755pub struct CachedCapsule {
756    /// The canonical capsule identity, `storeId:rootHash`.
757    pub capsule: String,
758    /// The store launcher id (64-hex).
759    pub store_id: HexId,
760    /// The generation root (64-hex).
761    pub root: HexId,
762    /// The module size in bytes.
763    pub size_bytes: u64,
764    /// When the module was last used (unix ms).
765    pub last_used_unix_ms: u64,
766}
767
768/// Result for [`cache.listCached`](crate::method::Method::CacheListCached).
769#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
770#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
771pub struct CachedList {
772    /// The cached capsules.
773    pub cached: Vec<CachedCapsule>,
774}
775
776/// Params for a capsule-keyed cache op
777/// ([`cache.removeCached`](crate::method::Method::CacheRemoveCached),
778/// [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache)).
779#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
780#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
781pub struct CapsuleKey {
782    /// The store launcher id (64-hex).
783    pub store_id: HexId,
784    /// The generation root (64-hex).
785    pub root: HexId,
786}
787
788/// Result for [`cache.removeCached`](crate::method::Method::CacheRemoveCached).
789#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
790#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
791pub struct RemoveCachedResult {
792    /// Whether an entry was removed.
793    pub removed: bool,
794}
795
796/// Result for [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache).
797///
798/// A failed fetch is reported in-band (`status = "failed"` + `message`) so the
799/// caller can show it without treating it as a transport error.
800#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
802pub struct FetchAndCacheResult {
803    /// `"cached"`, `"already_cached"`, or `"failed"`.
804    pub status: String,
805    /// The fetched module size in bytes (on success).
806    #[serde(skip_serializing_if = "Option::is_none", default)]
807    pub size_bytes: Option<u64>,
808    /// The served generation root (64-hex, on success).
809    #[serde(skip_serializing_if = "Option::is_none", default)]
810    pub served_root: Option<HexId>,
811    /// The failure message (on `status = "failed"`).
812    #[serde(skip_serializing_if = "Option::is_none", default)]
813    pub message: Option<String>,
814}
815
816// ===========================================================================
817// control.peerStatus  (CONTROL — loopback / in-process only)
818// ===========================================================================
819
820/// Result for [`control.peerStatus`](crate::method::Method::ControlPeerStatus) —
821/// a snapshot of the node's L7 peer network. Always safe to call; reports
822/// `running: false` on the FFI path.
823#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
824#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
825pub struct PeerStatusSnapshot {
826    /// Whether a peer network is currently active.
827    pub running: bool,
828    /// This node's `peer_id` (64-hex), if a peer network is running.
829    #[serde(skip_serializing_if = "Option::is_none", default)]
830    pub peer_id: Option<HexId>,
831    /// The DIG network id.
832    pub network_id: String,
833    /// The relay reservation posture.
834    pub relay: RelayStatus,
835    /// The number of currently connected peers.
836    pub connected_peers: u64,
837    /// The last peer-network error, if any.
838    #[serde(skip_serializing_if = "Option::is_none", default)]
839    pub last_error: Option<String>,
840}
841
842// ===========================================================================
843// cache.stats  (CONTROL — loopback / in-process only)
844// ===========================================================================
845
846/// The decoded-content cache hit/miss counters carried in
847/// [`CacheStats`](CacheStats::content_cache).
848#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
849#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
850pub struct ContentCacheCounters {
851    /// Session decoded-content cache hits.
852    pub hits: u64,
853    /// Session decoded-content cache misses.
854    pub misses: u64,
855}
856
857/// Result for [`cache.stats`](crate::method::Method::CacheStats) — cache
858/// telemetry beside [`cache.getConfig`](crate::method::Method::CacheGetConfig):
859/// the reserved cap + live usage, the cached-capsule count + total on-disk
860/// bytes, and the session eviction + content-cache counters.
861#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
862#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
863pub struct CacheStats {
864    /// The on-disk cache size cap in bytes.
865    pub cap_bytes: u64,
866    /// The bytes currently used on disk.
867    pub used_bytes: u64,
868    /// The number of durable cached capsules.
869    pub entry_count: u64,
870    /// The total on-disk bytes across the cached capsules.
871    pub total_bytes: u64,
872    /// Capsules evicted this session.
873    pub evicted_count: u64,
874    /// Bytes evicted this session.
875    pub evicted_bytes: u64,
876    /// The decoded-content cache hit/miss counters.
877    pub content_cache: ContentCacheCounters,
878}
879
880// ===========================================================================
881// control.subscribe / control.unsubscribe / control.listSubscriptions
882// (CONTROL — loopback / in-process only)
883// ===========================================================================
884
885/// Params for [`control.subscribe`](crate::method::Method::ControlSubscribe) and
886/// [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
887#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
888#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
889pub struct SubscribeParams {
890    /// The store launcher id to (un)subscribe (64-hex).
891    pub store_id: HexId,
892}
893
894/// Result for [`control.subscribe`](crate::method::Method::ControlSubscribe).
895#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
896#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
897pub struct SubscribeResult {
898    /// Always `true` — the store is subscribed after this call.
899    pub subscribed: bool,
900    /// Whether this call ADDED the subscription (`false` ⇒ already subscribed).
901    pub added: bool,
902    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
903    pub store_id: HexId,
904}
905
906/// Result for [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
907#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
908#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
909pub struct UnsubscribeResult {
910    /// Always `false` — the store is not subscribed after this call.
911    pub subscribed: bool,
912    /// Whether this call REMOVED a subscription (`false` ⇒ was not subscribed).
913    pub removed: bool,
914    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
915    pub store_id: HexId,
916}
917
918/// Result for
919/// [`control.listSubscriptions`](crate::method::Method::ControlListSubscriptions).
920#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
921#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
922pub struct SubscriptionsList {
923    /// The persisted subscribed store ids (64-hex each).
924    pub subscriptions: Vec<HexId>,
925    /// The subscription count (`subscriptions.len()`).
926    pub count: u64,
927}
928
929// ===========================================================================
930// control.peers.connect / control.peers.disconnect
931// (CONTROL — loopback / in-process only)
932// ===========================================================================
933
934/// Params for [`control.peers.connect`](crate::method::Method::ControlPeersConnect)
935/// and [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
936#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
937#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
938pub struct PeerConnectParams {
939    /// The peer to dial/drop — a dialable address, or a known peer's `peer_id`
940    /// (64-hex) to resolve an already-connected peer.
941    pub peer: String,
942}
943
944/// Result for
945/// [`control.peers.connect`](crate::method::Method::ControlPeersConnect).
946#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
947#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
948pub struct PeerConnectResult {
949    /// Always `true` on success — the peer is a counted, connected pool member.
950    pub connected: bool,
951    /// The connected peer's stable `peer_id` (64-hex).
952    pub peer_id: HexId,
953}
954
955/// Result for
956/// [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
957///
958/// Idempotent: disconnecting a peer that is not connected succeeds as a no-op.
959#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
960#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
961pub struct PeerDisconnectResult {
962    /// Always `true` — the peer is not in the pool after this call.
963    pub disconnected: bool,
964    /// The dropped peer's `peer_id` (trimmed + lower-cased, 64-hex).
965    pub peer_id: HexId,
966}
967
968// ===========================================================================
969// dig.health / dig.methods / rpc.discover  (discovery)
970// ===========================================================================
971
972/// Result for [`dig.health`](crate::method::Method::Health) — liveness + a
973/// capability summary.
974#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
975#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
976pub struct Health {
977    /// Liveness — `"ok"` when the node can serve.
978    pub status: String,
979    /// The node's software version.
980    #[serde(skip_serializing_if = "Option::is_none", default)]
981    pub version: Option<String>,
982    /// The DIG network id the node serves.
983    #[serde(skip_serializing_if = "Option::is_none", default)]
984    pub network_id: Option<String>,
985    /// The method names this node implements (its profile).
986    #[serde(default)]
987    pub methods: Vec<String>,
988}
989
990/// Result for [`dig.methods`](crate::method::Method::Methods) — the method names
991/// this node implements (agent self-describe).
992#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
993#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
994pub struct Methods {
995    /// The implemented method names.
996    pub methods: Vec<String>,
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002
1003    /// **Proves:** `ContentChunk` round-trips a node-profile window (no
1004    /// network-profile fields) without inventing keys.
1005    /// **Catches:** a missing `skip_serializing_if` that would leak `null`
1006    /// network-profile fields onto the node profile.
1007    #[test]
1008    fn content_chunk_node_profile_is_lean() {
1009        let c = ContentChunk {
1010            ciphertext: "AAA=".into(),
1011            root: "ab".repeat(32),
1012            complete: false,
1013            next_offset: Some(3_145_728),
1014            inclusion_proof: Some("cHJvb2Y=".into()),
1015            chunk_lens: Some(vec![10, 20]),
1016            source: Some("local".into()),
1017            total_length: None,
1018            length: None,
1019            offset: None,
1020            program_hash: None,
1021        };
1022        let v = serde_json::to_value(&c).unwrap();
1023        assert_eq!(v["source"], "local");
1024        assert!(
1025            v.get("total_length").is_none(),
1026            "node profile must omit total_length"
1027        );
1028        assert!(v.get("program_hash").is_none());
1029        assert_eq!(serde_json::from_value::<ContentChunk>(v).unwrap(), c);
1030    }
1031
1032    /// **Proves:** the network-profile fields serialize when present.
1033    #[test]
1034    fn content_chunk_network_profile_carries_extras() {
1035        let c = ContentChunk {
1036            ciphertext: "AAA=".into(),
1037            root: "cd".repeat(32),
1038            complete: true,
1039            next_offset: None,
1040            inclusion_proof: None,
1041            chunk_lens: None,
1042            source: None,
1043            total_length: Some(100),
1044            length: Some(100),
1045            offset: Some(0),
1046            program_hash: Some("ef".repeat(32)),
1047        };
1048        let v = serde_json::to_value(&c).unwrap();
1049        assert_eq!(v["total_length"], 100);
1050        assert_eq!(v["length"], 100);
1051        assert!(v.get("source").is_none());
1052    }
1053
1054    /// **Proves:** the untagged `Inventory` picks `ForStore` vs `AllStores` by
1055    /// shape.
1056    /// **Catches:** a lost `#[serde(untagged)]` that would tag the variant.
1057    #[test]
1058    fn inventory_untagged_by_shape() {
1059        let for_store = Inventory::ForStore {
1060            store_id: "ab".repeat(32),
1061            roots: vec!["cd".repeat(32)],
1062        };
1063        let s = serde_json::to_string(&for_store).unwrap();
1064        assert!(s.contains("\"roots\""));
1065        assert!(!s.contains("ForStore"));
1066        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), for_store);
1067
1068        let all = Inventory::AllStores {
1069            stores: vec!["ef".repeat(32)],
1070        };
1071        let s = serde_json::to_string(&all).unwrap();
1072        assert!(s.contains("\"stores\""));
1073        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), all);
1074    }
1075
1076    /// **Proves:** `RedirectInfo` serializes the full redirect payload the
1077    /// `-32008` envelope carries.
1078    #[test]
1079    fn redirect_info_shape() {
1080        let r = RedirectInfo {
1081            content: ContentRef {
1082                store_id: "ab".repeat(32),
1083                root: Some("cd".repeat(32)),
1084                retrieval_key: Some("ef".repeat(32)),
1085            },
1086            providers: vec![Provider {
1087                peer_id: "12".repeat(32),
1088                addresses: vec![PeerAddress {
1089                    host: "::1".into(),
1090                    port: 9444,
1091                    kind: "direct".into(),
1092                }],
1093            }],
1094            redirect_depth: 1,
1095            max_redirects: 4,
1096        };
1097        let v = serde_json::to_value(&r).unwrap();
1098        assert_eq!(v["redirect_depth"], 1);
1099        assert_eq!(v["max_redirects"], 4);
1100        assert_eq!(v["providers"][0]["addresses"][0]["host"], "::1");
1101        assert_eq!(serde_json::from_value::<RedirectInfo>(v).unwrap(), r);
1102    }
1103
1104    /// **Proves:** `cache.stats` models the live dig-node result field-for-field
1105    /// (the nested `content_cache{hits,misses}` object included).
1106    /// **Catches:** a drift from the node's `cache.stats` wire shape (#1075).
1107    #[test]
1108    fn cache_stats_wire_shape() {
1109        let s = CacheStats {
1110            cap_bytes: 1 << 30,
1111            used_bytes: 2048,
1112            entry_count: 3,
1113            total_bytes: 2048,
1114            evicted_count: 1,
1115            evicted_bytes: 512,
1116            content_cache: ContentCacheCounters { hits: 7, misses: 2 },
1117        };
1118        let v = serde_json::to_value(s).unwrap();
1119        assert_eq!(v["cap_bytes"], 1 << 30);
1120        assert_eq!(v["entry_count"], 3);
1121        assert_eq!(v["content_cache"]["hits"], 7);
1122        assert_eq!(v["content_cache"]["misses"], 2);
1123        assert_eq!(serde_json::from_value::<CacheStats>(v).unwrap(), s);
1124    }
1125
1126    /// **Proves:** the subscription-management results carry the exact
1127    /// `{subscribed, added|removed, store_id}` / `{subscriptions, count}` shapes
1128    /// the live node returns.
1129    #[test]
1130    fn subscription_result_shapes() {
1131        let sub = SubscribeResult {
1132            subscribed: true,
1133            added: true,
1134            store_id: "ab".repeat(32),
1135        };
1136        let v = serde_json::to_value(&sub).unwrap();
1137        assert_eq!(v["subscribed"], true);
1138        assert_eq!(v["added"], true);
1139        assert_eq!(serde_json::from_value::<SubscribeResult>(v).unwrap(), sub);
1140
1141        let unsub = UnsubscribeResult {
1142            subscribed: false,
1143            removed: true,
1144            store_id: "cd".repeat(32),
1145        };
1146        let v = serde_json::to_value(&unsub).unwrap();
1147        assert_eq!(v["subscribed"], false);
1148        assert_eq!(v["removed"], true);
1149        assert_eq!(
1150            serde_json::from_value::<UnsubscribeResult>(v).unwrap(),
1151            unsub
1152        );
1153
1154        let list = SubscriptionsList {
1155            subscriptions: vec!["ef".repeat(32)],
1156            count: 1,
1157        };
1158        let v = serde_json::to_value(&list).unwrap();
1159        assert_eq!(v["count"], 1);
1160        assert_eq!(
1161            serde_json::from_value::<SubscriptionsList>(v).unwrap(),
1162            list
1163        );
1164    }
1165
1166    /// **Proves:** `ModuleInfo` carries `chunk_lens` covering every chunk, and
1167    /// round-trips with unknown future fields.
1168    /// **Catches:** a missing `chunk_lens` field that would leave a puller unable
1169    /// to map a fetched byte range to its covering chunk hash.
1170    /// **Invariants enforced by docs:** `chunk_lens` must have the same length as
1171    /// `chunk_hashes` and must sum to `total_size`.
1172    #[test]
1173    fn module_info_chunk_lens_shape() {
1174        let info = ModuleInfo {
1175            total_size: 1024,
1176            module_hash: "ab".repeat(32),
1177            chunk_hashes: vec!["cd".repeat(32), "ef".repeat(32)],
1178            chunk_lens: vec![512, 512],
1179        };
1180        let v = serde_json::to_value(&info).unwrap();
1181        assert_eq!(v["total_size"], 1024);
1182        assert_eq!(v["chunk_hashes"].as_array().unwrap().len(), 2);
1183        assert_eq!(v["chunk_lens"].as_array().unwrap().len(), 2);
1184        assert_eq!(v["chunk_lens"][0], 512);
1185        assert_eq!(v["chunk_lens"][1], 512);
1186        assert_eq!(serde_json::from_value::<ModuleInfo>(v).unwrap(), info);
1187    }
1188
1189    /// **Proves:** `ModuleInfo` deserialization REJECTS missing `chunk_lens` field.
1190    /// This is a REQUIRED field (not optional) — omitting it from the wire is a
1191    /// protocol violation and must fail-closed.
1192    #[test]
1193    fn module_info_rejects_missing_chunk_lens() {
1194        let json_str = r#"{"total_size": 2048, "module_hash": "1122334455667788990011223344556677889900112233445566778899001122", "chunk_hashes": []}"#;
1195        let result: Result<ModuleInfo, _> = serde_json::from_str(json_str);
1196        assert!(
1197            result.is_err(),
1198            "ModuleInfo must reject JSON missing the required chunk_lens field"
1199        );
1200        let err = result.unwrap_err();
1201        assert!(
1202            err.to_string().contains("chunk_lens"),
1203            "error message should mention chunk_lens: {}",
1204            err
1205        );
1206    }
1207
1208    /// **Proves:** the peer connect/disconnect params + results round-trip and
1209    /// match the node's `{connected|disconnected, peer_id}` shapes.
1210    #[test]
1211    fn peer_connect_disconnect_shapes() {
1212        let p = PeerConnectParams {
1213            peer: "12".repeat(32),
1214        };
1215        let v = serde_json::to_value(&p).unwrap();
1216        assert_eq!(serde_json::from_value::<PeerConnectParams>(v).unwrap(), p);
1217
1218        let c = PeerConnectResult {
1219            connected: true,
1220            peer_id: "12".repeat(32),
1221        };
1222        let v = serde_json::to_value(&c).unwrap();
1223        assert_eq!(v["connected"], true);
1224        assert_eq!(serde_json::from_value::<PeerConnectResult>(v).unwrap(), c);
1225
1226        let d = PeerDisconnectResult {
1227            disconnected: true,
1228            peer_id: "34".repeat(32),
1229        };
1230        let v = serde_json::to_value(&d).unwrap();
1231        assert_eq!(v["disconnected"], true);
1232        assert_eq!(
1233            serde_json::from_value::<PeerDisconnectResult>(v).unwrap(),
1234            d
1235        );
1236    }
1237
1238    /// **Proves:** `cache.getConfig` uses the canonical `cache_dir` field name.
1239    /// **Catches:** a regression to the shell's historical `dir` name.
1240    #[test]
1241    fn cache_config_field_name_is_cache_dir() {
1242        let c = CacheConfig {
1243            cap_bytes: 1 << 30,
1244            used_bytes: 0,
1245            cache_dir: "/var/cache/dig".into(),
1246            shared: true,
1247        };
1248        let v = serde_json::to_value(&c).unwrap();
1249        assert!(v.get("cache_dir").is_some());
1250        assert!(v.get("dir").is_none(), "must not use the legacy `dir` name");
1251    }
1252}