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. The first frame (`offset == 0`) carries the
524/// per-resource verification metadata; later frames carry only the window.
525#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
526#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
527pub struct RangeFrame {
528    /// The window start offset (echoed).
529    pub offset: u64,
530    /// This window's byte length.
531    pub length: u64,
532    /// This window's ciphertext, base64.
533    pub bytes: String,
534    /// Whether this frame ends the resource.
535    pub complete: bool,
536    /// The full resource ciphertext length. First frame only.
537    #[serde(skip_serializing_if = "Option::is_none", default)]
538    pub total_length: Option<u64>,
539    /// Per-chunk ciphertext lengths of the full resource. First frame only.
540    #[serde(skip_serializing_if = "Option::is_none", default)]
541    pub chunk_lens: Option<Vec<u64>>,
542    /// This frame's chunk index. First frame only (`0`).
543    #[serde(skip_serializing_if = "Option::is_none", default)]
544    pub chunk_index: Option<u64>,
545    /// Whole-resource merkle proof, base64. First frame only.
546    #[serde(skip_serializing_if = "Option::is_none", default)]
547    pub inclusion_proof: Option<String>,
548    /// The chain-anchored root (64-hex). First frame only.
549    #[serde(skip_serializing_if = "Option::is_none", default)]
550    pub root: Option<HexId>,
551}
552
553// ===========================================================================
554// dig.stage  (CONTROL — loopback / in-process only)
555// ===========================================================================
556
557/// Params for [`dig.stage`](crate::method::Method::Stage) — compile a local
558/// folder into a capsule `.dig` module in-process.
559#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
560#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
561pub struct StageParams {
562    /// The absolute path to the folder to compile.
563    pub dir: String,
564    /// The target store launcher id (64-hex). Absent ⇒ an ephemeral,
565    /// content-derived id (a preview).
566    #[serde(skip_serializing_if = "Option::is_none", default)]
567    pub store_id: Option<HexId>,
568    /// The store salt (64-hex). Present ⇒ a private store.
569    #[serde(skip_serializing_if = "Option::is_none", default)]
570    pub salt: Option<HexId>,
571    /// Optional DIGHub-style manifest metadata to embed.
572    #[serde(skip_serializing_if = "Option::is_none", default)]
573    pub metadata: Option<serde_json::Value>,
574}
575
576/// Result for [`dig.stage`](crate::method::Method::Stage) — the compiled capsule.
577#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
578#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
579pub struct StageResult {
580    /// The canonical capsule identity, `storeId:rootHash`.
581    pub capsule: String,
582    /// The store launcher id (64-hex).
583    pub store_id: HexId,
584    /// The compiled generation root (64-hex).
585    pub root: HexId,
586    /// The filesystem path to the compiled `.dig` module.
587    pub module_path: String,
588    /// The module size in bytes.
589    pub size: u64,
590    /// The `chia://storeId:rootHash/` content address.
591    #[serde(skip_serializing_if = "Option::is_none", default)]
592    pub content_address: Option<String>,
593    /// The relative paths compiled into the capsule.
594    #[serde(default)]
595    pub files: Vec<String>,
596    /// Whether this is an ephemeral preview (not advancing a real store).
597    #[serde(skip_serializing_if = "Option::is_none", default)]
598    pub ephemeral: Option<bool>,
599}
600
601// ===========================================================================
602// cache.*  (CONTROL — loopback / in-process only)
603// ===========================================================================
604
605/// Result for [`cache.getConfig`](crate::method::Method::CacheGetConfig).
606///
607/// The canonical field name for the cache path is `cache_dir` everywhere (the
608/// shell's historical `dir` is unified onto this name).
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
611pub struct CacheConfig {
612    /// The on-disk cache size cap in bytes (floored at 64 MiB).
613    pub cap_bytes: u64,
614    /// The bytes currently used.
615    pub used_bytes: u64,
616    /// The effective resolved cache directory.
617    pub cache_dir: String,
618    /// Whether that directory is the canonical shared location (vs a
619    /// process-private fallback).
620    pub shared: bool,
621}
622
623/// Params for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
625#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
626pub struct SetCapBytesParams {
627    /// The requested cap in bytes (floored at 64 MiB by the node).
628    pub cap_bytes: u64,
629}
630
631/// Result for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
633#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
634pub struct SetCapBytesResult {
635    /// The effective cap after flooring.
636    pub cap_bytes: u64,
637}
638
639/// One durable cached-module entry.
640#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
641#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
642pub struct CachedCapsule {
643    /// The canonical capsule identity, `storeId:rootHash`.
644    pub capsule: String,
645    /// The store launcher id (64-hex).
646    pub store_id: HexId,
647    /// The generation root (64-hex).
648    pub root: HexId,
649    /// The module size in bytes.
650    pub size_bytes: u64,
651    /// When the module was last used (unix ms).
652    pub last_used_unix_ms: u64,
653}
654
655/// Result for [`cache.listCached`](crate::method::Method::CacheListCached).
656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
657#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
658pub struct CachedList {
659    /// The cached capsules.
660    pub cached: Vec<CachedCapsule>,
661}
662
663/// Params for a capsule-keyed cache op
664/// ([`cache.removeCached`](crate::method::Method::CacheRemoveCached),
665/// [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache)).
666#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
667#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
668pub struct CapsuleKey {
669    /// The store launcher id (64-hex).
670    pub store_id: HexId,
671    /// The generation root (64-hex).
672    pub root: HexId,
673}
674
675/// Result for [`cache.removeCached`](crate::method::Method::CacheRemoveCached).
676#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
677#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
678pub struct RemoveCachedResult {
679    /// Whether an entry was removed.
680    pub removed: bool,
681}
682
683/// Result for [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache).
684///
685/// A failed fetch is reported in-band (`status = "failed"` + `message`) so the
686/// caller can show it without treating it as a transport error.
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
688#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
689pub struct FetchAndCacheResult {
690    /// `"cached"`, `"already_cached"`, or `"failed"`.
691    pub status: String,
692    /// The fetched module size in bytes (on success).
693    #[serde(skip_serializing_if = "Option::is_none", default)]
694    pub size_bytes: Option<u64>,
695    /// The served generation root (64-hex, on success).
696    #[serde(skip_serializing_if = "Option::is_none", default)]
697    pub served_root: Option<HexId>,
698    /// The failure message (on `status = "failed"`).
699    #[serde(skip_serializing_if = "Option::is_none", default)]
700    pub message: Option<String>,
701}
702
703// ===========================================================================
704// control.peerStatus  (CONTROL — loopback / in-process only)
705// ===========================================================================
706
707/// Result for [`control.peerStatus`](crate::method::Method::ControlPeerStatus) —
708/// a snapshot of the node's L7 peer network. Always safe to call; reports
709/// `running: false` on the FFI path.
710#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
711#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
712pub struct PeerStatusSnapshot {
713    /// Whether a peer network is currently active.
714    pub running: bool,
715    /// This node's `peer_id` (64-hex), if a peer network is running.
716    #[serde(skip_serializing_if = "Option::is_none", default)]
717    pub peer_id: Option<HexId>,
718    /// The DIG network id.
719    pub network_id: String,
720    /// The relay reservation posture.
721    pub relay: RelayStatus,
722    /// The number of currently connected peers.
723    pub connected_peers: u64,
724    /// The last peer-network error, if any.
725    #[serde(skip_serializing_if = "Option::is_none", default)]
726    pub last_error: Option<String>,
727}
728
729// ===========================================================================
730// cache.stats  (CONTROL — loopback / in-process only)
731// ===========================================================================
732
733/// The decoded-content cache hit/miss counters carried in
734/// [`CacheStats`](CacheStats::content_cache).
735#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
736#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
737pub struct ContentCacheCounters {
738    /// Session decoded-content cache hits.
739    pub hits: u64,
740    /// Session decoded-content cache misses.
741    pub misses: u64,
742}
743
744/// Result for [`cache.stats`](crate::method::Method::CacheStats) — cache
745/// telemetry beside [`cache.getConfig`](crate::method::Method::CacheGetConfig):
746/// the reserved cap + live usage, the cached-capsule count + total on-disk
747/// bytes, and the session eviction + content-cache counters.
748#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
749#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
750pub struct CacheStats {
751    /// The on-disk cache size cap in bytes.
752    pub cap_bytes: u64,
753    /// The bytes currently used on disk.
754    pub used_bytes: u64,
755    /// The number of durable cached capsules.
756    pub entry_count: u64,
757    /// The total on-disk bytes across the cached capsules.
758    pub total_bytes: u64,
759    /// Capsules evicted this session.
760    pub evicted_count: u64,
761    /// Bytes evicted this session.
762    pub evicted_bytes: u64,
763    /// The decoded-content cache hit/miss counters.
764    pub content_cache: ContentCacheCounters,
765}
766
767// ===========================================================================
768// control.subscribe / control.unsubscribe / control.listSubscriptions
769// (CONTROL — loopback / in-process only)
770// ===========================================================================
771
772/// Params for [`control.subscribe`](crate::method::Method::ControlSubscribe) and
773/// [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
774#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
775#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
776pub struct SubscribeParams {
777    /// The store launcher id to (un)subscribe (64-hex).
778    pub store_id: HexId,
779}
780
781/// Result for [`control.subscribe`](crate::method::Method::ControlSubscribe).
782#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
783#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
784pub struct SubscribeResult {
785    /// Always `true` — the store is subscribed after this call.
786    pub subscribed: bool,
787    /// Whether this call ADDED the subscription (`false` ⇒ already subscribed).
788    pub added: bool,
789    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
790    pub store_id: HexId,
791}
792
793/// Result for [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
794#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
795#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
796pub struct UnsubscribeResult {
797    /// Always `false` — the store is not subscribed after this call.
798    pub subscribed: bool,
799    /// Whether this call REMOVED a subscription (`false` ⇒ was not subscribed).
800    pub removed: bool,
801    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
802    pub store_id: HexId,
803}
804
805/// Result for
806/// [`control.listSubscriptions`](crate::method::Method::ControlListSubscriptions).
807#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
808#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
809pub struct SubscriptionsList {
810    /// The persisted subscribed store ids (64-hex each).
811    pub subscriptions: Vec<HexId>,
812    /// The subscription count (`subscriptions.len()`).
813    pub count: u64,
814}
815
816// ===========================================================================
817// control.peers.connect / control.peers.disconnect
818// (CONTROL — loopback / in-process only)
819// ===========================================================================
820
821/// Params for [`control.peers.connect`](crate::method::Method::ControlPeersConnect)
822/// and [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
823#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
824#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
825pub struct PeerConnectParams {
826    /// The peer to dial/drop — a dialable address, or a known peer's `peer_id`
827    /// (64-hex) to resolve an already-connected peer.
828    pub peer: String,
829}
830
831/// Result for
832/// [`control.peers.connect`](crate::method::Method::ControlPeersConnect).
833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
834#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
835pub struct PeerConnectResult {
836    /// Always `true` on success — the peer is a counted, connected pool member.
837    pub connected: bool,
838    /// The connected peer's stable `peer_id` (64-hex).
839    pub peer_id: HexId,
840}
841
842/// Result for
843/// [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
844///
845/// Idempotent: disconnecting a peer that is not connected succeeds as a no-op.
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
848pub struct PeerDisconnectResult {
849    /// Always `true` — the peer is not in the pool after this call.
850    pub disconnected: bool,
851    /// The dropped peer's `peer_id` (trimmed + lower-cased, 64-hex).
852    pub peer_id: HexId,
853}
854
855// ===========================================================================
856// dig.health / dig.methods / rpc.discover  (discovery)
857// ===========================================================================
858
859/// Result for [`dig.health`](crate::method::Method::Health) — liveness + a
860/// capability summary.
861#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
862#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
863pub struct Health {
864    /// Liveness — `"ok"` when the node can serve.
865    pub status: String,
866    /// The node's software version.
867    #[serde(skip_serializing_if = "Option::is_none", default)]
868    pub version: Option<String>,
869    /// The DIG network id the node serves.
870    #[serde(skip_serializing_if = "Option::is_none", default)]
871    pub network_id: Option<String>,
872    /// The method names this node implements (its profile).
873    #[serde(default)]
874    pub methods: Vec<String>,
875}
876
877/// Result for [`dig.methods`](crate::method::Method::Methods) — the method names
878/// this node implements (agent self-describe).
879#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
880#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
881pub struct Methods {
882    /// The implemented method names.
883    pub methods: Vec<String>,
884}
885
886#[cfg(test)]
887mod tests {
888    use super::*;
889
890    /// **Proves:** `ContentChunk` round-trips a node-profile window (no
891    /// network-profile fields) without inventing keys.
892    /// **Catches:** a missing `skip_serializing_if` that would leak `null`
893    /// network-profile fields onto the node profile.
894    #[test]
895    fn content_chunk_node_profile_is_lean() {
896        let c = ContentChunk {
897            ciphertext: "AAA=".into(),
898            root: "ab".repeat(32),
899            complete: false,
900            next_offset: Some(3_145_728),
901            inclusion_proof: Some("cHJvb2Y=".into()),
902            chunk_lens: Some(vec![10, 20]),
903            source: Some("local".into()),
904            total_length: None,
905            length: None,
906            offset: None,
907            program_hash: None,
908        };
909        let v = serde_json::to_value(&c).unwrap();
910        assert_eq!(v["source"], "local");
911        assert!(
912            v.get("total_length").is_none(),
913            "node profile must omit total_length"
914        );
915        assert!(v.get("program_hash").is_none());
916        assert_eq!(serde_json::from_value::<ContentChunk>(v).unwrap(), c);
917    }
918
919    /// **Proves:** the network-profile fields serialize when present.
920    #[test]
921    fn content_chunk_network_profile_carries_extras() {
922        let c = ContentChunk {
923            ciphertext: "AAA=".into(),
924            root: "cd".repeat(32),
925            complete: true,
926            next_offset: None,
927            inclusion_proof: None,
928            chunk_lens: None,
929            source: None,
930            total_length: Some(100),
931            length: Some(100),
932            offset: Some(0),
933            program_hash: Some("ef".repeat(32)),
934        };
935        let v = serde_json::to_value(&c).unwrap();
936        assert_eq!(v["total_length"], 100);
937        assert_eq!(v["length"], 100);
938        assert!(v.get("source").is_none());
939    }
940
941    /// **Proves:** the untagged `Inventory` picks `ForStore` vs `AllStores` by
942    /// shape.
943    /// **Catches:** a lost `#[serde(untagged)]` that would tag the variant.
944    #[test]
945    fn inventory_untagged_by_shape() {
946        let for_store = Inventory::ForStore {
947            store_id: "ab".repeat(32),
948            roots: vec!["cd".repeat(32)],
949        };
950        let s = serde_json::to_string(&for_store).unwrap();
951        assert!(s.contains("\"roots\""));
952        assert!(!s.contains("ForStore"));
953        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), for_store);
954
955        let all = Inventory::AllStores {
956            stores: vec!["ef".repeat(32)],
957        };
958        let s = serde_json::to_string(&all).unwrap();
959        assert!(s.contains("\"stores\""));
960        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), all);
961    }
962
963    /// **Proves:** `RedirectInfo` serializes the full redirect payload the
964    /// `-32008` envelope carries.
965    #[test]
966    fn redirect_info_shape() {
967        let r = RedirectInfo {
968            content: ContentRef {
969                store_id: "ab".repeat(32),
970                root: Some("cd".repeat(32)),
971                retrieval_key: Some("ef".repeat(32)),
972            },
973            providers: vec![Provider {
974                peer_id: "12".repeat(32),
975                addresses: vec![PeerAddress {
976                    host: "::1".into(),
977                    port: 9444,
978                    kind: "direct".into(),
979                }],
980            }],
981            redirect_depth: 1,
982            max_redirects: 4,
983        };
984        let v = serde_json::to_value(&r).unwrap();
985        assert_eq!(v["redirect_depth"], 1);
986        assert_eq!(v["max_redirects"], 4);
987        assert_eq!(v["providers"][0]["addresses"][0]["host"], "::1");
988        assert_eq!(serde_json::from_value::<RedirectInfo>(v).unwrap(), r);
989    }
990
991    /// **Proves:** `cache.stats` models the live dig-node result field-for-field
992    /// (the nested `content_cache{hits,misses}` object included).
993    /// **Catches:** a drift from the node's `cache.stats` wire shape (#1075).
994    #[test]
995    fn cache_stats_wire_shape() {
996        let s = CacheStats {
997            cap_bytes: 1 << 30,
998            used_bytes: 2048,
999            entry_count: 3,
1000            total_bytes: 2048,
1001            evicted_count: 1,
1002            evicted_bytes: 512,
1003            content_cache: ContentCacheCounters { hits: 7, misses: 2 },
1004        };
1005        let v = serde_json::to_value(s).unwrap();
1006        assert_eq!(v["cap_bytes"], 1 << 30);
1007        assert_eq!(v["entry_count"], 3);
1008        assert_eq!(v["content_cache"]["hits"], 7);
1009        assert_eq!(v["content_cache"]["misses"], 2);
1010        assert_eq!(serde_json::from_value::<CacheStats>(v).unwrap(), s);
1011    }
1012
1013    /// **Proves:** the subscription-management results carry the exact
1014    /// `{subscribed, added|removed, store_id}` / `{subscriptions, count}` shapes
1015    /// the live node returns.
1016    #[test]
1017    fn subscription_result_shapes() {
1018        let sub = SubscribeResult {
1019            subscribed: true,
1020            added: true,
1021            store_id: "ab".repeat(32),
1022        };
1023        let v = serde_json::to_value(&sub).unwrap();
1024        assert_eq!(v["subscribed"], true);
1025        assert_eq!(v["added"], true);
1026        assert_eq!(serde_json::from_value::<SubscribeResult>(v).unwrap(), sub);
1027
1028        let unsub = UnsubscribeResult {
1029            subscribed: false,
1030            removed: true,
1031            store_id: "cd".repeat(32),
1032        };
1033        let v = serde_json::to_value(&unsub).unwrap();
1034        assert_eq!(v["subscribed"], false);
1035        assert_eq!(v["removed"], true);
1036        assert_eq!(
1037            serde_json::from_value::<UnsubscribeResult>(v).unwrap(),
1038            unsub
1039        );
1040
1041        let list = SubscriptionsList {
1042            subscriptions: vec!["ef".repeat(32)],
1043            count: 1,
1044        };
1045        let v = serde_json::to_value(&list).unwrap();
1046        assert_eq!(v["count"], 1);
1047        assert_eq!(
1048            serde_json::from_value::<SubscriptionsList>(v).unwrap(),
1049            list
1050        );
1051    }
1052
1053    /// **Proves:** the peer connect/disconnect params + results round-trip and
1054    /// match the node's `{connected|disconnected, peer_id}` shapes.
1055    #[test]
1056    fn peer_connect_disconnect_shapes() {
1057        let p = PeerConnectParams {
1058            peer: "12".repeat(32),
1059        };
1060        let v = serde_json::to_value(&p).unwrap();
1061        assert_eq!(serde_json::from_value::<PeerConnectParams>(v).unwrap(), p);
1062
1063        let c = PeerConnectResult {
1064            connected: true,
1065            peer_id: "12".repeat(32),
1066        };
1067        let v = serde_json::to_value(&c).unwrap();
1068        assert_eq!(v["connected"], true);
1069        assert_eq!(serde_json::from_value::<PeerConnectResult>(v).unwrap(), c);
1070
1071        let d = PeerDisconnectResult {
1072            disconnected: true,
1073            peer_id: "34".repeat(32),
1074        };
1075        let v = serde_json::to_value(&d).unwrap();
1076        assert_eq!(v["disconnected"], true);
1077        assert_eq!(
1078            serde_json::from_value::<PeerDisconnectResult>(v).unwrap(),
1079            d
1080        );
1081    }
1082
1083    /// **Proves:** `cache.getConfig` uses the canonical `cache_dir` field name.
1084    /// **Catches:** a regression to the shell's historical `dir` name.
1085    #[test]
1086    fn cache_config_field_name_is_cache_dir() {
1087        let c = CacheConfig {
1088            cap_bytes: 1 << 30,
1089            used_bytes: 0,
1090            cache_dir: "/var/cache/dig".into(),
1091            shared: true,
1092        };
1093        let v = serde_json::to_value(&c).unwrap();
1094        assert!(v.get("cache_dir").is_some());
1095        assert!(v.get("dir").is_none(), "must not use the legacy `dir` name");
1096    }
1097}