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:443`).
327    pub url: String,
328    /// Whether a relay reservation is currently held.
329    pub reserved: bool,
330}
331
332/// Result for [`dig.getNetworkInfo`](crate::method::Method::GetNetworkInfo) —
333/// this node's own peer-network posture.
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
335#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
336pub struct NetworkInfo {
337    /// This node's stable `peer_id` = `SHA-256(TLS SPKI DER)` (64-hex), or
338    /// `null` when no identity is configured.
339    #[serde(skip_serializing_if = "Option::is_none", default)]
340    pub peer_id: Option<HexId>,
341    /// The DIG network id (e.g. `DIG_MAINNET`).
342    pub network_id: String,
343    /// The first advertised (dialable) candidate address, `host:port`.
344    pub listen_addr: String,
345    /// The STUN-discovered reflexive address, if known.
346    #[serde(skip_serializing_if = "Option::is_none", default)]
347    pub reflexive_addr: Option<String>,
348    /// All advertised candidate addresses (IPv6-first).
349    pub candidate_addresses: Vec<String>,
350    /// Reachability posture: `"direct"` or `"relayed"`.
351    pub reachability: String,
352    /// The relay reservation posture.
353    pub relay: RelayStatus,
354}
355
356// ===========================================================================
357// dig.getPeers  (PEER)
358// ===========================================================================
359
360/// Result for [`dig.getPeers`](crate::method::Method::GetPeers) — the peers this
361/// node currently knows (peer exchange over RPC).
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
363#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
364pub struct PeersList {
365    /// The known peers (peer_id + candidate addresses).
366    pub peers: Vec<Provider>,
367}
368
369// ===========================================================================
370// dig.announce  (PEER)
371// ===========================================================================
372
373/// Params for [`dig.announce`](crate::method::Method::Announce).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
376pub struct AnnounceParams {
377    /// The announcing peer's `peer_id` (64-hex).
378    pub peer_id: HexId,
379    /// The announcing peer's candidate addresses.
380    pub addresses: Vec<PeerAddress>,
381}
382
383/// Result for [`dig.announce`](crate::method::Method::Announce).
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
385#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
386pub struct AnnounceAck {
387    /// Whether the announcement was accepted.
388    pub accepted: bool,
389    /// How many peers this node now knows.
390    pub known_peers: u64,
391}
392
393// ===========================================================================
394// dig.getAvailability  (PEER)
395// ===========================================================================
396
397/// One availability query item. Granularity is inferred from which fields are
398/// present: `store_id` only ⇒ which roots are held; `+root` ⇒ a capsule; `+root
399/// +retrieval_key` ⇒ a resource.
400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
401#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
402pub struct AvailabilityQuery {
403    /// The store launcher id (64-hex, required).
404    pub store_id: HexId,
405    /// The generation root (64-hex), for capsule/resource granularity.
406    #[serde(skip_serializing_if = "Option::is_none", default)]
407    pub root: Option<HexId>,
408    /// The resource retrieval key (64-hex), for resource granularity.
409    #[serde(skip_serializing_if = "Option::is_none", default)]
410    pub retrieval_key: Option<HexId>,
411}
412
413/// Params for [`dig.getAvailability`](crate::method::Method::GetAvailability).
414///
415/// # Construction
416///
417/// Like [`FetchRangeParams`], this type is `#[non_exhaustive]`: build it with
418/// [`new`](Self::new) plus the `with_*` setters rather than a struct literal, so a
419/// future additive field is a PATCH for every consumer instead of a semver cascade.
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
421#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
422#[non_exhaustive]
423pub struct GetAvailabilityParams {
424    /// The items to check. Capped at 512 per batch (past-cap items are dropped).
425    pub items: Vec<AvailabilityQuery>,
426    /// The hop budget already consumed by this ask. Absent means zero — read it
427    /// through [`hops_consumed`](Self::hops_consumed), never directly.
428    ///
429    /// # What it means for an availability ask
430    ///
431    /// An availability answer is not only *this* node's holdings: on a miss it may
432    /// name the holders it located, in
433    /// [`AvailabilityAnswer::providers`](AvailabilityAnswer::providers) — the same
434    /// enrichment a [`RedirectInfo`] carries. A responder that cannot answer from
435    /// what it holds MAY ask its own peers, so one caller's question can walk
436    /// several hops, and each hop is a node spending someone else's bandwidth.
437    /// This field is what bounds that walk.
438    ///
439    /// It is the SAME budget, counted the SAME way, as
440    /// [`RedirectInfo::redirect_depth`] and as the `redirect_depth` that
441    /// [`GetContentParams`] and [`FetchRangeParams`] already echo: the number of
442    /// hops ALREADY CONSUMED when this ask arrives, counting UP from zero — never a
443    /// remaining allowance counting down. A responder that asks onward sends
444    /// `hops_consumed() + 1` (saturating at the type maximum), and MUST NOT ask
445    /// onward when that would reach the budget it advertises as
446    /// [`RedirectInfo::max_redirects`].
447    ///
448    /// Absent reads as a fresh, unhopped ask, so a client written before this field
449    /// existed is served unchanged.
450    #[serde(skip_serializing_if = "Option::is_none", default)]
451    pub redirect_depth: Option<u64>,
452    /// The wall-clock TIME this ask may still spend, in milliseconds. Absent means
453    /// unbudgeted — read it through [`budget_ms`](Self::budget_ms), never directly.
454    ///
455    /// # Why this is its OWN field and not the hop budget
456    ///
457    /// [`redirect_depth`](Self::redirect_depth) counts hops UP from zero toward a
458    /// ceiling; this counts milliseconds DOWN toward zero. The two move in opposite
459    /// directions along different axes, so one integer cannot carry both, and folding
460    /// them together would make "one more hop" and "more time" the same request.
461    ///
462    /// # The contract a relaying responder MUST honour
463    ///
464    /// A responder that asks its own peers onward MUST pass a value it has decremented
465    /// by the time it has itself already spent, and it MUST NOT grant a child less time
466    /// than the work it asks that child to do. Concretely: a parent that asks `n`
467    /// children SEQUENTIALLY must divide the remaining budget between them, and a
468    /// parent with less time left than one round trip needs MUST answer
469    /// [`ContentMissInconclusive`](crate::error::ErrorCode::ContentMissInconclusive)
470    /// rather than ask onward and then time out.
471    ///
472    /// This exists because the alternative is measurable: a FIXED per-ask bound with
473    /// sequential asks and a fan-out greater than one guarantees the second hop times
474    /// out, and a responder that reads that timeout as a miss reports a CONFIDENT
475    /// not-found for content it never looked for.
476    ///
477    /// Absent reads as unbudgeted, so a client written before this field existed is
478    /// served exactly as it was.
479    #[serde(skip_serializing_if = "Option::is_none", default)]
480    pub budget_ms: Option<u64>,
481    /// An opaque identity for this ask, for cross-path dedup. Absent means the caller
482    /// opted out of dedup — read it through [`ask_id`](Self::ask_id).
483    ///
484    /// # What it is for
485    ///
486    /// A recursive ask walks a graph, not a tree. Two disjoint paths can arrive at the
487    /// same responder, and without a shared identity that responder cannot tell a
488    /// re-walk from a fresh question — so a diamond in the peer graph does not
489    /// terminate. A responder that has already seen an `ask_id` MUST answer from what
490    /// it already knows instead of asking onward again.
491    ///
492    /// # What it is NOT
493    ///
494    /// It is **not** the JSON-RPC `id`. That field correlates one request with one
495    /// response on one connection; it is chosen per-connection, is commonly a small
496    /// constant, and says nothing about whether two arrivals are the same ask. An
497    /// implementation that reused the JSON-RPC `id` for dedup would either collide
498    /// every unrelated ask together or dedup nothing at all.
499    ///
500    /// # Requirements
501    ///
502    /// 32 lowercase hex characters: **16 unpredictable random bytes**, freshly drawn
503    /// by the ORIGINATOR and copied verbatim by every relaying hop. It MUST be
504    /// unpredictable, because a value an attacker can guess lets that attacker
505    /// pre-poison a responder dedup memo and suppress an ask that has not happened
506    /// yet. A responder MUST NOT derive anything from its value beyond EQUALITY — it
507    /// carries no structure, no origin, no timestamp and no ordering.
508    #[serde(skip_serializing_if = "Option::is_none", default)]
509    pub ask_id: Option<String>,
510}
511
512impl GetAvailabilityParams {
513    /// An availability batch for `items`, asked at hop zero.
514    pub fn new(items: Vec<AvailabilityQuery>) -> Self {
515        GetAvailabilityParams {
516            items,
517            redirect_depth: None,
518            budget_ms: None,
519            ask_id: None,
520        }
521    }
522
523    /// Echo the hop budget already consumed — from a `-32008` redirect, or from the
524    /// ask this one is being made on behalf of. See
525    /// [`redirect_depth`](Self::redirect_depth).
526    pub fn with_redirect_depth(mut self, redirect_depth: u64) -> Self {
527        self.redirect_depth = Some(redirect_depth);
528        self
529    }
530
531    /// The hops already consumed by this ask.
532    ///
533    /// The single home for the "absent means zero" rule. A responder that reached for
534    /// `redirect_depth.is_some()` instead would read every pre-0.8 client's ask as
535    /// budget-free and forward it without bound — the amplification the budget exists
536    /// to stop.
537    pub fn hops_consumed(&self) -> u64 {
538        self.redirect_depth.unwrap_or(0)
539    }
540
541    /// Set the remaining time budget for this ask. See [`budget_ms`](Self::budget_ms).
542    pub fn with_budget_ms(mut self, budget_ms: u64) -> Self {
543        self.budget_ms = Some(budget_ms);
544        self
545    }
546
547    /// The time this ask may still spend, or `None` when the caller sent no budget.
548    ///
549    /// Deliberately NOT collapsed to a number, unlike
550    /// [`hops_consumed`](Self::hops_consumed): there is no safe scalar default. Zero
551    /// would refuse every older caller ask outright, and any positive default would
552    /// silently impose one node idea of patience on another node question. A responder
553    /// that receives `None` applies its OWN policy and passes on what it granted.
554    pub fn budget_ms(&self) -> Option<u64> {
555        self.budget_ms
556    }
557
558    /// Set the cross-path dedup identity. See [`ask_id`](Self::ask_id).
559    pub fn with_ask_id(mut self, ask_id: impl Into<String>) -> Self {
560        self.ask_id = Some(ask_id.into());
561        self
562    }
563
564    /// The dedup identity, or `None` when the caller opted out of dedup.
565    pub fn ask_id(&self) -> Option<&str> {
566        self.ask_id.as_deref()
567    }
568}
569
570/// One availability answer. Only the fields relevant to the query's granularity
571/// are populated.
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
573#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
574pub struct AvailabilityAnswer {
575    /// Whether this node holds the queried item.
576    pub available: bool,
577    /// The roots held (store-granularity queries only).
578    #[serde(skip_serializing_if = "Option::is_none", default)]
579    pub roots: Option<Vec<HexId>>,
580    /// The full resource ciphertext length (resource-granularity only).
581    #[serde(skip_serializing_if = "Option::is_none", default)]
582    pub total_length: Option<u64>,
583    /// The chunk count (resource-granularity only).
584    #[serde(skip_serializing_if = "Option::is_none", default)]
585    pub chunk_count: Option<u64>,
586    /// Whether the whole item is held (root/resource-granularity only).
587    #[serde(skip_serializing_if = "Option::is_none", default)]
588    pub complete: Option<bool>,
589    /// Providers that hold the item — present on a miss when holders were
590    /// located (enriched answer).
591    #[serde(skip_serializing_if = "Option::is_none", default)]
592    pub providers: Option<Vec<Provider>>,
593    /// Whether this responder actually ESTABLISHED that nobody holds the item.
594    ///
595    /// Only meaningful beside `available: false`; on a hit the item is held and there
596    /// is nothing to establish.
597    ///
598    /// # Absent is a THIRD state, not `false`
599    ///
600    /// - `Some(true)` — the responder looked, reached everything it meant to reach,
601    ///   and asserts absence. A client MAY stop searching.
602    /// - `Some(false)` — the responder looked and could NOT establish absence: a hop
603    ///   timed out, was unreachable, or refused uninformatively. A client MUST keep
604    ///   looking. This is the in-band form of
605    ///   [`ContentMissInconclusive`](crate::error::ErrorCode::ContentMissInconclusive),
606    ///   for a batch where only SOME items were inconclusive and the call itself
607    ///   therefore succeeded.
608    /// - `None` — the responder predates this field and makes NO claim either way.
609    ///   It is NOT `Some(false)`: `Some(false)` is a responder telling you its search
610    ///   was incomplete, while `None` is a responder that cannot describe its search at
611    ///   all. Conflating them lets an older server every miss be read as a positive
612    ///   report of incompleteness; conflating it the other way (`unwrap_or(true)`)
613    ///   turns an unknown into an assertion of absence. Read it through
614    ///   [`absence_established_or_unknown`](AvailabilityAnswer::absence_established_or_unknown),
615    ///   which keeps the three states distinct.
616    #[serde(skip_serializing_if = "Option::is_none", default)]
617    pub absence_established: Option<bool>,
618}
619
620impl AvailabilityAnswer {
621    /// Whether absence was established, as a THREE-state answer: `Some(true)`
622    /// asserted, `Some(false)` explicitly not established, `None` unknown because the
623    /// responder predates the field.
624    ///
625    /// A pass-through, and that is the point — it is the named home for the rule that
626    /// there is no safe collapse to `bool`. A client that wants to stop searching MUST
627    /// require `Some(true)`.
628    pub fn absence_established_or_unknown(&self) -> Option<bool> {
629        self.absence_established
630    }
631}
632
633/// Result for [`dig.getAvailability`](crate::method::Method::GetAvailability) —
634/// one answer per query item, in order.
635#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
636#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
637pub struct AvailabilityBatch {
638    /// The per-item answers (index-aligned to the query items served).
639    pub items: Vec<AvailabilityAnswer>,
640}
641
642// ===========================================================================
643// dig.listInventory  (PEER)
644// ===========================================================================
645
646/// Params for [`dig.listInventory`](crate::method::Method::ListInventory).
647#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
648#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
649pub struct ListInventoryParams {
650    /// The store to list roots for (64-hex). Absent ⇒ list all stores served.
651    #[serde(skip_serializing_if = "Option::is_none", default)]
652    pub store_id: Option<HexId>,
653    /// The maximum number of entries to return.
654    #[serde(skip_serializing_if = "Option::is_none", default)]
655    pub limit: Option<u64>,
656}
657
658/// Result for [`dig.listInventory`](crate::method::Method::ListInventory).
659///
660/// With a `store_id` the node returns the roots it holds for that store; without
661/// one it returns the stores it serves. `#[serde(untagged)]` keeps the wire flat
662/// (`{"roots": …}` or `{"stores": …}`).
663#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
664#[serde(untagged)]
665#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
666pub enum Inventory {
667    /// The roots held for a specific store.
668    ForStore {
669        /// The store launcher id (echoed, 64-hex).
670        store_id: HexId,
671        /// The roots this node holds for the store.
672        roots: Vec<HexId>,
673    },
674    /// The stores this node serves (no `store_id` given).
675    AllStores {
676        /// The store launcher ids served.
677        stores: Vec<HexId>,
678    },
679}
680
681// ===========================================================================
682// dig.fetchRange  (PEER)
683// ===========================================================================
684
685/// Params for [`dig.fetchRange`](crate::method::Method::FetchRange) — a single
686/// range frame of a resource this node holds.
687///
688/// # Construction
689///
690/// Like [`RangeFrame`], this type is `#[non_exhaustive]`: build it with
691/// [`resource`](Self::resource) plus the `with_*` setters rather than a struct
692/// literal, so a future additive field is a PATCH for every consumer instead of a
693/// semver cascade.
694///
695/// # Cross-repo contract
696///
697/// [`skip_layout`](Self::skip_layout) is byte-identical to
698/// `dig_nat::mux::RangeRequest::skip_layout`, pinned in
699/// `tests/nat_wire_mirror.rs`. The two enclosing types deliberately differ in every
700/// other respect — dig-nat's `RangeRequest` is a length-prefixed stream preamble,
701/// this is a JSON-RPC params object with a `redirect_depth` dig-nat has no notion
702/// of — so the byte-identical contract here is the FIELD, not the object.
703#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
704#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
705#[non_exhaustive]
706pub struct FetchRangeParams {
707    /// The store launcher id (64-hex, required).
708    pub store_id: HexId,
709    /// The generation root (64-hex, required for a resource fetch).
710    pub root: HexId,
711    /// `SHA-256(urn)` (64-hex, required for a resource fetch).
712    pub retrieval_key: HexId,
713    /// The range start (default 0).
714    #[serde(skip_serializing_if = "Option::is_none", default)]
715    pub offset: Option<u64>,
716    /// The range length in bytes (> 0; clamped to the window cap).
717    pub length: u64,
718    /// Whole-capsule mode (default false). Capsule range fetch is not yet
719    /// served; a `true` here yields `-32004`.
720    #[serde(skip_serializing_if = "Option::is_none", default)]
721    pub capsule: Option<bool>,
722    /// The redirect budget already consumed (echoed from a `-32008` redirect).
723    #[serde(skip_serializing_if = "Option::is_none", default)]
724    pub redirect_depth: Option<u64>,
725    /// Suppress the resource-scaling layout metadata (`chunk_lens` +
726    /// `inclusion_proof`) on this stream's frames, because the client already holds
727    /// the commitment for this `root`.
728    ///
729    /// A client that has already read the layout once — a resumed download, a second
730    /// range of the same resource, a parallel fetch from another holder — does not
731    /// need it again, and re-sending it costs a whole paged prologue PER STREAM: a
732    /// 1,048,576-chunk layout is roughly 7.3 MB, which a 64-way parallel plan would
733    /// otherwise pay 64 times over. Suppressing it is the difference between a
734    /// bounded and an unbounded cost on the read path.
735    ///
736    /// Absent or `false` preserves the pre-0.6.0 behaviour, so an older holder that
737    /// ignores this field is never broken by it — it simply sends metadata the client
738    /// discards. Read the rule through
739    /// [`suppresses_layout`](Self::suppresses_layout) rather than re-deriving it.
740    ///
741    /// The fixed-size identity fields ([`root`](RangeFrame::root),
742    /// [`total_length`](RangeFrame::total_length),
743    /// [`chunk_count`](RangeFrame::chunk_count),
744    /// [`chunk_index`](RangeFrame::chunk_index)) are NOT suppressed: they are what
745    /// detects a wrong-generation holder on arrival, and a client that stopped
746    /// receiving them would lose that check on exactly the streams it fetches most.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub skip_layout: Option<bool>,
749}
750
751impl FetchRangeParams {
752    /// A range request for one content resource: `length` bytes of
753    /// `retrieval_key`'s ciphertext at the generation `root`.
754    pub fn resource(
755        store_id: impl Into<HexId>,
756        root: impl Into<HexId>,
757        retrieval_key: impl Into<HexId>,
758        length: u64,
759    ) -> Self {
760        FetchRangeParams {
761            store_id: store_id.into(),
762            root: root.into(),
763            retrieval_key: retrieval_key.into(),
764            offset: None,
765            length,
766            capsule: None,
767            redirect_depth: None,
768            skip_layout: None,
769        }
770    }
771
772    /// Start the range at `offset` rather than at 0.
773    pub fn with_offset(mut self, offset: u64) -> Self {
774        self.offset = Some(offset);
775        self
776    }
777
778    /// Request whole-capsule mode. Capsule range fetch is not yet served — a `true`
779    /// here yields
780    /// [`ResourceUnavailable`](crate::error::ErrorCode::ResourceUnavailable).
781    pub fn with_capsule(mut self, capsule: bool) -> Self {
782        self.capsule = Some(capsule);
783        self
784    }
785
786    /// Echo the redirect budget already consumed, from a `-32008` redirect.
787    pub fn with_redirect_depth(mut self, redirect_depth: u64) -> Self {
788        self.redirect_depth = Some(redirect_depth);
789        self
790    }
791
792    /// Ask the holder to omit the resource-scaling layout metadata, because this
793    /// client already holds the commitment for this `root`. See
794    /// [`skip_layout`](Self::skip_layout).
795    pub fn with_skip_layout(mut self, skip_layout: bool) -> Self {
796        self.skip_layout = Some(skip_layout);
797        self
798    }
799
800    /// Whether this request suppresses the resource-scaling layout metadata.
801    ///
802    /// The single home for the "absent or `false` means SEND the layout" rule. A
803    /// serve path that reached for `skip_layout.is_some()` instead would suppress the
804    /// layout for a client that had explicitly asked for it — unrecoverable for that
805    /// client, since the layout is a decrypt input it cannot obtain any other way on
806    /// that stream.
807    pub fn suppresses_layout(&self) -> bool {
808        self.skip_layout.unwrap_or(false)
809    }
810}
811
812/// One range frame of a resource: a byte window, plus the per-resource
813/// verification metadata that makes the window independently checkable.
814///
815/// The metadata splits in two by whether it scales with the resource, and the
816/// split decides which frames carry it:
817///
818/// - **The identity set — [`root`](Self::root),
819///   [`total_length`](Self::total_length), [`chunk_count`](Self::chunk_count),
820///   plus [`chunk_index`](Self::chunk_index) when the window begins on a chunk
821///   boundary — rides EVERY frame.** It is fixed-size, so carrying it everywhere
822///   costs a bounded number of bytes, and it is what lets a client fetching in
823///   parallel from many holders reject a wrong-generation or wrong-layout source
824///   the moment a frame arrives, rather than after paying for the whole resource
825///   in bandwidth.
826/// - **The resource-scaling set — [`chunk_lens`](Self::chunk_lens) and
827///   [`inclusion_proof`](Self::inclusion_proof) — rides the first frame, or a
828///   paged prologue, once per range stream.** Repeating it per frame would cost
829///   proportionally to the resource against a frame budget with no slack; a layout
830///   too large to state on one frame is paged instead, each page stamped with the
831///   [`chunk_lens_offset`](Self::chunk_lens_offset) it begins at.
832///
833/// The window is exactly the span the caller requested — never widened.
834///
835/// # Construction
836///
837/// This type is [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html):
838/// build it with [`data`](Self::data) and the `with_*` setters rather than a struct
839/// literal. That is deliberate — the wire form grows as the protocol does, and
840/// routing construction through named setters means a future additive field is a
841/// PATCH release for every consumer instead of another semver cascade. It also
842/// makes the two frame shapes different call chains rather than one call with a
843/// pile of `None`s, so a continuation frame cannot accidentally claim a layout it
844/// is not stating.
845///
846/// # Cross-repo contract
847///
848/// The wire form is **byte-identical** to `dig_nat::mux::RangeFrame`, the
849/// streaming implementation of this frame (`SYSTEM.md` → "Canonical DIG-node RPC
850/// interface"). Field names, encodings, and the population rule above are pinned
851/// against dig-nat's actual output in `tests/nat_wire_mirror.rs`; a change to any
852/// of them lands in both crates in the same unit of work or not at all.
853#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
854#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
855#[non_exhaustive]
856pub struct RangeFrame {
857    /// The window start offset (echoed).
858    pub offset: u64,
859    /// This window's byte length.
860    pub length: u64,
861    /// This window's ciphertext, base64.
862    pub bytes: String,
863    /// Whether this frame ends the resource.
864    pub complete: bool,
865    /// The full resource ciphertext length. Part of the fixed-size **identity
866    /// set**, so it rides EVERY frame.
867    #[serde(skip_serializing_if = "Option::is_none", default)]
868    pub total_length: Option<u64>,
869    /// Per-chunk ciphertext lengths of the full resource, in order — the layout a
870    /// reader needs before it can decrypt (per-chunk AEAD needs the WHOLE array,
871    /// and a reader rejects an array whose sum differs from
872    /// [`total_length`](Self::total_length)).
873    ///
874    /// Resource-scaling, so it rides the first frame or a **paged prologue**, once
875    /// per range stream — never repeated on continuation frames. When paged, this
876    /// is one page of the array and
877    /// [`chunk_lens_offset`](Self::chunk_lens_offset) states the entry it begins
878    /// at.
879    #[serde(skip_serializing_if = "Option::is_none", default)]
880    pub chunk_lens: Option<Vec<u64>>,
881    /// This frame's first chunk index — the pre-existing alias of
882    /// [`first_chunk_index`](Self::first_chunk_index), carrying the same value, and
883    /// the name dig-nat emits.
884    ///
885    /// Part of the **identity set**: it rides every frame whose window begins on a
886    /// chunk boundary, and is OMITTED (rather than guessed) on a mid-chunk window.
887    /// Being fixed-size, it is settable on its own — see
888    /// [`with_chunk_index`](Self::with_chunk_index) — precisely so a continuation
889    /// frame can state it without dragging along the once-per-stream
890    /// [`inclusion_proof`](Self::inclusion_proof).
891    #[serde(skip_serializing_if = "Option::is_none", default)]
892    pub chunk_index: Option<u64>,
893    /// Whole-resource merkle proof against [`root`](Self::root), base64, relayed
894    /// verbatim.
895    ///
896    /// Resource-scaling, so it rides the first frame or the paged prologue, once
897    /// per range stream. A holder MUST NOT repeat it per frame: it is bounded at
898    /// 4,096 base64 bytes, which against the frame budget leaves no slack for the
899    /// payload the frame exists to carry.
900    #[serde(skip_serializing_if = "Option::is_none", default)]
901    pub inclusion_proof: Option<String>,
902    /// The chain-anchored root (64-hex) this frame's resource verified against.
903    /// Part of the fixed-size **identity set**, so it rides EVERY frame.
904    ///
905    /// NOT A TRUST ANCHOR BY ITSELF. The client resolves the resource's root from
906    /// the URN (chain-anchored) and PINS it before fetching; a peer-declared value
907    /// never replaces that pinned root. What this field provides is a
908    /// generation-CONSISTENCY check: a frame declaring a root other than the pinned
909    /// one is REJECTED and attributed to the offending peer (NC-9 fail-closed). So
910    /// a declared root can only ever cause rejection — it can never move the pinned
911    /// root, and never makes an unverified frame acceptable.
912    #[serde(skip_serializing_if = "Option::is_none", default)]
913    pub root: Option<HexId>,
914    /// **RESERVED — not currently derivable; a server MUST NOT emit it.**
915    ///
916    /// Per-chunk merkle inclusion proofs for the chunks a frame covers. No such
917    /// proof exists in the current store format: the generation root's merkle
918    /// leaves are per-RESOURCE (a leaf is the SHA-256 of a resource's WHOLE
919    /// ciphertext), so a single chunk has no leaf to prove. A client MUST NOT
920    /// require this field, and per-range verification instead uses the
921    /// whole-resource [`inclusion_proof`](Self::inclusion_proof) together with the
922    /// per-frame [`root`](Self::root)/[`chunk_lens`](Self::chunk_lens) metadata.
923    ///
924    /// Making it derivable requires a per-resource chunk-level commitment in the
925    /// store format first (tracked as `dig_ecosystem#1601`). The field is kept in
926    /// the wire type, unused, so populating it later is additive (§5.1); each entry
927    /// would be an opaque base64 proof blob, since this pure level-00 wire type
928    /// MUST NOT depend on the merkle primitive.
929    #[serde(skip_serializing_if = "Option::is_none", default)]
930    pub range_proof: Option<Vec<String>>,
931    /// The chunk index of the first chunk in this frame (0-based, into the
932    /// resource's chunk sequence described by [`chunk_lens`](Self::chunk_lens)).
933    ///
934    /// Present only when the frame's window begins EXACTLY on a chunk boundary; a
935    /// mid-chunk window omits it rather than assert an index the caller's own
936    /// alignment check would contradict. The served window is exactly the requested
937    /// span — a server MUST NOT widen a range to a chunk boundary — so a frame is
938    /// chunk-aligned only when the caller asked for an aligned span.
939    #[serde(skip_serializing_if = "Option::is_none", default)]
940    pub first_chunk_index: Option<u64>,
941    /// The resource's TOTAL chunk count — how many entries the fully reassembled
942    /// [`chunk_lens`](Self::chunk_lens) array has.
943    ///
944    /// Fixed-size, so it belongs to the **identity set** and rides EVERY frame.
945    /// Together with [`root`](Self::root) and
946    /// [`total_length`](Self::total_length) it is what lets a reader detect a
947    /// wrong-generation or wrong-layout holder on the first frame it receives. It is
948    /// also how a reader sizes the array it is paging in, and therefore how it knows
949    /// a **paged prologue** is complete: the prologue ends when the reader holds
950    /// `chunk_count` entries, which no single page can tell it.
951    #[serde(default, skip_serializing_if = "Option::is_none")]
952    pub chunk_count: Option<u64>,
953    /// The index into the resource's [`chunk_lens`](Self::chunk_lens) array at which
954    /// THIS frame's page begins — how a **paged prologue** is located and
955    /// reassembled.
956    ///
957    /// A resource whose layout exceeds the per-frame entry cap cannot state it on
958    /// one frame, so the sender pages it: successive frames each carry up to that
959    /// many entries, stamped with the offset they start at. A reader places each page
960    /// at its offset and holds the whole array once it has
961    /// [`chunk_count`](Self::chunk_count) entries.
962    ///
963    /// Absent means "this frame's `chunk_lens`, if any, begins at entry 0" — the
964    /// single-frame layout, which is the shape every pre-0.6.0 producer emits. So an
965    /// older frame decodes with exactly its original meaning (§5.1).
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub chunk_lens_offset: Option<u64>,
968}
969
970impl RangeFrame {
971    /// A **data frame**: `length` bytes of base64 ciphertext at `offset`, carrying
972    /// no metadata — the bare shape every continuation frame starts from.
973    ///
974    /// `length` is stated rather than derived because [`bytes`](Self::bytes) is
975    /// already base64 on this type, and recovering the raw window length from it
976    /// would need a base64 codec this pure level-00 wire crate deliberately does not
977    /// depend on. A serve path passes the length it served.
978    pub fn data(offset: u64, length: u64, bytes: impl Into<String>) -> Self {
979        RangeFrame {
980            offset,
981            length,
982            bytes: bytes.into(),
983            complete: false,
984            total_length: None,
985            chunk_lens: None,
986            chunk_index: None,
987            inclusion_proof: None,
988            root: None,
989            range_proof: None,
990            first_chunk_index: None,
991            chunk_count: None,
992            chunk_lens_offset: None,
993        }
994    }
995
996    /// Mark this as the final frame of the range.
997    pub fn with_complete(mut self, complete: bool) -> Self {
998        self.complete = complete;
999        self
1000    }
1001
1002    /// The fixed-size **identity set** every frame of a range carries: the
1003    /// generation `root` (64-hex) the range is served from, the resource's
1004    /// ciphertext `total_length`, and its `chunk_count`.
1005    ///
1006    /// These three are what let a reader reject a wrong-generation or wrong-layout
1007    /// holder the moment a frame arrives — which the resource-scaling metadata never
1008    /// could, since it arrives once. Call this on every frame.
1009    pub fn with_identity(
1010        mut self,
1011        root: impl Into<HexId>,
1012        total_length: u64,
1013        chunk_count: u64,
1014    ) -> Self {
1015        self.root = Some(root.into());
1016        self.total_length = Some(total_length);
1017        self.chunk_count = Some(chunk_count);
1018        self
1019    }
1020
1021    /// State [`chunk_index`](Self::chunk_index) — the chunk this frame's window
1022    /// begins on — for a chunk-aligned window.
1023    ///
1024    /// Separate from [`with_inclusion_proof`](Self::with_inclusion_proof) on purpose:
1025    /// the index is fixed-size identity metadata that rides every aligned frame,
1026    /// while the proof is once-per-stream, so binding them together would force a
1027    /// producer to either repeat a proof it MUST NOT repeat or bypass this API. Omit
1028    /// the call entirely for a mid-chunk window.
1029    pub fn with_chunk_index(mut self, chunk_index: u64) -> Self {
1030        self.chunk_index = Some(chunk_index);
1031        self
1032    }
1033
1034    /// Additionally state [`first_chunk_index`](Self::first_chunk_index), this
1035    /// crate's v0.4.0 alias of [`chunk_index`](Self::chunk_index).
1036    ///
1037    /// Both names carry the same value. dig-nat emits only `chunk_index`, so
1038    /// [`with_chunk_index`](Self::with_chunk_index) alone is the interoperable
1039    /// choice; a producer serving readers that expect the newer name states both.
1040    pub fn with_first_chunk_index(mut self, first_chunk_index: u64) -> Self {
1041        self.first_chunk_index = Some(first_chunk_index);
1042        self
1043    }
1044
1045    /// One page of the resource's `chunk_lens` array, beginning at entry
1046    /// `chunk_lens_offset`.
1047    ///
1048    /// Call it once with offset `0` for a layout that fits a single frame, or once
1049    /// per page of a **paged prologue**. A page is only ever useful as part of a
1050    /// complete set: `chunk_lens` is a decrypt input, and a reader needs all
1051    /// [`chunk_count`](Self::chunk_count) entries before it can decrypt anything.
1052    pub fn with_chunk_lens_page(mut self, chunk_lens_offset: u64, chunk_lens: Vec<u64>) -> Self {
1053        self.chunk_lens_offset = Some(chunk_lens_offset);
1054        self.chunk_lens = Some(chunk_lens);
1055        self
1056    }
1057
1058    /// The whole-resource merkle inclusion proof against
1059    /// [`root`](Self::root) (base64, relayed verbatim).
1060    ///
1061    /// Resource-scaling: state it on the first frame or the prologue, once per range
1062    /// stream, never per frame.
1063    pub fn with_inclusion_proof(mut self, inclusion_proof: impl Into<String>) -> Self {
1064        self.inclusion_proof = Some(inclusion_proof.into());
1065        self
1066    }
1067
1068    /// State the **RESERVED** [`range_proof`](Self::range_proof) field.
1069    ///
1070    /// A server MUST NOT emit it — no per-chunk proof is derivable from the current
1071    /// store format (see the field's own documentation). The setter exists so the
1072    /// shape stays constructible for the conformance vectors that pin it, and so no
1073    /// field of this `#[non_exhaustive]` type is unreachable; it is not a serve-path
1074    /// call.
1075    pub fn with_range_proof(mut self, range_proof: Vec<String>) -> Self {
1076        self.range_proof = Some(range_proof);
1077        self
1078    }
1079}
1080
1081// ===========================================================================
1082// dig.getModuleInfo / dig.fetchModuleRange  (PEER — whole-module pull, #1576)
1083// ===========================================================================
1084
1085/// Params for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
1086/// handshake a peer reads before range-pulling a whole `.dig` module for
1087/// `(store, root)`.
1088#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1089#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1090pub struct GetModuleInfoParams {
1091    /// The store launcher id (64-hex, required).
1092    pub store_id: HexId,
1093    /// The generation root whose `.dig` module is being pulled (64-hex, required).
1094    pub root: HexId,
1095}
1096
1097/// Result for [`dig.getModuleInfo`](crate::method::Method::GetModuleInfo) — the
1098/// transfer descriptor of a whole `.dig` module.
1099///
1100/// The whole-module blob is content-addressed + immutable (the `.dig` container
1101/// is byte-identical by construction). [`module_hash`](Self::module_hash) is the
1102/// content id of the assembled blob; a puller verifies each pulled range against
1103/// [`chunk_hashes`](Self::chunk_hashes) (per-peer attribution on a multi-source
1104/// pull) and the fully-assembled blob against `module_hash`, THEN verifies the
1105/// assembled module against its chain-anchored root before admitting + resharing
1106/// (NC-9 verified-content-not-safe-content).
1107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1108#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1109pub struct ModuleInfo {
1110    /// The total byte length of the whole `.dig` module blob.
1111    pub total_size: u64,
1112    /// The content id of the fully-assembled module blob (64-hex `SHA-256` of the
1113    /// module bytes). The puller checks the assembled blob against this.
1114    pub module_hash: HexId,
1115    /// Per-chunk content hashes (64-hex each) in ascending chunk order, covering
1116    /// the blob in [`total_size`](Self::total_size)-spanning fixed-size chunks
1117    /// (the trailing chunk may be short). A puller checks each pulled
1118    /// [`RangeFrame`] against the covering entries for per-source attribution on a
1119    /// multi-source pull (a tampered range fails closed before assembly).
1120    pub chunk_hashes: Vec<HexId>,
1121    /// Per-chunk byte lengths (in the same order as [`chunk_hashes`](Self::chunk_hashes)).
1122    /// MUST have the same length as `chunk_hashes` and MUST sum to `total_size`.
1123    /// A puller uses these to map a fetched byte range to the covering chunk hash(es).
1124    pub chunk_lens: Vec<u64>,
1125}
1126
1127/// Params for [`dig.fetchModuleRange`](crate::method::Method::FetchModuleRange) —
1128/// a single range frame of the whole `.dig` module blob for `(store, root)`.
1129///
1130/// The response reuses [`RangeFrame`]: [`bytes`](RangeFrame::bytes) carries the
1131/// window of the module blob (base64), [`total_length`](RangeFrame::total_length)
1132/// echoes the whole-module size on the first frame, and
1133/// [`complete`](RangeFrame::complete) ends the stream.
1134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1135#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1136pub struct FetchModuleRangeParams {
1137    /// The store launcher id (64-hex, required).
1138    pub store_id: HexId,
1139    /// The generation root whose `.dig` module is being pulled (64-hex, required).
1140    pub root: HexId,
1141    /// The range start into the module blob (default 0).
1142    #[serde(skip_serializing_if = "Option::is_none", default)]
1143    pub offset: Option<u64>,
1144    /// The range length in bytes (> 0; clamped to the window cap).
1145    pub length: u64,
1146}
1147
1148// ===========================================================================
1149// dig.stage  (CONTROL — loopback / in-process only)
1150// ===========================================================================
1151
1152/// Params for [`dig.stage`](crate::method::Method::Stage) — compile a local
1153/// folder into a capsule `.dig` module in-process.
1154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1155#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1156pub struct StageParams {
1157    /// The absolute path to the folder to compile.
1158    pub dir: String,
1159    /// The target store launcher id (64-hex). Absent ⇒ an ephemeral,
1160    /// content-derived id (a preview).
1161    #[serde(skip_serializing_if = "Option::is_none", default)]
1162    pub store_id: Option<HexId>,
1163    /// The store salt (64-hex). Present ⇒ a private store.
1164    #[serde(skip_serializing_if = "Option::is_none", default)]
1165    pub salt: Option<HexId>,
1166    /// Optional DIGHub-style manifest metadata to embed.
1167    #[serde(skip_serializing_if = "Option::is_none", default)]
1168    pub metadata: Option<serde_json::Value>,
1169}
1170
1171/// Result for [`dig.stage`](crate::method::Method::Stage) — the compiled capsule.
1172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1173#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1174pub struct StageResult {
1175    /// The canonical capsule identity, `storeId:rootHash`.
1176    pub capsule: String,
1177    /// The store launcher id (64-hex).
1178    pub store_id: HexId,
1179    /// The compiled generation root (64-hex).
1180    pub root: HexId,
1181    /// The filesystem path to the compiled `.dig` module.
1182    pub module_path: String,
1183    /// The module size in bytes.
1184    pub size: u64,
1185    /// The `chia://storeId:rootHash/` content address.
1186    #[serde(skip_serializing_if = "Option::is_none", default)]
1187    pub content_address: Option<String>,
1188    /// The relative paths compiled into the capsule.
1189    #[serde(default)]
1190    pub files: Vec<String>,
1191    /// Whether this is an ephemeral preview (not advancing a real store).
1192    #[serde(skip_serializing_if = "Option::is_none", default)]
1193    pub ephemeral: Option<bool>,
1194}
1195
1196// ===========================================================================
1197// cache.*  (CONTROL — loopback / in-process only)
1198// ===========================================================================
1199
1200/// Result for [`cache.getConfig`](crate::method::Method::CacheGetConfig).
1201///
1202/// The canonical field name for the cache path is `cache_dir` everywhere (the
1203/// shell's historical `dir` is unified onto this name).
1204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1205#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1206pub struct CacheConfig {
1207    /// The on-disk cache size cap in bytes (floored at 64 MiB).
1208    pub cap_bytes: u64,
1209    /// The bytes currently used.
1210    pub used_bytes: u64,
1211    /// The effective resolved cache directory.
1212    pub cache_dir: String,
1213    /// Whether that directory is the canonical shared location (vs a
1214    /// process-private fallback).
1215    pub shared: bool,
1216}
1217
1218/// Params for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
1219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1220#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1221pub struct SetCapBytesParams {
1222    /// The requested cap in bytes (floored at 64 MiB by the node).
1223    pub cap_bytes: u64,
1224}
1225
1226/// Result for [`cache.setCapBytes`](crate::method::Method::CacheSetCapBytes).
1227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1228#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1229pub struct SetCapBytesResult {
1230    /// The effective cap after flooring.
1231    pub cap_bytes: u64,
1232}
1233
1234/// One durable cached-module entry.
1235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1236#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1237pub struct CachedCapsule {
1238    /// The canonical capsule identity, `storeId:rootHash`.
1239    pub capsule: String,
1240    /// The store launcher id (64-hex).
1241    pub store_id: HexId,
1242    /// The generation root (64-hex).
1243    pub root: HexId,
1244    /// The module size in bytes.
1245    pub size_bytes: u64,
1246    /// When the module was last used (unix ms).
1247    pub last_used_unix_ms: u64,
1248}
1249
1250/// Result for [`cache.listCached`](crate::method::Method::CacheListCached).
1251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1252#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1253pub struct CachedList {
1254    /// The cached capsules.
1255    pub cached: Vec<CachedCapsule>,
1256}
1257
1258/// Params for a capsule-keyed cache op
1259/// ([`cache.removeCached`](crate::method::Method::CacheRemoveCached),
1260/// [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache)).
1261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1262#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1263pub struct CapsuleKey {
1264    /// The store launcher id (64-hex).
1265    pub store_id: HexId,
1266    /// The generation root (64-hex).
1267    pub root: HexId,
1268}
1269
1270/// Result for [`cache.removeCached`](crate::method::Method::CacheRemoveCached).
1271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1272#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1273pub struct RemoveCachedResult {
1274    /// Whether an entry was removed.
1275    pub removed: bool,
1276}
1277
1278/// Result for [`cache.fetchAndCache`](crate::method::Method::CacheFetchAndCache).
1279///
1280/// A failed fetch is reported in-band (`status = "failed"` + `message`) so the
1281/// caller can show it without treating it as a transport error.
1282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1283#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1284pub struct FetchAndCacheResult {
1285    /// `"cached"`, `"already_cached"`, or `"failed"`.
1286    pub status: String,
1287    /// The fetched module size in bytes (on success).
1288    #[serde(skip_serializing_if = "Option::is_none", default)]
1289    pub size_bytes: Option<u64>,
1290    /// The served generation root (64-hex, on success).
1291    #[serde(skip_serializing_if = "Option::is_none", default)]
1292    pub served_root: Option<HexId>,
1293    /// The failure message (on `status = "failed"`).
1294    #[serde(skip_serializing_if = "Option::is_none", default)]
1295    pub message: Option<String>,
1296}
1297
1298// ===========================================================================
1299// control.peerStatus  (CONTROL — loopback / in-process only)
1300// ===========================================================================
1301
1302/// Result for [`control.peerStatus`](crate::method::Method::ControlPeerStatus) —
1303/// a snapshot of the node's L7 peer network. Always safe to call; reports
1304/// `running: false` on the FFI path.
1305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1306#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1307pub struct PeerStatusSnapshot {
1308    /// Whether a peer network is currently active.
1309    pub running: bool,
1310    /// This node's `peer_id` (64-hex), if a peer network is running.
1311    #[serde(skip_serializing_if = "Option::is_none", default)]
1312    pub peer_id: Option<HexId>,
1313    /// The DIG network id.
1314    pub network_id: String,
1315    /// The relay reservation posture.
1316    pub relay: RelayStatus,
1317    /// The number of currently connected peers.
1318    pub connected_peers: u64,
1319    /// The last peer-network error, if any.
1320    #[serde(skip_serializing_if = "Option::is_none", default)]
1321    pub last_error: Option<String>,
1322}
1323
1324// ===========================================================================
1325// cache.stats  (CONTROL — loopback / in-process only)
1326// ===========================================================================
1327
1328/// The decoded-content cache hit/miss counters carried in
1329/// [`CacheStats`](CacheStats::content_cache).
1330#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1331#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1332pub struct ContentCacheCounters {
1333    /// Session decoded-content cache hits.
1334    pub hits: u64,
1335    /// Session decoded-content cache misses.
1336    pub misses: u64,
1337}
1338
1339/// Result for [`cache.stats`](crate::method::Method::CacheStats) — cache
1340/// telemetry beside [`cache.getConfig`](crate::method::Method::CacheGetConfig):
1341/// the reserved cap + live usage, the cached-capsule count + total on-disk
1342/// bytes, and the session eviction + content-cache counters.
1343#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1344#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1345pub struct CacheStats {
1346    /// The on-disk cache size cap in bytes.
1347    pub cap_bytes: u64,
1348    /// The bytes currently used on disk.
1349    pub used_bytes: u64,
1350    /// The number of durable cached capsules.
1351    pub entry_count: u64,
1352    /// The total on-disk bytes across the cached capsules.
1353    pub total_bytes: u64,
1354    /// Capsules evicted this session.
1355    pub evicted_count: u64,
1356    /// Bytes evicted this session.
1357    pub evicted_bytes: u64,
1358    /// The decoded-content cache hit/miss counters.
1359    pub content_cache: ContentCacheCounters,
1360}
1361
1362// ===========================================================================
1363// control.subscribe / control.unsubscribe / control.listSubscriptions
1364// (CONTROL — loopback / in-process only)
1365// ===========================================================================
1366
1367/// Params for [`control.subscribe`](crate::method::Method::ControlSubscribe) and
1368/// [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
1369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1370#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1371pub struct SubscribeParams {
1372    /// The store launcher id to (un)subscribe (64-hex).
1373    pub store_id: HexId,
1374}
1375
1376/// Result for [`control.subscribe`](crate::method::Method::ControlSubscribe).
1377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1378#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1379pub struct SubscribeResult {
1380    /// Always `true` — the store is subscribed after this call.
1381    pub subscribed: bool,
1382    /// Whether this call ADDED the subscription (`false` ⇒ already subscribed).
1383    pub added: bool,
1384    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
1385    pub store_id: HexId,
1386}
1387
1388/// Result for [`control.unsubscribe`](crate::method::Method::ControlUnsubscribe).
1389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1390#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1391pub struct UnsubscribeResult {
1392    /// Always `false` — the store is not subscribed after this call.
1393    pub subscribed: bool,
1394    /// Whether this call REMOVED a subscription (`false` ⇒ was not subscribed).
1395    pub removed: bool,
1396    /// The canonical persisted store id (trimmed + lower-cased, 64-hex).
1397    pub store_id: HexId,
1398}
1399
1400/// Result for
1401/// [`control.listSubscriptions`](crate::method::Method::ControlListSubscriptions).
1402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1403#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1404pub struct SubscriptionsList {
1405    /// The persisted subscribed store ids (64-hex each).
1406    pub subscriptions: Vec<HexId>,
1407    /// The subscription count (`subscriptions.len()`).
1408    pub count: u64,
1409}
1410
1411// ===========================================================================
1412// control.peers.connect / control.peers.disconnect
1413// (CONTROL — loopback / in-process only)
1414// ===========================================================================
1415
1416/// Params for [`control.peers.connect`](crate::method::Method::ControlPeersConnect)
1417/// and [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
1418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1419#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1420pub struct PeerConnectParams {
1421    /// The peer to dial/drop — a dialable address, or a known peer's `peer_id`
1422    /// (64-hex) to resolve an already-connected peer.
1423    pub peer: String,
1424}
1425
1426/// Result for
1427/// [`control.peers.connect`](crate::method::Method::ControlPeersConnect).
1428#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1429#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1430pub struct PeerConnectResult {
1431    /// Always `true` on success — the peer is a counted, connected pool member.
1432    pub connected: bool,
1433    /// The connected peer's stable `peer_id` (64-hex).
1434    pub peer_id: HexId,
1435}
1436
1437/// Result for
1438/// [`control.peers.disconnect`](crate::method::Method::ControlPeersDisconnect).
1439///
1440/// Idempotent: disconnecting a peer that is not connected succeeds as a no-op.
1441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1442#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1443pub struct PeerDisconnectResult {
1444    /// Always `true` — the peer is not in the pool after this call.
1445    pub disconnected: bool,
1446    /// The dropped peer's `peer_id` (trimmed + lower-cased, 64-hex).
1447    pub peer_id: HexId,
1448}
1449
1450// ===========================================================================
1451// dig.listRewardDistributors / dig.getRewardProverStatus / dig.getRewardDistributor
1452// (CONTROL — loopback / in-process only; dig-rewards-coin SPEC.md §2.3 / §2.6)
1453// ===========================================================================
1454
1455/// The always-on reward prover loop's state — SPEC §2.3, the closed set.
1456///
1457/// `#[non_exhaustive]`-equivalent by convention rather than attribute (the SPEC
1458/// pins this to an exact nine-member set; a variant needs a SPEC amendment, not
1459/// a semver-additive appendix). Deserialization is fail-closed: no
1460/// `#[serde(other)]` catch-all and no `Default` impl, so an unknown wire string
1461/// (a newer node, a typo) is a hard parse error rather than a silently-coerced
1462/// state.
1463#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1464#[serde(rename_all = "camelCase")]
1465#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1466pub enum ProverState {
1467    /// No distributor assigned; the loop is parked.
1468    Idle,
1469    /// A cycle is in progress.
1470    Running,
1471    /// The local capsule/store copy this cycle needs is missing.
1472    LocalCopyMissing,
1473    /// The chain source (full node / peer) is unreachable this cycle.
1474    ChainSourceUnavailable,
1475    /// The distributor is unfunded — no reserve to pay a cycle out of.
1476    Unfunded,
1477    /// The fee budget for entry-set writes is exhausted for this cycle.
1478    FeeBudgetExhausted,
1479    /// The entry set is at capacity; no further entries can be added.
1480    EntrySetFull,
1481    /// Paused by an operator action.
1482    Paused,
1483    /// Stopped; the loop will not run again without an explicit restart.
1484    Stopped,
1485}
1486
1487/// The reward prover loop's running counters — SPEC §2.3.
1488#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1489#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1490pub struct ProverCounters {
1491    /// Distinct mirrors observed across all cycles.
1492    pub mirrors_seen: u64,
1493    /// Ranged capsule challenges issued.
1494    pub challenges_issued: u64,
1495    /// Challenges that passed verification.
1496    pub challenges_passed: u64,
1497    /// Challenges that failed verification.
1498    pub challenges_failed: u64,
1499    /// Entry-set entries added.
1500    pub entries_added: u64,
1501    /// Entry-set entries removed.
1502    pub entries_removed: u64,
1503    /// The current entry-set size.
1504    pub entry_count: u64,
1505    /// The distributor's reserve, in base units.
1506    pub reserve_base_units: u64,
1507    /// Total paid out over the loop's lifetime, in base units.
1508    pub total_paid_out_base_units: u64,
1509}
1510
1511/// One distributor's prover-loop status — SPEC §2.3 / §2.4.
1512///
1513/// # No health boolean, no pre-computed staleness
1514///
1515/// This type carries no `healthy`/`ok`/`up`/`running`/`stale` field and no
1516/// `seconds_since_last_run`. SPEC §2.4: a wedged loop cannot report its own
1517/// wedging — a boolean the writer sets on every successful cycle reads `true`
1518/// forever after exactly the failure it exists to reveal, because the write
1519/// that would flip it never runs. The reader derives staleness itself from
1520/// [`last_cycle_completed_at`](Self::last_cycle_completed_at) /
1521/// [`next_cycle_due_at`](Self::next_cycle_due_at) against
1522/// [`observed_at`](Self::observed_at) and its own clock. Contrast
1523/// [`GetRewardDistributorResult::entry_set_stale`], which IS a boolean — it is
1524/// permitted there because it is computed from the singleton's on-chain spend
1525/// history by the responder at read time, not self-reported by the writer this
1526/// type describes.
1527#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1528#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1529pub struct RewardProverStatus {
1530    /// The distributor singleton's launcher id (64-hex).
1531    pub launcher_id: HexId,
1532    /// The backing store's launcher id (64-hex).
1533    pub store_id: HexId,
1534    /// The store's current generation root (64-hex).
1535    pub root: HexId,
1536    /// The loop's current state.
1537    pub prover_state: ProverState,
1538    /// Unix seconds the loop entered `prover_state`.
1539    pub prover_state_since: u64,
1540    /// Unix seconds the current/most recent cycle started, if any has run.
1541    pub last_cycle_started_at: Option<u64>,
1542    /// Unix seconds the most recent cycle completed, if any has completed.
1543    pub last_cycle_completed_at: Option<u64>,
1544    /// Unix seconds the next cycle is scheduled, if the loop is scheduling one.
1545    pub next_cycle_due_at: Option<u64>,
1546    /// Unix seconds of the most recent entry-set write, if any.
1547    pub last_entry_write_at: Option<u64>,
1548    /// Consecutive cycle failures (resets to 0 on a completed cycle).
1549    pub consecutive_cycle_failures: u32,
1550    /// Entry writes queued but not yet committed.
1551    pub pending_entry_writes: u32,
1552    /// Unix seconds this status was assembled (the reader's staleness anchor).
1553    pub observed_at: u64,
1554    /// The loop's running counters.
1555    pub counters: ProverCounters,
1556}
1557
1558/// Params for
1559/// [`dig.getRewardProverStatus`](crate::method::Method::GetRewardProverStatus).
1560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1561#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1562pub struct GetRewardProverStatusParams {
1563    /// Restrict to one distributor's launcher id (64-hex). Absent ⇒ every
1564    /// distributor this node runs a prover loop for.
1565    #[serde(skip_serializing_if = "Option::is_none", default)]
1566    pub launcher_id: Option<HexId>,
1567}
1568
1569/// Result for
1570/// [`dig.getRewardProverStatus`](crate::method::Method::GetRewardProverStatus).
1571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1572#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1573pub struct GetRewardProverStatusResult {
1574    /// One entry per prover loop this node runs, in no particular order — or
1575    /// the statement that the prover registry was never consulted.
1576    ///
1577    /// This is a [`Half`] for the same reason as
1578    /// [`ListRewardDistributorsResult`]'s two halves: a bare empty vector cannot
1579    /// tell an operator "this node runs no prover loops" apart from "I could not
1580    /// read the registry", and on a reward surface the second reads as the first
1581    /// while meaning the opposite. It describes the responder's own consultation
1582    /// of its prover registry, never a chain fact about any one distributor.
1583    pub statuses: Half<RewardProverStatus>,
1584}
1585
1586/// A minimal distributor reference — SPEC §2.6.
1587#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1588#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1589pub struct RewardDistributorRef {
1590    /// The distributor singleton's launcher id (64-hex).
1591    pub launcher_id: HexId,
1592    /// The backing store's launcher id (64-hex).
1593    pub store_id: HexId,
1594    /// The store's current generation root (64-hex).
1595    pub root: HexId,
1596}
1597
1598/// One collection a responder either consulted — and can therefore answer for —
1599/// or did not: dig-rewards-coin SPEC §12.5 clause 6.
1600///
1601/// # Why the items live INSIDE the variant
1602///
1603/// Clause 6: "the absence MUST be surfaced, not swallowed", and it "MUST be
1604/// dated by an `observed_at` and MUST NOT be presented as a bare zero". A bare
1605/// `claimable: []` cannot tell an operator apart "I looked and I hold no mirror
1606/// claims" from "nothing looked" — a funder-only responder emitting the empty
1607/// vector reads as the former while meaning the latter.
1608///
1609/// An observation carried *beside* its collection would leave
1610/// `{"outcome": "not_consulted", "items": [seven things]}` expressible, forbidden
1611/// only by prose. Folding the items into
1612/// [`Consulted`](Self::Consulted) makes that contradiction unconstructible in
1613/// Rust and unparseable on the wire: the arm that says nothing looked has no
1614/// field to put items in, and the arm that carries items has already said it
1615/// looked. A partially consulted half, if this crate ever needs one, is a third
1616/// arm rather than a new convention layered over the same two fields.
1617///
1618/// # What it deliberately cannot say
1619///
1620/// It describes the **responder's own consultation of the collection**, never a
1621/// chain fact about any one member. Clause 7 forbids a consumer reconstructing
1622/// "never admitted" from "evicted after settlement", and there is no arm, reason
1623/// code or per-member record here that could carry that split: after a
1624/// `Consulted` read, a distributor the peer was never admitted to and one it was
1625/// evicted from are both simply absent from `items`, exactly as before.
1626///
1627/// This does **not** discharge clause 6's *per-member* dated absence, which
1628/// needs a field this wire does not yet carry. What it closes is the
1629/// per-collection consultation record.
1630///
1631/// # Relation to `absence_established`
1632///
1633/// [`AvailabilityAnswer::absence_established`] is this crate's earlier, weaker
1634/// expression of the same idea: a marker *beside* the data, so "absence not
1635/// established, and here are seven items" stays representable and is forbidden
1636/// only by prose. `Half` is the intended direction for new shapes.
1637/// `AvailabilityAnswer` keeps its form because it has shipped consumers; it is
1638/// not a second pattern to copy.
1639///
1640/// # Fail-closed
1641///
1642/// Matching [`ProverState`]: internally tagged on `outcome`, no
1643/// `#[serde(other)]`, no `Default`, no `skip_serializing_if`, and `observed_at`
1644/// required in **every** arm. An unknown or missing outcome, or a missing date,
1645/// is a hard parse error rather than a silently coerced "consulted".
1646///
1647/// ```
1648/// use dig_rpc_protocol::types::Half;
1649///
1650/// let looked: Half<u32> = Half::Consulted { observed_at: 1_700, items: vec![] };
1651/// let did_not: Half<u32> = Half::NotConsulted { observed_at: 1_700 };
1652/// assert_eq!(looked.items(), Some(&[][..]));
1653/// assert_eq!(did_not.items(), None);
1654/// assert_eq!(did_not.observed_at(), 1_700);
1655/// ```
1656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1657#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
1658#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1659pub enum Half<T> {
1660    /// The collection WAS consulted, and `items` is its complete answer as of
1661    /// `observed_at` (Unix seconds). An empty `items` here means "none", and the
1662    /// reader derives staleness itself from `observed_at`.
1663    Consulted {
1664        /// Unix seconds the collection was read.
1665        observed_at: u64,
1666        /// The complete answer as of `observed_at`; empty means "none".
1667        items: Vec<T>,
1668    },
1669    /// The collection was NOT consulted as of `observed_at` (Unix seconds):
1670    /// nothing looked, so there is no answer here to read as "none".
1671    NotConsulted {
1672        /// Unix seconds this answer was assembled without consulting the
1673        /// collection.
1674        observed_at: u64,
1675    },
1676}
1677
1678impl<T> Half<T> {
1679    /// The Unix seconds this half was observed — present in both arms, so a
1680    /// reader always has a staleness anchor.
1681    pub fn observed_at(&self) -> u64 {
1682        match self {
1683            Half::Consulted { observed_at, .. } | Half::NotConsulted { observed_at } => {
1684                *observed_at
1685            }
1686        }
1687    }
1688
1689    /// The consulted answer, or `None` when nothing looked.
1690    ///
1691    /// `Some(&[])` means "consulted, and there are none"; `None` means "not
1692    /// consulted" — the distinction a bare `Vec` cannot make.
1693    pub fn items(&self) -> Option<&[T]> {
1694        match self {
1695            Half::Consulted { items, .. } => Some(items),
1696            Half::NotConsulted { .. } => None,
1697        }
1698    }
1699}
1700
1701/// Result for
1702/// [`dig.listRewardDistributors`](crate::method::Method::ListRewardDistributors)
1703/// — SPEC §2.6: "the distributors this node funds, and the distributors this
1704/// node has a claim to as a mirror".
1705///
1706/// # No `Default`, by design
1707///
1708/// `Default` is not derived here and MUST NOT be re-added. A default could only
1709/// be the empty, consulted-looking answer — the exact ambiguity [`Half`] exists
1710/// to remove (SPEC §12.5 clause 6). Every producer must state, per half, whether
1711/// it consulted that half.
1712#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1713#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1714pub struct ListRewardDistributorsResult {
1715    /// Distributors this node funds (the reserve is this node's), or the
1716    /// statement that the funded half was never consulted.
1717    ///
1718    /// A responder whose funded set is unconfigured, unreadable, or failed to
1719    /// read must say so here rather than emit an empty list, which would read as
1720    /// "this node funds nothing" — a claim about the operator's own money.
1721    pub funded: Half<RewardDistributorRef>,
1722    /// Distributors this node has a claim to as a mirror but does not fund, or
1723    /// the statement that the claimable half was never consulted.
1724    pub claimable: Half<RewardDistributorRef>,
1725}
1726
1727/// Params for
1728/// [`dig.getRewardDistributor`](crate::method::Method::GetRewardDistributor).
1729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1730#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1731pub struct GetRewardDistributorParams {
1732    /// The distributor singleton's launcher id (64-hex, required).
1733    pub launcher_id: HexId,
1734}
1735
1736/// Result for
1737/// [`dig.getRewardDistributor`](crate::method::Method::GetRewardDistributor) —
1738/// SPEC §2.6, third method: chain-derived distributor state only, never the
1739/// local prover loop's own state (see [`RewardProverStatus`] for that).
1740///
1741/// # `entry_set_stale` lives HERE, never on `RewardProverStatus`
1742///
1743/// This is the one boolean in the reward-distributor surface, and it belongs
1744/// here specifically: per SPEC §12.4 it is computed by the responder from the
1745/// distributor singleton's on-chain spend history at read time, not
1746/// self-reported by a possibly-wedged writer. Copying it onto
1747/// [`RewardProverStatus`] would reintroduce exactly the self-reported-health
1748/// failure that type's doc comment forbids — see that type for the full
1749/// argument.
1750///
1751/// # The chain-view anchor (`chain_peak_height` / `chain_peak_timestamp`) — SPEC §4.5
1752///
1753/// `observed_at` dates when THIS REPLY was assembled — a wall clock, and
1754/// nothing else. `entry_set_stale` above is computed on a different clock
1755/// entirely: the distributor singleton's on-chain peak. A stalled chain
1756/// source freezes that peak while the wall clock keeps advancing, which
1757/// freezes `entry_set_stale` at `false` under a freshly stamped
1758/// `observed_at` — the optimistic-staleness defect this field pair exists to
1759/// close (dig_ecosystem#3262). `chain_peak_height` and `chain_peak_timestamp`
1760/// expose the clock `entry_set_stale` was actually computed against, so a
1761/// reader can check the two are self-consistent:
1762///
1763/// ```text
1764/// entry_set_stale == (reserve_base_units > 0
1765///     && chain_peak_timestamp - last_entry_write_at.unwrap_or(0) >= 172_800)
1766/// ```
1767///
1768/// **What this check is, and is not.** Every value on the right-hand side —
1769/// `chain_peak_timestamp` included — comes from the SAME response and the
1770/// SAME responder as `entry_set_stale` itself. Re-deriving the formula from
1771/// the responder's own numbers catches an INTERNALLY INCONSISTENT responder
1772/// only; it is not evidence against a lying, wedged, or compromised one,
1773/// which can report any self-consistent triple it likes and pass this check
1774/// every time. What the anchor genuinely fixes is narrower, and real: an
1775/// HONEST but chain-stalled responder can no longer freeze `entry_set_stale`
1776/// at `false` under a freshly stamped `observed_at`, because its own stalled
1777/// chain clock now travels on the wire beside it — the defect
1778/// dig_ecosystem#3262 was filed for, and it is closed. Real protection
1779/// against a dishonest responder requires comparing `chain_peak_height`
1780/// against a chain view the consumer obtained INDEPENDENTLY of this
1781/// response — see [`Self::chain_peak_height`]. SPEC §4.5.
1782///
1783/// Both fields are **required**, never `Option`, never `0`. A responder that
1784/// cannot obtain the chain peak (dig-rewards-coin's `read_distributor`
1785/// refuses without one) MUST answer a JSON-RPC error, not a result with a
1786/// missing or zeroed anchor — there is no result arm for "I could not look".
1787#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1788#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1789pub struct GetRewardDistributorResult {
1790    /// The distributor singleton's launcher id (64-hex).
1791    pub launcher_id: HexId,
1792    /// The backing store's launcher id (64-hex).
1793    pub store_id: HexId,
1794    /// The store's current generation root (64-hex).
1795    pub root: HexId,
1796    /// The payout epoch length, in seconds.
1797    pub epoch_seconds: u64,
1798    /// Unix seconds the first epoch started.
1799    pub first_epoch_start: u64,
1800    /// The reserve threshold, in base units, that triggers a payout.
1801    pub payout_threshold: u64,
1802    /// The distributor's fee, in basis points.
1803    pub fee_bps: u16,
1804    /// The share of a clawed-back commitment the committer recovers, in basis
1805    /// points — SPEC §7.5. `withdrawal_share_bps = 9000` means a clawback
1806    /// returns 90% of the committed value; the remaining 10% is forfeited to
1807    /// the reserve as a deterrent against the funder (SPEC §7.5 clause 1: it
1808    /// is priced correctly and is **not** compensation to induced mirrors).
1809    /// Curried at launch and immutable, same as [`Self::fee_bps`] beside it.
1810    pub withdrawal_share_bps: u16,
1811    /// The current reserve, in base units.
1812    pub reserve_base_units: u64,
1813    /// The current entry-set size.
1814    pub entry_count: u64,
1815    /// The current epoch index (`0`-based from `first_epoch_start`).
1816    pub current_distributor_epoch: u64,
1817    /// Unix seconds of the most recent entry-set write on chain, if any.
1818    /// `None` together with a non-zero `reserve_base_units` **implies
1819    /// stale**: an entry set that has never been written is maximally
1820    /// stale, not unknown, and a consumer MUST NOT render it as blank or
1821    /// "unknown" (SPEC §2.4 cl. 1 — silence is not an acceptable
1822    /// representation of "not distributing").
1823    pub last_entry_write_at: Option<u64>,
1824    /// `true` when the entry set has not changed in
1825    /// `STALE_ENTRY_SET_SECONDS = 172_800` (48 h) **while the reserve is
1826    /// non-zero** — SPEC §12.4. A drained distributor with a frozen entry set
1827    /// is not stale, it is [`Unfunded`](crate::types::ProverState::Unfunded);
1828    /// the non-zero-reserve conjunct exists to keep the two states distinct.
1829    /// The responder computes this at read time from the singleton's own
1830    /// on-chain spend history — it is not self-reported, so a wedged prover
1831    /// cannot fake it. See the type doc for why this boolean is safe here and
1832    /// forbidden on [`RewardProverStatus`].
1833    pub entry_set_stale: bool,
1834    /// Unix seconds this result was assembled — a WALL clock. Says nothing
1835    /// about chain freshness; read `chain_peak_timestamp` for that (see the
1836    /// type doc's "chain-view anchor" section).
1837    pub observed_at: u64,
1838    /// The distributor singleton's chain peak height at read time
1839    /// (`ChainObservation::peak_height`, widened losslessly from `u32`).
1840    /// Required — a responder with no chain peak in hand errors instead of
1841    /// answering. This is the field that carries REAL protection against a
1842    /// dishonest responder: compare it against a chain view the consumer
1843    /// obtained independently, not against anything else in this response.
1844    /// See the type doc's trust-boundary section. SPEC §4.5.
1845    pub chain_peak_height: u64,
1846    /// `block_timestamp(chain_peak_height)` — the CHAIN clock, never the wall
1847    /// clock, and the exact clock [`Self::entry_set_stale`] is computed
1848    /// against. Required, never `0`: a responder with no chain peak errors
1849    /// instead of answering. Self-consistency against `entry_set_stale` only
1850    /// catches an internally inconsistent responder — see the type doc's
1851    /// trust-boundary section. SPEC §4.5.
1852    pub chain_peak_timestamp: u64,
1853}
1854
1855/// Params for
1856/// [`dig.listRewardDistributorCommitments`](crate::method::Method::ListRewardDistributorCommitments).
1857#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1858#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1859pub struct ListRewardDistributorCommitmentsParams {
1860    /// The distributor singleton's launcher id (64-hex, required).
1861    pub launcher_id: HexId,
1862}
1863
1864/// One clawback commitment slot for a distributor epoch — SPEC §7.4 clause 5.
1865///
1866/// # `recoverable_base_units` is NOT `rewards_base_units`
1867///
1868/// Committed is not recoverable: SPEC §7.4 clause 4 / §7.5 return only
1869/// `withdrawal_share_bps / 10000` of the committed value on clawback (the
1870/// remainder is forfeited to the reserve — see
1871/// [`GetRewardDistributorResult::withdrawal_share_bps`]). Reporting only
1872/// `rewards_base_units` and letting a caller label it "recoverable" would
1873/// overstate every clawback by the forfeit fraction — exactly the
1874/// one-balance-figure money-honesty failure SPEC §7.4 clause 5 forbids,
1875/// relocated from a single total into a single per-slot figure. So the
1876/// **responder** must compute `recoverable_base_units` itself, with integer
1877/// arithmetic in the order `rewards_base_units * withdrawal_share_bps /
1878/// 10_000` — multiply then divide, no floats, truncated (never rounded up:
1879/// rounding up would promise money the chain will not return). This type
1880/// does not enforce that computation — see below.
1881///
1882/// Only the holder of the key for `clawback_puzzle_hash` may claw this slot
1883/// back — not an operator role, not the manager singleton, and not the
1884/// launcher (SPEC §7.4 clause 3). This field is the proof of entitlement; a
1885/// reader must not mistake it for a display label.
1886///
1887/// This type does not enforce any of the above: `recoverable_base_units` is
1888/// a bare `pub u64` with no constructor or validation. The **responder**
1889/// must compute it in the order described; nothing here checks that it did.
1890#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1891#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1892pub struct RewardDistributorCommitment {
1893    /// The epoch this commitment slot funds.
1894    pub epoch_start: u64,
1895    /// The chain's `clawback_ph` (SPEC / `chia-sdk-types`
1896    /// `RewardDistributorCommitmentSlotValue`): the puzzle hash whose key
1897    /// holder alone may claw this slot back.
1898    pub clawback_puzzle_hash: HexId,
1899    /// The committed amount, in base units.
1900    pub rewards_base_units: u64,
1901    /// The amount actually recoverable on clawback, in base units —
1902    /// `rewards_base_units * withdrawal_share_bps / 10_000`, integer
1903    /// arithmetic, truncated down. See the type doc for why this must never
1904    /// be derived by a caller from `rewards_base_units` alone.
1905    ///
1906    /// This is share arithmetic only. It is **NOT an eligibility claim**: it
1907    /// says what fraction of the slot would return, not that the caller may
1908    /// claw it back. Entitlement is key-holding against
1909    /// `clawback_puzzle_hash` and nothing else (SPEC §7.4 cl. 3).
1910    pub recoverable_base_units: u64,
1911}
1912
1913/// Result for
1914/// [`dig.listRewardDistributorCommitments`](crate::method::Method::ListRewardDistributorCommitments)
1915/// — SPEC §7.4 clause 5: per-epoch commitment slots, never a single balance
1916/// figure.
1917///
1918/// # The chain-view anchor — SPEC §4.5
1919///
1920/// `commitments` is read off the distributor singleton's on-chain slots, so
1921/// it carries the same chain-view anchor as [`GetRewardDistributorResult`]
1922/// and for the same reason: `observed_at` is the wall clock of reply
1923/// assembly, `chain_peak_height` / `chain_peak_timestamp` are the chain's own
1924/// clock at read time. See that type's doc for the full argument and the
1925/// refusal rule (both anchor fields required, never `Option`, never `0`).
1926#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1927#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1928pub struct ListRewardDistributorCommitmentsResult {
1929    /// The distributor singleton's launcher id (64-hex).
1930    pub launcher_id: HexId,
1931    /// The curried launch constant, echoed so a caller's row math (dividing
1932    /// `recoverable_base_units` by `rewards_base_units`) is auditable against
1933    /// the value that actually governs it. A responder MUST use this echoed
1934    /// value — never a compiled-in constant — when computing each row's
1935    /// `recoverable_base_units`, because the share is a launch-curried,
1936    /// per-distributor value that differs across distributors. A conforming
1937    /// responder MUST NOT emit a value above `10_000`.
1938    pub withdrawal_share_bps: u16,
1939    /// The payout epoch length, in seconds — a launch-curried, immutable
1940    /// distributor constant, echoed here so a caller can compute an epoch's
1941    /// end (`epoch_start + epoch_seconds`) or place a commitment on a
1942    /// calendar without a second `dig.getRewardDistributor` call. This is
1943    /// per-distributor and defaulted, not a fixed 7-day value, so it must
1944    /// not be hardcoded.
1945    pub epoch_seconds: u64,
1946    /// One entry per commitment slot. Empty is legitimate: a distributor
1947    /// funded only via `AddIncentives` has no clawback-eligible slots at all
1948    /// — an irrevocable donation, not an error.
1949    pub commitments: Vec<RewardDistributorCommitment>,
1950    /// Unix seconds this result was assembled — a WALL clock. Says nothing
1951    /// about chain freshness; read `chain_peak_timestamp` for that.
1952    pub observed_at: u64,
1953    /// The distributor singleton's chain peak height at read time. Required
1954    /// — see [`GetRewardDistributorResult::chain_peak_height`]. SPEC §4.5.
1955    pub chain_peak_height: u64,
1956    /// `block_timestamp(chain_peak_height)` — the chain clock. Required, never
1957    /// `0` — see [`GetRewardDistributorResult::chain_peak_timestamp`]. SPEC
1958    /// §4.5.
1959    pub chain_peak_timestamp: u64,
1960}
1961
1962// ===========================================================================
1963// dig.getPayeeRewardClaimStatus
1964// (CONTROL — loopback / in-process only; dig-rewards-coin SPEC §12.5 clause 6,
1965//  §2.4)
1966// ===========================================================================
1967
1968/// The subject of a **payee-side** status answer.
1969///
1970/// One variant on purpose, and named for that one variant on purpose. A payee's
1971/// claim-side posture and a funder's distributor-side posture are different
1972/// answers with different money behind them, and this crate keeps them in
1973/// different types rather than in two arms of one enum — so a payee-shaped
1974/// result structurally cannot be built carrying a funder's subject, whatever a
1975/// responder gets wrong. A funder answer, if this crate ever grows one, gets its
1976/// own type and its own literal.
1977///
1978/// The name carries that rule. A `RewardSubject` invites a `Funder` arm, and the
1979/// moment it has one the type guarantees nothing; `PayeeSubject` cannot absorb a
1980/// funder arm without a rename obviously wrong at the call site, which is the
1981/// point.
1982#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1983#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
1984pub enum PayeeSubject {
1985    /// The node answering is speaking as a **payee** — a mirror with a claim,
1986    /// not the party that funded the reserve.
1987    #[serde(rename = "payee")]
1988    Payee,
1989}
1990
1991/// What a node can say about its own claim log: it read the log and has a count,
1992/// or it did not read the log and has no count to give.
1993///
1994/// # Why the count is inside the variant
1995///
1996/// The count and the fact that anything was counted cannot be separated, for the
1997/// same reason [`Half`]'s items live inside `Consulted`. A node whose claim log
1998/// is missing, unreadable, or failed to read has nothing to report, and a
1999/// `claims_submitted_count: 0` beside a freshly stamped `observed_at` is worse
2000/// than an undated zero: the date actively reassures the reader that something
2001/// looked at the log just now and found nothing, which is dig-rewards-coin SPEC
2002/// §12.5 clause 6's "reassuring zero" reproduced inside the type added to remove
2003/// it. There is no arm here that can carry a count without having read the log.
2004///
2005/// This is a sibling of [`Half`] rather than an instance of it: `Half` answers
2006/// for a *collection* and carries `items`, and forcing a scalar tally through it
2007/// would mean either a vacuous `Vec` or a wire key that names the wrong thing.
2008/// The vocabulary — `outcome`, two arms, `observed_at` in both — is deliberately
2009/// identical, so a reader who has learned one has learned the other.
2010///
2011/// `observed_at` dates the **consultation**, not the assembly of the answer:
2012/// in [`Consulted`](Self::Consulted) it is when the log was read, and in
2013/// [`NotConsulted`](Self::NotConsulted) it is when the responder established
2014/// that it could not read it. Fail-closed like [`Half`]: internally tagged, no
2015/// `#[serde(other)]`, no `Default`, no `skip_serializing_if`.
2016#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2017#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
2018#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2019pub enum ClaimLogObservation {
2020    /// The claim log WAS read as of `observed_at` (Unix seconds), and
2021    /// `claims_submitted_count` is what it held.
2022    Consulted {
2023        /// Unix seconds the claim log was read.
2024        observed_at: u64,
2025        /// How many claim submissions this node has made as a payee. A count of
2026        /// attempts, not of money: it says nothing about how much was settled,
2027        /// and a reader MUST NOT treat it as an amount or as a success count.
2028        claims_submitted_count: u64,
2029    },
2030    /// The claim log was NOT read as of `observed_at` (Unix seconds) — missing,
2031    /// unreadable, or the read failed. There is deliberately no count here.
2032    NotConsulted {
2033        /// Unix seconds the responder established it could not read the log.
2034        observed_at: u64,
2035    },
2036}
2037
2038/// The claim loop's own condition, as the loop last reported it — a closed
2039/// set of seven members (SPEC §4.4.3). `ClaimLoopState` mirrors the producer's
2040/// enumeration one-to-one, payloads included: a wire type with fewer states
2041/// than the loop can be in is a new instance of the defect this method exists
2042/// to remove, a type that cannot say something went wrong.
2043///
2044/// The tag key is `kind`, not `state` — the field holding this type is already
2045/// named `state`, and `"state": { "state": … }` would put two meanings under
2046/// one key in adjacent positions.
2047///
2048/// [`ClaimableButNotClaiming`](Self::ClaimableButNotClaiming) is the state a
2049/// conforming producer reports **whenever claims exist that the loop did not
2050/// make and no cycle-wide fault is live** — the anti-silence signal this
2051/// method exists to carry. It is never folded into
2052/// [`Nominal`](Self::Nominal) for lack of anywhere else to go, and a
2053/// cycle-wide fault is never folded into it either.
2054///
2055/// The five payload-less members ([`Idle`](Self::Idle),
2056/// [`ChainSourceUnavailable`](Self::ChainSourceUnavailable),
2057/// [`PersistedStateCorrupt`](Self::PersistedStateCorrupt),
2058/// [`CadenceNotElapsed`](Self::CadenceNotElapsed), [`Nominal`](Self::Nominal))
2059/// serialise as exactly `{ "kind": … }`. serde does not apply
2060/// `deny_unknown_fields` to the payload-less members of an internally tagged
2061/// enum, so `{ "kind": "idle", "claimable": 5 }` parses as `Idle` with the
2062/// stray key silently dropped (SPEC §4.4.1's one stated vacuity) — a
2063/// conforming producer never emits the stray key, and a consumer MUST NOT
2064/// read any key but `kind` from a payload-less state. The property this type
2065/// does enforce is the one that carries weight: the counts a reader acts on
2066/// live on [`ClaimLoopObservation::Consulted`], where unknown and missing
2067/// keys ARE rejected.
2068///
2069/// Not `#[non_exhaustive]`, on purpose: a wildcard arm in a consumer is
2070/// `#[serde(other)]` relocated to the render path, deciding at compile time
2071/// that a state nobody has heard of renders as something bland. A new member
2072/// is a SPEC amendment and a breaking release for every consumer.
2073#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2074#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
2075#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2076pub enum ClaimLoopState {
2077    /// No cycle has been attempted yet.
2078    Idle,
2079    /// The chain seam reported itself unavailable; no cycle ran. The true
2080    /// state, not a silent no-op.
2081    ChainSourceUnavailable,
2082    /// The loop's persisted claim state was unreadable, unparsable, over its
2083    /// own budget or future-dated; the loop treats its spend window as
2084    /// exhausted and submits nothing this cycle. A refusal made visible, not
2085    /// a freeze that reads as [`Nominal`](Self::Nominal).
2086    PersistedStateCorrupt,
2087    /// The claim cadence has not elapsed since the last completed cycle: a
2088    /// deliberate skip, named as its own condition rather than left as the
2089    /// absence of one.
2090    CadenceNotElapsed,
2091    /// A chain call this cycle failed with a real error, distinct from "no
2092    /// chain at all".
2093    Faulted {
2094        /// Consecutive cycles, including the current one, on which the loop
2095        /// has observed a cycle-wide fault. From a conforming producer this
2096        /// is at least 1; the type does not reject `0`.
2097        cycles: u64,
2098    },
2099    /// Fewer distributors were claimed against this cycle than should have
2100    /// been, and no fault is live. **The anti-silence signal**: the loop is
2101    /// running and paying nobody, or not everybody. This is the state
2102    /// reported whenever claims exist and none are being made.
2103    ClaimableButNotClaiming {
2104        /// This cycle's distributors that should have been claimed against.
2105        /// A count of distributors, never an amount, and at least
2106        /// [`ClaimLoopObservation::Consulted`]'s own
2107        /// `distributors_claimable` — the producer folds in refusals it
2108        /// never counted as claimable.
2109        claimable: u64,
2110        /// This cycle's distributors actually claimed against. From a
2111        /// conforming producer, strictly less than `claimable`; the type
2112        /// does not reject the contrary.
2113        submitted: u64,
2114    },
2115    /// A cycle completed and none of the above is true.
2116    Nominal,
2117}
2118
2119/// What a node can say about its own claim loop: it read the loop's last
2120/// reported condition and has counts and a state, or it did not read the loop
2121/// and has nothing to give.
2122///
2123/// A sibling of [`ClaimLogObservation`], same vocabulary: `outcome`, two
2124/// arms, `observed_at` in both. `observed_at` dates the **consultation** —
2125/// in [`Consulted`](Self::Consulted) it is when the loop last wrote the
2126/// status this arm reports, stamped by the loop in the cycle that produced
2127/// these numbers or, before any cycle, when the loop published its initial
2128/// `idle`; a responder MUST NOT stamp it with the clock of the RPC handler
2129/// that read the status. Re-dating the snapshot at read time manufactures
2130/// freshness for a number nobody produced just now, and only an
2131/// `observed_at` that stops advancing tells a reader a stuck loop's last
2132/// `nominal` is its last word rather than its current one.
2133///
2134/// In [`NotConsulted`](Self::NotConsulted) it is when the responder
2135/// established the loop's status could not be read: the loop is not
2136/// constructed (claiming disabled or not started) or its status was
2137/// unreadable — not "the chain is unreachable" (that is a
2138/// [`ClaimLoopState`]) and not "no distributors" (that is a count).
2139///
2140/// Fail-closed like [`ClaimLogObservation`]: internally tagged, no
2141/// `#[serde(other)]`, no `Default`, no `skip_serializing_if`,
2142/// `deny_unknown_fields` on the whole enum — a count or a verdict cannot
2143/// ride an arm that says nothing was read.
2144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2145#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
2146#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2147pub enum ClaimLoopObservation {
2148    /// The claim loop's status WAS read as of `observed_at` (Unix seconds).
2149    Consulted {
2150        /// Unix seconds the claim loop last wrote the status this arm
2151        /// reports.
2152        observed_at: u64,
2153        /// How many reward distributors this node's claim loop has
2154        /// discovered as candidates it might hold an entry in. A count of
2155        /// distributors, never an amount.
2156        distributors_known: u64,
2157        /// How many of those the loop judged claimable in the cycle dated by
2158        /// `observed_at`. A count of distributors, never an amount, and a
2159        /// per-cycle reading, not a lifetime total.
2160        distributors_claimable: u64,
2161        /// The loop's condition in the cycle dated by `observed_at`.
2162        state: ClaimLoopState,
2163    },
2164    /// The claim loop's status was NOT read as of `observed_at` (Unix
2165    /// seconds) — the loop is not constructed or its status was unreadable.
2166    /// There is deliberately no count and no state here.
2167    NotConsulted {
2168        /// Unix seconds the responder established it could not read the
2169        /// loop's status.
2170        observed_at: u64,
2171    },
2172}
2173
2174/// Result for
2175/// [`dig.getPayeeRewardClaimStatus`](crate::method::Method::GetPayeeRewardClaimStatus)
2176/// — the claim-side posture of the node answering, as a payee.
2177///
2178/// # The subject is on the wire, not inferred from the endpoint
2179///
2180/// [`subject`](Self::subject) is required and is the literal `"payee"`. It is
2181/// not redundant with the method name: this epic shipped a defect in which a
2182/// **funder's** distributor-wide total was rendered to a **payee** as that
2183/// operator's own earnings, overstating by up to 250x, and it passed security
2184/// review and a full green CI because no test asserted *whose* money the number
2185/// was. A renderer that reads `subject` off the payload cannot make that
2186/// substitution silently; one that infers the subject from which endpoint it
2187/// thinks it called can.
2188///
2189/// # No monetary amount, at all
2190///
2191/// There is deliberately no amount field here — not optional, not nullable,
2192/// absent. A payload that carries no amount has nothing a UI can misrender as
2193/// earnings, and that absence is the whole defence; an `Option<u64>` would not
2194/// be, because the misrendering path is a present number attributed to the wrong
2195/// party. A payee that wants its own settled history reads its own past
2196/// `InitiatePayout` spends, which are on chain and are evidence (SPEC §12.5
2197/// clause 7). The payout puzzle hash is likewise absent and MUST NOT be added:
2198/// it is the payee's payment identity, and nothing here needs it.
2199///
2200/// # No `#[serde(default)]`, no `skip_serializing_if`
2201///
2202/// Every field is required on the wire in both directions. A defaulting field is
2203/// a field a producer can omit and a consumer will invent — which for
2204/// [`subject`](Self::subject) would restore exactly the inferred-subject hazard
2205/// above, and for [`claim_log`](Self::claim_log) would manufacture a
2206/// consultation nobody performed.
2207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2208#[serde(deny_unknown_fields)]
2209#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2210pub struct PayeeClaimStatus {
2211    /// Always [`PayeeSubject::Payee`]; serialises as the literal
2212    /// `"subject": "payee"`.
2213    pub subject: PayeeSubject,
2214    /// This node's claim log: read, with the count it held, or not read at all.
2215    ///
2216    /// The count lives inside the observation so it cannot be separated from the
2217    /// fact that something read the log. The reader derives staleness itself
2218    /// from the observation's `observed_at` and its own clock (SPEC §2.4); no
2219    /// staleness is pre-computed here.
2220    pub claim_log: ClaimLogObservation,
2221    /// This node's claim loop: read, with its counts and last-reported
2222    /// state, or not read at all (new in 0.13.0, SPEC §4.4).
2223    ///
2224    /// New in 0.13.0. `deny_unknown_fields` on this struct means a 0.12.0
2225    /// payload — which has no `claim_loop` key — fails to parse rather than
2226    /// silently answering with a missing field: version skew fails loudly in
2227    /// both directions.
2228    pub claim_loop: ClaimLoopObservation,
2229}
2230
2231// ===========================================================================
2232// dig.health / dig.methods / rpc.discover  (discovery)
2233// ===========================================================================
2234
2235/// Result for [`dig.health`](crate::method::Method::Health) — liveness + a
2236/// capability summary.
2237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2238#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2239pub struct Health {
2240    /// Liveness — `"ok"` when the node can serve.
2241    pub status: String,
2242    /// The node's software version.
2243    #[serde(skip_serializing_if = "Option::is_none", default)]
2244    pub version: Option<String>,
2245    /// The DIG network id the node serves.
2246    #[serde(skip_serializing_if = "Option::is_none", default)]
2247    pub network_id: Option<String>,
2248    /// The method names this node implements (its profile).
2249    #[serde(default)]
2250    pub methods: Vec<String>,
2251}
2252
2253/// Result for [`dig.methods`](crate::method::Method::Methods) — the method names
2254/// this node implements (agent self-describe).
2255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
2256#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
2257pub struct Methods {
2258    /// The implemented method names.
2259    pub methods: Vec<String>,
2260}
2261
2262#[cfg(test)]
2263mod tests {
2264    use super::*;
2265    use serde_json::json;
2266
2267    /// The JSON object keys of `value`, sorted — so a key-set assertion reads as
2268    /// one line and fails naming the field that appeared or vanished.
2269    fn sorted_keys(value: &serde_json::Value) -> Vec<&str> {
2270        let mut keys: Vec<&str> = value
2271            .as_object()
2272            .expect("expected a JSON object")
2273            .keys()
2274            .map(String::as_str)
2275            .collect();
2276        keys.sort_unstable();
2277        keys
2278    }
2279
2280    /// **Proves:** `ContentChunk` round-trips a node-profile window (no
2281    /// network-profile fields) without inventing keys.
2282    /// **Catches:** a missing `skip_serializing_if` that would leak `null`
2283    /// network-profile fields onto the node profile.
2284    #[test]
2285    fn content_chunk_node_profile_is_lean() {
2286        let c = ContentChunk {
2287            ciphertext: "AAA=".into(),
2288            root: "ab".repeat(32),
2289            complete: false,
2290            next_offset: Some(3_145_728),
2291            inclusion_proof: Some("cHJvb2Y=".into()),
2292            chunk_lens: Some(vec![10, 20]),
2293            source: Some("local".into()),
2294            total_length: None,
2295            length: None,
2296            offset: None,
2297            program_hash: None,
2298        };
2299        let v = serde_json::to_value(&c).unwrap();
2300        assert_eq!(v["source"], "local");
2301        assert!(
2302            v.get("total_length").is_none(),
2303            "node profile must omit total_length"
2304        );
2305        assert!(v.get("program_hash").is_none());
2306        assert_eq!(serde_json::from_value::<ContentChunk>(v).unwrap(), c);
2307    }
2308
2309    /// **Proves:** the network-profile fields serialize when present.
2310    #[test]
2311    fn content_chunk_network_profile_carries_extras() {
2312        let c = ContentChunk {
2313            ciphertext: "AAA=".into(),
2314            root: "cd".repeat(32),
2315            complete: true,
2316            next_offset: None,
2317            inclusion_proof: None,
2318            chunk_lens: None,
2319            source: None,
2320            total_length: Some(100),
2321            length: Some(100),
2322            offset: Some(0),
2323            program_hash: Some("ef".repeat(32)),
2324        };
2325        let v = serde_json::to_value(&c).unwrap();
2326        assert_eq!(v["total_length"], 100);
2327        assert_eq!(v["length"], 100);
2328        assert!(v.get("source").is_none());
2329    }
2330
2331    /// **Proves:** the untagged `Inventory` picks `ForStore` vs `AllStores` by
2332    /// shape.
2333    /// **Catches:** a lost `#[serde(untagged)]` that would tag the variant.
2334    #[test]
2335    fn inventory_untagged_by_shape() {
2336        let for_store = Inventory::ForStore {
2337            store_id: "ab".repeat(32),
2338            roots: vec!["cd".repeat(32)],
2339        };
2340        let s = serde_json::to_string(&for_store).unwrap();
2341        assert!(s.contains("\"roots\""));
2342        assert!(!s.contains("ForStore"));
2343        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), for_store);
2344
2345        let all = Inventory::AllStores {
2346            stores: vec!["ef".repeat(32)],
2347        };
2348        let s = serde_json::to_string(&all).unwrap();
2349        assert!(s.contains("\"stores\""));
2350        assert_eq!(serde_json::from_str::<Inventory>(&s).unwrap(), all);
2351    }
2352
2353    /// **Proves:** `RedirectInfo` serializes the full redirect payload the
2354    /// `-32008` envelope carries.
2355    #[test]
2356    fn redirect_info_shape() {
2357        let r = RedirectInfo {
2358            content: ContentRef {
2359                store_id: "ab".repeat(32),
2360                root: Some("cd".repeat(32)),
2361                retrieval_key: Some("ef".repeat(32)),
2362            },
2363            providers: vec![Provider {
2364                peer_id: "12".repeat(32),
2365                addresses: vec![PeerAddress {
2366                    host: "::1".into(),
2367                    port: 9444,
2368                    kind: "direct".into(),
2369                }],
2370            }],
2371            redirect_depth: 1,
2372            max_redirects: 4,
2373        };
2374        let v = serde_json::to_value(&r).unwrap();
2375        assert_eq!(v["redirect_depth"], 1);
2376        assert_eq!(v["max_redirects"], 4);
2377        assert_eq!(v["providers"][0]["addresses"][0]["host"], "::1");
2378        assert_eq!(serde_json::from_value::<RedirectInfo>(v).unwrap(), r);
2379    }
2380
2381    /// **Proves:** `cache.stats` models the live dig-node result field-for-field
2382    /// (the nested `content_cache{hits,misses}` object included).
2383    /// **Catches:** a drift from the node's `cache.stats` wire shape (#1075).
2384    #[test]
2385    fn cache_stats_wire_shape() {
2386        let s = CacheStats {
2387            cap_bytes: 1 << 30,
2388            used_bytes: 2048,
2389            entry_count: 3,
2390            total_bytes: 2048,
2391            evicted_count: 1,
2392            evicted_bytes: 512,
2393            content_cache: ContentCacheCounters { hits: 7, misses: 2 },
2394        };
2395        let v = serde_json::to_value(s).unwrap();
2396        assert_eq!(v["cap_bytes"], 1 << 30);
2397        assert_eq!(v["entry_count"], 3);
2398        assert_eq!(v["content_cache"]["hits"], 7);
2399        assert_eq!(v["content_cache"]["misses"], 2);
2400        assert_eq!(serde_json::from_value::<CacheStats>(v).unwrap(), s);
2401    }
2402
2403    /// **Proves:** the subscription-management results carry the exact
2404    /// `{subscribed, added|removed, store_id}` / `{subscriptions, count}` shapes
2405    /// the live node returns.
2406    #[test]
2407    fn subscription_result_shapes() {
2408        let sub = SubscribeResult {
2409            subscribed: true,
2410            added: true,
2411            store_id: "ab".repeat(32),
2412        };
2413        let v = serde_json::to_value(&sub).unwrap();
2414        assert_eq!(v["subscribed"], true);
2415        assert_eq!(v["added"], true);
2416        assert_eq!(serde_json::from_value::<SubscribeResult>(v).unwrap(), sub);
2417
2418        let unsub = UnsubscribeResult {
2419            subscribed: false,
2420            removed: true,
2421            store_id: "cd".repeat(32),
2422        };
2423        let v = serde_json::to_value(&unsub).unwrap();
2424        assert_eq!(v["subscribed"], false);
2425        assert_eq!(v["removed"], true);
2426        assert_eq!(
2427            serde_json::from_value::<UnsubscribeResult>(v).unwrap(),
2428            unsub
2429        );
2430
2431        let list = SubscriptionsList {
2432            subscriptions: vec!["ef".repeat(32)],
2433            count: 1,
2434        };
2435        let v = serde_json::to_value(&list).unwrap();
2436        assert_eq!(v["count"], 1);
2437        assert_eq!(
2438            serde_json::from_value::<SubscriptionsList>(v).unwrap(),
2439            list
2440        );
2441    }
2442
2443    /// **Proves:** `ModuleInfo` carries `chunk_lens` covering every chunk, and
2444    /// round-trips with unknown future fields.
2445    /// **Catches:** a missing `chunk_lens` field that would leave a puller unable
2446    /// to map a fetched byte range to its covering chunk hash.
2447    /// **Invariants enforced by docs:** `chunk_lens` must have the same length as
2448    /// `chunk_hashes` and must sum to `total_size`.
2449    #[test]
2450    fn module_info_chunk_lens_shape() {
2451        let info = ModuleInfo {
2452            total_size: 1024,
2453            module_hash: "ab".repeat(32),
2454            chunk_hashes: vec!["cd".repeat(32), "ef".repeat(32)],
2455            chunk_lens: vec![512, 512],
2456        };
2457        let v = serde_json::to_value(&info).unwrap();
2458        assert_eq!(v["total_size"], 1024);
2459        assert_eq!(v["chunk_hashes"].as_array().unwrap().len(), 2);
2460        assert_eq!(v["chunk_lens"].as_array().unwrap().len(), 2);
2461        assert_eq!(v["chunk_lens"][0], 512);
2462        assert_eq!(v["chunk_lens"][1], 512);
2463        assert_eq!(serde_json::from_value::<ModuleInfo>(v).unwrap(), info);
2464    }
2465
2466    /// **Proves:** `ModuleInfo` deserialization REJECTS missing `chunk_lens` field.
2467    /// This is a REQUIRED field (not optional) — omitting it from the wire is a
2468    /// protocol violation and must fail-closed.
2469    #[test]
2470    fn module_info_rejects_missing_chunk_lens() {
2471        let json_str = r#"{"total_size": 2048, "module_hash": "1122334455667788990011223344556677889900112233445566778899001122", "chunk_hashes": []}"#;
2472        let result: Result<ModuleInfo, _> = serde_json::from_str(json_str);
2473        assert!(
2474            result.is_err(),
2475            "ModuleInfo must reject JSON missing the required chunk_lens field"
2476        );
2477        let err = result.unwrap_err();
2478        assert!(
2479            err.to_string().contains("chunk_lens"),
2480            "error message should mention chunk_lens: {}",
2481            err
2482        );
2483    }
2484
2485    /// **Proves:** the peer connect/disconnect params + results round-trip and
2486    /// match the node's `{connected|disconnected, peer_id}` shapes.
2487    #[test]
2488    fn peer_connect_disconnect_shapes() {
2489        let p = PeerConnectParams {
2490            peer: "12".repeat(32),
2491        };
2492        let v = serde_json::to_value(&p).unwrap();
2493        assert_eq!(serde_json::from_value::<PeerConnectParams>(v).unwrap(), p);
2494
2495        let c = PeerConnectResult {
2496            connected: true,
2497            peer_id: "12".repeat(32),
2498        };
2499        let v = serde_json::to_value(&c).unwrap();
2500        assert_eq!(v["connected"], true);
2501        assert_eq!(serde_json::from_value::<PeerConnectResult>(v).unwrap(), c);
2502
2503        let d = PeerDisconnectResult {
2504            disconnected: true,
2505            peer_id: "34".repeat(32),
2506        };
2507        let v = serde_json::to_value(&d).unwrap();
2508        assert_eq!(v["disconnected"], true);
2509        assert_eq!(
2510            serde_json::from_value::<PeerDisconnectResult>(v).unwrap(),
2511            d
2512        );
2513    }
2514
2515    /// **Proves:** `cache.getConfig` uses the canonical `cache_dir` field name.
2516    /// **Catches:** a regression to the shell's historical `dir` name.
2517    #[test]
2518    fn cache_config_field_name_is_cache_dir() {
2519        let c = CacheConfig {
2520            cap_bytes: 1 << 30,
2521            used_bytes: 0,
2522            cache_dir: "/var/cache/dig".into(),
2523            shared: true,
2524        };
2525        let v = serde_json::to_value(&c).unwrap();
2526        assert!(v.get("cache_dir").is_some());
2527        assert!(v.get("dir").is_none(), "must not use the legacy `dir` name");
2528    }
2529
2530    /// **Proves:** an OLDER client's `dig.getAvailability` params — written
2531    /// before the hop budget existed — still deserialize, and read as a fresh,
2532    /// unhopped ask.
2533    /// **Catches:** a `redirect_depth` declared as a required `u64`, which
2534    /// rejects exactly these params with `missing field redirect_depth` and would
2535    /// make every pre-0.8 caller's ask a parse error at the peer boundary.
2536    /// **Guarded by:** the field's `Option` TYPE. `serde`'s derive already reads a
2537    /// missing `Option` field as `None`, so the `#[serde(default)]` beside it is
2538    /// parity with the sibling params types rather than the live guard — removing
2539    /// it alone leaves this test green (mutant-tested). Do not cite the attribute
2540    /// as the thing that keeps older clients working.
2541    #[test]
2542    fn get_availability_params_accepts_an_older_clients_params() {
2543        let older = json!({
2544            "items": [ { "store_id": "ab".repeat(32) } ]
2545        });
2546        let p: GetAvailabilityParams = serde_json::from_value(older).unwrap();
2547        assert_eq!(p.items.len(), 1);
2548        assert_eq!(p.redirect_depth, None, "an absent budget stays absent");
2549        assert_eq!(p.hops_consumed(), 0, "absent means zero hops consumed");
2550    }
2551
2552    /// **Proves:** a hop-zero ask serializes to exactly the pre-0.8 bytes — the
2553    /// `redirect_depth` key is absent, not `null`.
2554    /// **Catches:** a bare `#[serde(default)]` without `skip_serializing_if`,
2555    /// which would add `"redirect_depth": null` to every existing caller's
2556    /// frame and change the wire for callers that never opted in.
2557    #[test]
2558    fn get_availability_params_omits_an_absent_hop_budget() {
2559        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
2560            store_id: "ab".repeat(32),
2561            root: None,
2562            retrieval_key: None,
2563        }]);
2564        let v = serde_json::to_value(&p).unwrap();
2565        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
2566        assert_eq!(keys, vec!["items"], "hop-zero params carry only `items`");
2567    }
2568
2569    /// **Proves:** a hopped ask round-trips its budget under the `redirect_depth`
2570    /// key, and reads back through `hops_consumed`.
2571    #[test]
2572    fn get_availability_params_round_trips_the_hop_budget() {
2573        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
2574            store_id: "cd".repeat(32),
2575            root: Some("ef".repeat(32)),
2576            retrieval_key: None,
2577        }])
2578        .with_redirect_depth(2);
2579        let v = serde_json::to_value(&p).unwrap();
2580        assert_eq!(v["redirect_depth"], 2);
2581        assert_eq!(p.hops_consumed(), 2);
2582        assert_eq!(
2583            serde_json::from_value::<GetAvailabilityParams>(v).unwrap(),
2584            p
2585        );
2586    }
2587
2588    /// **Proves:** an older client params object — written before ANY of the
2589    /// recursive-ask fields existed — still deserializes, and every new field reads
2590    /// as its documented absent value.
2591    /// **Catches:** any of the three declared as required, which would turn every
2592    /// pre-0.9 caller ask into `missing field` at the peer boundary.
2593    #[test]
2594    fn get_availability_params_accepts_a_client_older_than_the_recursive_ask() {
2595        let older = json!({ "items": [ { "store_id": "ab".repeat(32) } ] });
2596        let p: GetAvailabilityParams = serde_json::from_value(older).unwrap();
2597
2598        assert_eq!(p.budget_ms(), None, "absent budget_ms means unbudgeted");
2599        assert_eq!(p.ask_id(), None, "absent ask_id means dedup opted out");
2600        assert_eq!(p.hops_consumed(), 0);
2601    }
2602
2603    /// **Proves:** a params object carrying no recursive-ask fields serializes to
2604    /// exactly the pre-0.9 bytes — the three new keys are ABSENT, not `null`.
2605    /// **Catches:** a bare `#[serde(default)]` without `skip_serializing_if`, which
2606    /// would add `"budget_ms": null` and `"ask_id": null` to the frame of every
2607    /// caller that never opted in.
2608    #[test]
2609    fn get_availability_params_omits_absent_recursive_ask_fields() {
2610        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
2611            store_id: "ab".repeat(32),
2612            root: None,
2613            retrieval_key: None,
2614        }]);
2615        let v = serde_json::to_value(&p).unwrap();
2616        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
2617        assert_eq!(keys, vec!["items"], "a plain ask carries only `items`");
2618    }
2619
2620    /// **Proves:** the time budget and the hop budget are two INDEPENDENT fields
2621    /// under two distinct keys, each round-tripping its own value.
2622    /// **Catches:** the shape defect this addition exists to prevent — folding the
2623    /// time budget into `redirect_depth`. The fixture sets them to DIFFERENT values
2624    /// (2 hops, 9000 ms) precisely so a single backing integer cannot satisfy both
2625    /// assertions; equal values would pass under either shape.
2626    #[test]
2627    fn the_time_budget_is_a_separate_field_from_the_hop_budget() {
2628        let p = GetAvailabilityParams::new(vec![AvailabilityQuery {
2629            store_id: "cd".repeat(32),
2630            root: None,
2631            retrieval_key: None,
2632        }])
2633        .with_redirect_depth(2)
2634        .with_budget_ms(9_000);
2635
2636        let v = serde_json::to_value(&p).unwrap();
2637        assert_eq!(v["redirect_depth"], 2, "hops counted UP from zero");
2638        assert_eq!(v["budget_ms"], 9_000, "milliseconds counted DOWN to zero");
2639        assert_eq!(p.hops_consumed(), 2);
2640        assert_eq!(p.budget_ms(), Some(9_000));
2641        assert_eq!(
2642            serde_json::from_value::<GetAvailabilityParams>(v).unwrap(),
2643            p
2644        );
2645    }
2646
2647    /// **Proves:** a zero time budget survives the wire as `Some(0)` and is NOT
2648    /// erased into `None`.
2649    /// **Catches:** a `skip_serializing_if` written over the VALUE rather than the
2650    /// Option (`is_zero`-style), which would make "you have no time left, do not ask
2651    /// onward" indistinguishable from "unbudgeted, use your own policy" — exactly
2652    /// inverting the field on the one hop where it matters most.
2653    #[test]
2654    fn a_zero_time_budget_is_not_the_same_as_an_absent_one() {
2655        let exhausted = GetAvailabilityParams::new(vec![]).with_budget_ms(0);
2656        let v = serde_json::to_value(&exhausted).unwrap();
2657
2658        assert_eq!(v["budget_ms"], 0, "an exhausted budget stays on the wire");
2659        assert_eq!(
2660            serde_json::from_value::<GetAvailabilityParams>(v)
2661                .unwrap()
2662                .budget_ms(),
2663            Some(0)
2664        );
2665        assert_eq!(
2666            GetAvailabilityParams::new(vec![]).budget_ms(),
2667            None,
2668            "unbudgeted is a different state from budget zero"
2669        );
2670    }
2671
2672    /// **Proves:** `ask_id` round-trips verbatim under its own key, and is NOT the
2673    /// JSON-RPC `id`.
2674    /// **Catches:** an implementation that reuses the envelope correlator for dedup.
2675    /// The fixture puts a hardcoded `"id": 1` — the exact value dig-node was sending
2676    /// — beside a real 16-byte ask id in one envelope, so a reader that took the
2677    /// correlator would see `1` and disagree with both assertions.
2678    #[test]
2679    fn the_ask_id_is_not_the_jsonrpc_correlator() {
2680        const ASK_ID: &str = "3f9c1a04b7e25d68f0a1c3b5d7e9f012";
2681        assert_eq!(ASK_ID.len(), 32, "16 random bytes as lowercase hex");
2682
2683        let envelope = json!({
2684            "jsonrpc": "2.0",
2685            "id": 1,
2686            "method": "dig.getAvailability",
2687            "params": {
2688                "items": [ { "store_id": "ab".repeat(32) } ],
2689                "ask_id": ASK_ID,
2690            }
2691        });
2692
2693        let p: GetAvailabilityParams = serde_json::from_value(envelope["params"].clone()).unwrap();
2694        assert_eq!(p.ask_id(), Some(ASK_ID));
2695        assert_ne!(
2696            p.ask_id(),
2697            Some("1"),
2698            "the dedup identity must not be read from the envelope `id`"
2699        );
2700        assert_eq!(envelope["id"], 1, "the correlator is untouched beside it");
2701    }
2702
2703    /// **Proves:** `absence_established` distinguishes THREE states on the wire —
2704    /// asserted, explicitly-not-established, and unknown-because-older-server — and
2705    /// that the unknown state serializes as an ABSENT key rather than `false`.
2706    /// **Catches:** the collapse this field exists to prevent. The fixture carries
2707    /// all three answers in ONE batch, so a `bool` with `#[serde(default)]` (which
2708    /// would read the old server answer as `false`) makes the second and third
2709    /// answers compare EQUAL and the test fails; a fixture with only one answer
2710    /// could not see that.
2711    #[test]
2712    fn absence_established_keeps_absent_distinct_from_false() {
2713        let asserted = AvailabilityAnswer {
2714            available: false,
2715            absence_established: Some(true),
2716            ..Default::default()
2717        };
2718        let inconclusive = AvailabilityAnswer {
2719            available: false,
2720            absence_established: Some(false),
2721            ..Default::default()
2722        };
2723        let older_server = AvailabilityAnswer {
2724            available: false,
2725            ..Default::default()
2726        };
2727
2728        assert_ne!(
2729            inconclusive, older_server,
2730            "an explicit `false` is a claim; an absent field is not"
2731        );
2732        assert_eq!(asserted.absence_established_or_unknown(), Some(true));
2733        assert_eq!(inconclusive.absence_established_or_unknown(), Some(false));
2734        assert_eq!(
2735            older_server.absence_established_or_unknown(),
2736            None,
2737            "an older server makes no claim either way"
2738        );
2739
2740        let batch = serde_json::to_value(AvailabilityBatch {
2741            items: vec![asserted, inconclusive, older_server],
2742        })
2743        .unwrap();
2744        assert_eq!(batch["items"][0]["absence_established"], true);
2745        assert_eq!(batch["items"][1]["absence_established"], false);
2746        assert!(
2747            batch["items"][2].get("absence_established").is_none(),
2748            "the unknown state is an absent key, never `false` and never `null`"
2749        );
2750    }
2751
2752    /// **Proves:** an OLDER client can still read a NEWER answer — the added field
2753    /// does not break the shipped shape (§5.1).
2754    #[test]
2755    fn an_answer_carrying_the_new_field_still_parses_as_the_shipped_shape() {
2756        let newer = json!({
2757            "items": [ { "available": false, "absence_established": true } ]
2758        });
2759        let b: AvailabilityBatch = serde_json::from_value(newer).unwrap();
2760        assert_eq!(b.items.len(), 1);
2761        assert!(!b.items[0].available);
2762        assert_eq!(b.items[0].absence_established_or_unknown(), Some(true));
2763    }
2764
2765    /// **Proves:** the hop budget an availability ask carries is the SAME field,
2766    /// with the same key, type and value, that a `-32008` redirect hands back and
2767    /// that `dig.getContent` / `dig.fetchRange` already echo — one field, one
2768    /// interpretation, counted UP toward `max_redirects`.
2769    /// **Catches:** a second reading of the budget in this crate (a remaining
2770    /// allowance counting DOWN, a differently-named key, a differently-typed
2771    /// value) — the byte-drift the shipped redirect contract exists to prevent.
2772    #[test]
2773    fn availability_hop_budget_mirrors_the_redirect_budget() {
2774        let handed_back = RedirectInfo {
2775            content: ContentRef {
2776                store_id: "ab".repeat(32),
2777                root: None,
2778                retrieval_key: None,
2779            },
2780            providers: vec![],
2781            redirect_depth: 3,
2782            max_redirects: 4,
2783        };
2784        let echoed = handed_back.redirect_depth;
2785
2786        let availability = serde_json::to_value(
2787            GetAvailabilityParams::new(vec![AvailabilityQuery {
2788                store_id: "ab".repeat(32),
2789                root: None,
2790                retrieval_key: None,
2791            }])
2792            .with_redirect_depth(echoed),
2793        )
2794        .unwrap();
2795        let content = serde_json::to_value(GetContentParams {
2796            store_id: "ab".repeat(32),
2797            retrieval_key: "cd".repeat(32),
2798            root: None,
2799            offset: None,
2800            mode: None,
2801            redirect_depth: Some(echoed),
2802        })
2803        .unwrap();
2804        let range = serde_json::to_value(
2805            FetchRangeParams::resource("ab".repeat(32), "cd".repeat(32), "ef".repeat(32), 1)
2806                .with_redirect_depth(echoed),
2807        )
2808        .unwrap();
2809
2810        for (method, params) in [
2811            ("dig.getAvailability", &availability),
2812            ("dig.getContent", &content),
2813            ("dig.fetchRange", &range),
2814        ] {
2815            assert_eq!(
2816                params["redirect_depth"], 3,
2817                "{method} must carry the echoed depth under `redirect_depth`"
2818            );
2819        }
2820        assert!(
2821            handed_back.redirect_depth < handed_back.max_redirects,
2822            "the budget counts UP toward `max_redirects`"
2823        );
2824    }
2825
2826    /// **Proves:** a NEWER client's params — carrying a field this build does not
2827    /// know — still deserialize, so a hop-bearing ask is never refused outright by
2828    /// an older responder that simply ignores the budget.
2829    /// **Catches:** a `#[serde(deny_unknown_fields)]` added to the params type,
2830    /// which would turn every forward-compatible extension into a hard parse
2831    /// failure at the peer boundary.
2832    #[test]
2833    fn get_availability_params_tolerates_an_unknown_field() {
2834        let newer = json!({
2835            "items": [ { "store_id": "ab".repeat(32) } ],
2836            "redirect_depth": 1,
2837            "a_field_this_build_does_not_know": true
2838        });
2839        let p: GetAvailabilityParams = serde_json::from_value(newer).unwrap();
2840        assert_eq!(p.hops_consumed(), 1);
2841    }
2842
2843    // -----------------------------------------------------------------
2844    // dig.listRewardDistributors / dig.getRewardProverStatus /
2845    // dig.getRewardDistributor  (#3250, dig-rewards-coin SPEC §2.3/§2.6)
2846    // -----------------------------------------------------------------
2847
2848    fn sample_prover_status() -> RewardProverStatus {
2849        RewardProverStatus {
2850            launcher_id: "ab".repeat(32),
2851            store_id: "cd".repeat(32),
2852            root: "ef".repeat(32),
2853            prover_state: ProverState::Running,
2854            prover_state_since: 1_000,
2855            last_cycle_started_at: Some(1_050),
2856            last_cycle_completed_at: None,
2857            next_cycle_due_at: Some(1_600),
2858            last_entry_write_at: Some(900),
2859            consecutive_cycle_failures: 0,
2860            pending_entry_writes: 2,
2861            observed_at: 1_700,
2862            counters: ProverCounters {
2863                mirrors_seen: 3,
2864                challenges_issued: 10,
2865                challenges_passed: 9,
2866                challenges_failed: 1,
2867                entries_added: 5,
2868                entries_removed: 1,
2869                entry_count: 4,
2870                reserve_base_units: 12_345,
2871                total_paid_out_base_units: 6_789,
2872            },
2873        }
2874    }
2875
2876    /// **Proves:** `RewardProverStatus` round-trips through serde.
2877    #[test]
2878    fn reward_prover_status_round_trips() {
2879        let status = sample_prover_status();
2880        let json = serde_json::to_string(&status).unwrap();
2881        let back: RewardProverStatus = serde_json::from_str(&json).unwrap();
2882        assert_eq!(status, back);
2883    }
2884
2885    /// **Proves:** `RewardProverStatus`'s JSON key set is EXACTLY the SPEC §2.3
2886    /// field list, and contains NEITHER a health boolean NOR a pre-computed
2887    /// staleness field — SPEC §2.4: a wedged loop cannot report its own
2888    /// wedging, so a boolean the writer sets reads true forever after the
2889    /// failure it exists to reveal.
2890    /// **Catches:** a `healthy`/`ok`/`up`/`running`/`stale`/
2891    /// `seconds_since_last_run`/`is_healthy` field reintroduced onto the
2892    /// self-reported prover record.
2893    #[test]
2894    fn reward_prover_status_has_no_health_boolean_and_exact_keys() {
2895        let value = serde_json::to_value(sample_prover_status()).unwrap();
2896        let obj = value.as_object().unwrap();
2897        let mut got: Vec<&str> = obj.keys().map(String::as_str).collect();
2898        got.sort_unstable();
2899
2900        let mut want = vec![
2901            "launcher_id",
2902            "store_id",
2903            "root",
2904            "prover_state",
2905            "prover_state_since",
2906            "last_cycle_started_at",
2907            "next_cycle_due_at",
2908            "last_entry_write_at",
2909            "consecutive_cycle_failures",
2910            "pending_entry_writes",
2911            "observed_at",
2912            "counters",
2913        ];
2914        // `last_cycle_completed_at` is `None` in the fixture and this type has
2915        // no `skip_serializing_if`, so it still serializes as `null` — include it.
2916        want.push("last_cycle_completed_at");
2917        want.sort_unstable();
2918        assert_eq!(got, want);
2919
2920        // Recurse into `counters` too — a smuggled health flag could hide one
2921        // level down, and a substring check on the serialized string would
2922        // miss it (and would also be actively wrong: `ProverState::Running`
2923        // legitimately serializes the *value* `"running"`, so a
2924        // `!s.contains("running")` assertion fails on honest input while
2925        // still passing a smuggled `isRunning` key).
2926        let counters_keys: Vec<&str> = value["counters"]
2927            .as_object()
2928            .unwrap()
2929            .keys()
2930            .map(String::as_str)
2931            .collect();
2932        let mut all_keys = got.clone();
2933        all_keys.extend(counters_keys);
2934
2935        for forbidden in [
2936            "healthy",
2937            "ok",
2938            "up",
2939            "running",
2940            "isRunning",
2941            "stale",
2942            "isStale",
2943            "staleness",
2944            "secondsSinceLastRun",
2945            "uptime",
2946            "alive",
2947            "live",
2948            "lastRunSecondsAgo",
2949        ] {
2950            assert!(
2951                !all_keys.contains(&forbidden),
2952                "RewardProverStatus (incl. counters) must not carry `{forbidden}` (SPEC §2.4)"
2953            );
2954        }
2955
2956        // Also assert directly against the Rust field list, independent of the
2957        // JSON round-trip, so a `#[serde(rename)]` cannot hide a violation.
2958        got.retain(|k| *k != "prover_state"); // enum-typed; checked separately below.
2959    }
2960
2961    /// **Proves:** `ProverState` deserializes each of the nine named SPEC §2.3
2962    /// variants and REJECTS an unknown string — fail-closed: no
2963    /// `#[serde(other)]`, no `Default`.
2964    #[test]
2965    fn prover_state_covers_the_closed_set_and_rejects_unknown() {
2966        let known = [
2967            ("idle", ProverState::Idle),
2968            ("running", ProverState::Running),
2969            ("localCopyMissing", ProverState::LocalCopyMissing),
2970            (
2971                "chainSourceUnavailable",
2972                ProverState::ChainSourceUnavailable,
2973            ),
2974            ("unfunded", ProverState::Unfunded),
2975            ("feeBudgetExhausted", ProverState::FeeBudgetExhausted),
2976            ("entrySetFull", ProverState::EntrySetFull),
2977            ("paused", ProverState::Paused),
2978            ("stopped", ProverState::Stopped),
2979        ];
2980        assert_eq!(known.len(), 9, "the SPEC §2.3 set has exactly nine members");
2981        for (wire, variant) in known {
2982            let got: ProverState = serde_json::from_value(json!(wire)).unwrap();
2983            assert_eq!(got, variant, "{wire}");
2984            assert_eq!(serde_json::to_value(variant).unwrap(), json!(wire));
2985        }
2986
2987        let err = serde_json::from_value::<ProverState>(json!("somethingElse"));
2988        assert!(
2989            err.is_err(),
2990            "an unknown ProverState string must be rejected"
2991        );
2992    }
2993
2994    /// **Proves:** `GetRewardProverStatusParams` / `GetRewardProverStatusResult`
2995    /// round-trip, and the statuses half is a `Half`.
2996    #[test]
2997    fn get_reward_prover_status_types_round_trip() {
2998        let params = GetRewardProverStatusParams {
2999            launcher_id: Some("ab".repeat(32)),
3000        };
3001        let back: GetRewardProverStatusParams =
3002            serde_json::from_str(&serde_json::to_string(&params).unwrap()).unwrap();
3003        assert_eq!(params, back);
3004
3005        let result = GetRewardProverStatusResult {
3006            statuses: Half::Consulted {
3007                observed_at: 1_700,
3008                items: vec![sample_prover_status()],
3009            },
3010        };
3011        let back: GetRewardProverStatusResult =
3012            serde_json::from_str(&serde_json::to_string(&result).unwrap()).unwrap();
3013        assert_eq!(result, back);
3014    }
3015
3016    /// **Proves:** "this node runs no prover loops" and "this node could not
3017    /// read its prover registry" are DIFFERENT wire payloads, each dated.
3018    /// **Catches:** `GetRewardProverStatusResult.statuses` reverting to a bare
3019    /// `Vec`, where an unreadable registry renders as a confident "none" on a
3020    /// reward surface.
3021    #[test]
3022    fn unconsulted_prover_registry_is_distinguishable_from_an_empty_one() {
3023        let not_consulted = GetRewardProverStatusResult {
3024            statuses: Half::NotConsulted { observed_at: 1_700 },
3025        };
3026        let consulted_and_empty = GetRewardProverStatusResult {
3027            statuses: Half::Consulted {
3028                observed_at: 1_700,
3029                items: vec![],
3030            },
3031        };
3032
3033        let a = serde_json::to_value(&not_consulted).unwrap();
3034        let b = serde_json::to_value(&consulted_and_empty).unwrap();
3035        assert_ne!(
3036            a, b,
3037            "an unread prover registry must not serialise as an empty one"
3038        );
3039        assert_eq!(a["statuses"]["outcome"], "not_consulted");
3040        assert_eq!(a["statuses"]["observed_at"], 1_700);
3041        assert_eq!(b["statuses"]["outcome"], "consulted");
3042        assert_eq!(b["statuses"]["observed_at"], 1_700);
3043
3044        let back: GetRewardProverStatusResult = serde_json::from_value(a).unwrap();
3045        assert_eq!(back, not_consulted);
3046        let back: GetRewardProverStatusResult = serde_json::from_value(b).unwrap();
3047        assert_eq!(back, consulted_and_empty);
3048    }
3049
3050    /// **Proves:** `ListRewardDistributorsResult` round-trips and its JSON keys
3051    /// are exactly `funded` / `claimable`, each a `Half` object carrying its own
3052    /// `outcome`, `observed_at` and `items` (SPEC §2.6, §12.5 clause 6).
3053    #[test]
3054    fn list_reward_distributors_result_round_trips_with_exact_keys() {
3055        let result = ListRewardDistributorsResult {
3056            funded: Half::Consulted {
3057                observed_at: 1_700,
3058                items: vec![RewardDistributorRef {
3059                    launcher_id: "11".repeat(32),
3060                    store_id: "22".repeat(32),
3061                    root: "33".repeat(32),
3062                }],
3063            },
3064            claimable: Half::Consulted {
3065                observed_at: 1_700,
3066                items: vec![],
3067            },
3068        };
3069        let value = serde_json::to_value(&result).unwrap();
3070        assert_eq!(sorted_keys(&value), vec!["claimable", "funded"]);
3071        assert_eq!(
3072            sorted_keys(&value["funded"]),
3073            vec!["items", "observed_at", "outcome"],
3074            "a half must carry its items INSIDE the tagged observation"
3075        );
3076
3077        let back: ListRewardDistributorsResult = serde_json::from_value(value).unwrap();
3078        assert_eq!(result, back);
3079    }
3080
3081    /// **Proves:** "the mirror-claim half was not consulted" and "it was
3082    /// consulted and is empty" are DIFFERENT wire payloads — the whole point of
3083    /// SPEC §12.5 clause 6. Both carry an `observed_at`, so neither is a bare,
3084    /// undated zero.
3085    /// **Catches:** the dated absence collapsing back into a plain empty vector,
3086    /// which is how a funder-only answer came to read as "you have no mirror
3087    /// claims".
3088    #[test]
3089    fn unconsulted_claimable_half_is_distinguishable_from_an_empty_one() {
3090        let not_consulted = ListRewardDistributorsResult {
3091            funded: Half::Consulted {
3092                observed_at: 1_700,
3093                items: vec![],
3094            },
3095            claimable: Half::NotConsulted { observed_at: 1_700 },
3096        };
3097        let consulted_and_empty = ListRewardDistributorsResult {
3098            claimable: Half::Consulted {
3099                observed_at: 1_700,
3100                items: vec![],
3101            },
3102            ..not_consulted.clone()
3103        };
3104
3105        let a = serde_json::to_value(&not_consulted).unwrap();
3106        let b = serde_json::to_value(&consulted_and_empty).unwrap();
3107        assert_ne!(
3108            a, b,
3109            "an unconsulted half must not serialise as an empty one"
3110        );
3111        assert_eq!(a["claimable"]["outcome"], "not_consulted");
3112        assert_eq!(a["claimable"]["observed_at"], 1_700);
3113        assert_eq!(b["claimable"]["outcome"], "consulted");
3114
3115        let back: ListRewardDistributorsResult = serde_json::from_value(a).unwrap();
3116        assert_eq!(back, not_consulted);
3117    }
3118
3119    /// **Proves:** "this node's funded half was not consulted" and "it was
3120    /// consulted and is empty" are DIFFERENT wire payloads, each dated, exactly
3121    /// as for the mirror-claim half (SPEC §12.5 clause 6).
3122    /// **Catches:** a node that cannot read its own funder registry -- not
3123    /// configured, persisted state corrupt, or the read failed -- reporting an
3124    /// empty funded list, which states that the operator funds nothing.
3125    #[test]
3126    fn unconsulted_funded_half_is_distinguishable_from_an_empty_one() {
3127        let not_consulted = ListRewardDistributorsResult {
3128            funded: Half::NotConsulted { observed_at: 1_700 },
3129            claimable: Half::Consulted {
3130                observed_at: 1_700,
3131                items: vec![],
3132            },
3133        };
3134        let consulted_and_empty = ListRewardDistributorsResult {
3135            funded: Half::Consulted {
3136                observed_at: 1_700,
3137                items: vec![],
3138            },
3139            ..not_consulted.clone()
3140        };
3141
3142        let a = serde_json::to_value(&not_consulted).unwrap();
3143        let b = serde_json::to_value(&consulted_and_empty).unwrap();
3144        assert_ne!(
3145            a, b,
3146            "an unconsulted funded half must not serialise as an empty one"
3147        );
3148        assert_eq!(a["funded"]["outcome"], "not_consulted");
3149        assert_eq!(a["funded"]["observed_at"], 1_700);
3150        assert_eq!(b["funded"]["outcome"], "consulted");
3151        assert_eq!(b["funded"]["observed_at"], 1_700);
3152
3153        let back: ListRewardDistributorsResult = serde_json::from_value(a).unwrap();
3154        assert_eq!(back, not_consulted);
3155        let back: ListRewardDistributorsResult = serde_json::from_value(b).unwrap();
3156        assert_eq!(back, consulted_and_empty);
3157    }
3158
3159    /// **Proves:** "nothing looked, and here are the results" is UNREPRESENTABLE
3160    /// — in Rust, because [`Half::NotConsulted`] has no `items` field at all; and
3161    /// on the wire, because the arm denies unknown fields, so a producer that
3162    /// emits both is a parse ERROR rather than having its items silently dropped.
3163    /// **Catches:** the observation drifting back out beside the collection,
3164    /// where only prose forbids the contradiction (dig_ecosystem#3269
3165    /// Condition 1).
3166    #[test]
3167    fn not_consulted_carrying_items_does_not_parse() {
3168        let contradiction = serde_json::json!({
3169            "outcome": "not_consulted",
3170            "observed_at": 1_700,
3171            "items": [{"launcher_id": "11".repeat(32),
3172                       "store_id": "22".repeat(32),
3173                       "root": "33".repeat(32)}],
3174        });
3175        assert!(
3176            serde_json::from_value::<Half<RewardDistributorRef>>(contradiction).is_err(),
3177            "\"not consulted, and here are the items\" must not parse"
3178        );
3179    }
3180
3181    /// **Proves:** `Half` is fail-closed — an unknown outcome, or one missing its
3182    /// `observed_at`, is a parse ERROR, never a silently coerced "consulted" (the
3183    /// `ProverState` discipline, SPEC §12.5 clause 6's ban on an undated absence).
3184    #[test]
3185    fn half_rejects_unknown_and_undated_outcomes() {
3186        let unknown = serde_json::json!({"outcome": "maybe", "observed_at": 1, "items": []});
3187        assert!(serde_json::from_value::<Half<RewardDistributorRef>>(unknown).is_err());
3188
3189        let undated = serde_json::json!({"outcome": "not_consulted"});
3190        assert!(serde_json::from_value::<Half<RewardDistributorRef>>(undated).is_err());
3191
3192        let undated_consulted = serde_json::json!({"outcome": "consulted", "items": []});
3193        assert!(serde_json::from_value::<Half<RewardDistributorRef>>(undated_consulted).is_err());
3194
3195        // A half that says it looked owes an answer, even an empty one.
3196        let itemless = serde_json::json!({"outcome": "consulted", "observed_at": 1});
3197        assert!(serde_json::from_value::<Half<RewardDistributorRef>>(itemless).is_err());
3198    }
3199
3200    /// **Proves:** [`Half::items`] distinguishes "consulted, none" (`Some(&[])`)
3201    /// from "not consulted" (`None`), and [`Half::observed_at`] answers in both
3202    /// arms — so a consumer never has to re-match to get a staleness anchor.
3203    #[test]
3204    fn half_accessors_keep_the_distinction() {
3205        let consulted: Half<RewardDistributorRef> = Half::Consulted {
3206            observed_at: 1_700,
3207            items: vec![],
3208        };
3209        let not_consulted: Half<RewardDistributorRef> = Half::NotConsulted { observed_at: 1_701 };
3210        assert_eq!(consulted.items().map(<[_]>::len), Some(0));
3211        assert!(not_consulted.items().is_none());
3212        assert_eq!(consulted.observed_at(), 1_700);
3213        assert_eq!(not_consulted.observed_at(), 1_701);
3214    }
3215
3216    /// A `ListRewardDistributorsResult` body with every key present, so a test
3217    /// can delete exactly one and assert the deletion is what broke it.
3218    fn full_list_reward_distributors_body() -> serde_json::Value {
3219        serde_json::json!({
3220            "funded": {"outcome": "consulted", "observed_at": 1_700, "items": []},
3221            "claimable": {"outcome": "consulted", "observed_at": 1_700, "items": []},
3222        })
3223    }
3224
3225    /// **Proves:** omitting `funded` -- or `claimable` -- is a PARSE ERROR, not a
3226    /// default, while the same body with both keys present parses. Neither half
3227    /// may be silently assumed consulted.
3228    /// **Catches:** `#[serde(default)]` (or a re-derived `Default`) being added
3229    /// as a compatibility convenience, which would make every legacy payload
3230    /// parse as "both halves consulted" -- the undated bare zero SPEC §12.5
3231    /// clause 6 forbids.
3232    #[test]
3233    fn omitting_either_half_is_a_parse_error() {
3234        serde_json::from_value::<ListRewardDistributorsResult>(full_list_reward_distributors_body())
3235            .expect("the complete body must parse, or the omission assertions prove nothing");
3236
3237        for omitted in ["funded", "claimable"] {
3238            let mut body = full_list_reward_distributors_body();
3239            body.as_object_mut().unwrap().remove(omitted).unwrap();
3240            assert!(
3241                serde_json::from_value::<ListRewardDistributorsResult>(body).is_err(),
3242                "omitting {omitted} must fail to parse, never default to consulted"
3243            );
3244        }
3245    }
3246
3247    /// **Proves:** `PayeeClaimStatus` carries the literal `"subject": "payee"`
3248    /// and a claim-log observation — and NO monetary field and no payout puzzle
3249    /// hash (dig_ecosystem#3269).
3250    /// **Catches:** an amount or a payment identity creeping back onto the payee
3251    /// payload, which is the shape that let a funder's total render as one
3252    /// operator's personal earnings.
3253    #[test]
3254    fn payee_claim_status_names_its_subject_and_carries_no_money() {
3255        let status = PayeeClaimStatus {
3256            subject: PayeeSubject::Payee,
3257            claim_log: ClaimLogObservation::Consulted {
3258                observed_at: 1_700,
3259                claims_submitted_count: 3,
3260            },
3261            claim_loop: ClaimLoopObservation::Consulted {
3262                observed_at: 1_690,
3263                distributors_known: 4,
3264                distributors_claimable: 2,
3265                state: ClaimLoopState::ClaimableButNotClaiming {
3266                    claimable: 2,
3267                    submitted: 0,
3268                },
3269            },
3270        };
3271        let value = serde_json::to_value(status).unwrap();
3272        assert_eq!(value["subject"], "payee");
3273        assert_eq!(
3274            sorted_keys(&value),
3275            vec!["claim_log", "claim_loop", "subject"],
3276            "PayeeClaimStatus gained a field -- if it names money or a payee's \
3277             payment identity, it must not ship"
3278        );
3279        assert_eq!(
3280            sorted_keys(&value["claim_log"]),
3281            vec!["claims_submitted_count", "observed_at", "outcome"],
3282            "the claim log gained a field -- the same money rule applies inside it"
3283        );
3284        assert_eq!(
3285            sorted_keys(&value["claim_loop"]),
3286            vec![
3287                "distributors_claimable",
3288                "distributors_known",
3289                "observed_at",
3290                "outcome",
3291                "state",
3292            ],
3293            "the claim loop's consulted arm gained a field -- the same money rule \
3294             applies inside it"
3295        );
3296
3297        let back: PayeeClaimStatus = serde_json::from_value(value).unwrap();
3298        assert_eq!(status, back);
3299    }
3300
3301    /// **Proves:** every field of `PayeeClaimStatus` is REQUIRED on the wire —
3302    /// nothing defaults, so a producer cannot omit the subject and have a
3303    /// consumer invent it.
3304    #[test]
3305    fn payee_claim_status_fields_do_not_default() {
3306        let full = || {
3307            serde_json::json!({
3308                "subject": "payee",
3309                "claim_log": {
3310                    "outcome": "consulted",
3311                    "observed_at": 1_700,
3312                    "claims_submitted_count": 3,
3313                },
3314                "claim_loop": {
3315                    "outcome": "consulted",
3316                    "observed_at": 1_690,
3317                    "distributors_known": 4,
3318                    "distributors_claimable": 2,
3319                    "state": { "kind": "nominal" },
3320                },
3321            })
3322        };
3323        serde_json::from_value::<PayeeClaimStatus>(full())
3324            .expect("the complete body must parse, or the omission assertions prove nothing");
3325
3326        for missing in ["subject", "claim_log", "claim_loop"] {
3327            let mut value = full();
3328            value.as_object_mut().unwrap().remove(missing).unwrap();
3329            assert!(
3330                serde_json::from_value::<PayeeClaimStatus>(value).is_err(),
3331                "{missing} must be required"
3332            );
3333        }
3334
3335        let wrong_subject = serde_json::json!({
3336            "subject": "funder",
3337            "claim_log": {
3338                "outcome": "consulted",
3339                "observed_at": 1_700,
3340                "claims_submitted_count": 3,
3341            },
3342            "claim_loop": {
3343                "outcome": "consulted",
3344                "observed_at": 1_690,
3345                "distributors_known": 4,
3346                "distributors_claimable": 2,
3347                "state": { "kind": "nominal" },
3348            },
3349        });
3350        assert!(
3351            serde_json::from_value::<PayeeClaimStatus>(wrong_subject).is_err(),
3352            "only the literal \"payee\" subject may parse into PayeeClaimStatus"
3353        );
3354    }
3355
3356    /// **Proves:** a node that never read its claim log cannot emit a count at
3357    /// all — there is no field for one in `not_consulted`, and a payload that
3358    /// carries one anyway is a parse ERROR. "Consulted and zero" and "never
3359    /// looked" are different, dated payloads.
3360    /// **Catches:** dig_ecosystem#3269 Condition 3 — a freshly dated
3361    /// `claims_submitted_count: 0` emitted by a node whose log was unreadable,
3362    /// which is SPEC §12.5 clause 6's reassuring zero with a timestamp on it.
3363    #[test]
3364    fn an_unread_claim_log_cannot_report_a_count() {
3365        let unread = PayeeClaimStatus {
3366            subject: PayeeSubject::Payee,
3367            claim_log: ClaimLogObservation::NotConsulted { observed_at: 1_700 },
3368            claim_loop: ClaimLoopObservation::NotConsulted { observed_at: 1_700 },
3369        };
3370        let read_and_zero = PayeeClaimStatus {
3371            subject: PayeeSubject::Payee,
3372            claim_log: ClaimLogObservation::Consulted {
3373                observed_at: 1_700,
3374                claims_submitted_count: 0,
3375            },
3376            claim_loop: ClaimLoopObservation::NotConsulted { observed_at: 1_700 },
3377        };
3378
3379        let a = serde_json::to_value(unread).unwrap();
3380        let b = serde_json::to_value(read_and_zero).unwrap();
3381        assert_ne!(a, b, "an unread claim log must not serialise as a zero one");
3382        assert_eq!(a["claim_log"]["outcome"], "not_consulted");
3383        assert_eq!(a["claim_log"]["observed_at"], 1_700);
3384        assert!(
3385            a["claim_log"].get("claims_submitted_count").is_none(),
3386            "an unread log has no count to give"
3387        );
3388        assert_eq!(b["claim_log"]["claims_submitted_count"], 0);
3389
3390        let contradiction = serde_json::json!({
3391            "outcome": "not_consulted",
3392            "observed_at": 1_700,
3393            "claims_submitted_count": 0,
3394        });
3395        assert!(
3396            serde_json::from_value::<ClaimLogObservation>(contradiction).is_err(),
3397            "\"never looked, and the count is zero\" must not parse"
3398        );
3399
3400        let undated = serde_json::json!({"outcome": "not_consulted"});
3401        assert!(serde_json::from_value::<ClaimLogObservation>(undated).is_err());
3402
3403        let countless = serde_json::json!({"outcome": "consulted", "observed_at": 1_700});
3404        assert!(
3405            serde_json::from_value::<ClaimLogObservation>(countless).is_err(),
3406            "a log that says it was read owes a count"
3407        );
3408    }
3409
3410    /// A `PayeeClaimStatus` carrying a fully populated `claim_loop` for use as
3411    /// a base by the new-test fixtures below.
3412    fn claim_loop_fixture() -> serde_json::Value {
3413        serde_json::json!({
3414            "subject": "payee",
3415            "claim_log": {
3416                "outcome": "not_consulted",
3417                "observed_at": 1_700,
3418            },
3419            "claim_loop": {
3420                "outcome": "consulted",
3421                "observed_at": 1_690,
3422                "distributors_known": 4,
3423                "distributors_claimable": 2,
3424                "state": { "kind": "nominal" },
3425            },
3426        })
3427    }
3428
3429    /// **Proves:** every one of the seven `ClaimLoopState` kinds round-trips
3430    /// through `PayeeClaimStatus` with exactly the keys SPEC §4.4.1 lists for
3431    /// its arm -- no more, no fewer. The two distributor counts parse from their
3432    /// correctly-named JSON keys: swapping `distributors_known` and
3433    /// `distributors_claimable` on the wire changes the parsed values.
3434    #[test]
3435    fn every_claim_loop_state_kind_round_trips_with_exact_keys() {
3436        let cases: Vec<(serde_json::Value, Vec<&str>)> = vec![
3437            (serde_json::json!({"kind": "idle"}), vec!["kind"]),
3438            (
3439                serde_json::json!({"kind": "chain_source_unavailable"}),
3440                vec!["kind"],
3441            ),
3442            (
3443                serde_json::json!({"kind": "persisted_state_corrupt"}),
3444                vec!["kind"],
3445            ),
3446            (
3447                serde_json::json!({"kind": "cadence_not_elapsed"}),
3448                vec!["kind"],
3449            ),
3450            (serde_json::json!({"kind": "nominal"}), vec!["kind"]),
3451            (
3452                serde_json::json!({"kind": "faulted", "cycles": 3}),
3453                vec!["cycles", "kind"],
3454            ),
3455            (
3456                serde_json::json!({
3457                    "kind": "claimable_but_not_claiming",
3458                    "claimable": 2,
3459                    "submitted": 0,
3460                }),
3461                vec!["claimable", "kind", "submitted"],
3462            ),
3463        ];
3464
3465        // Pin the wire names to their field bindings: a transposition on the
3466        // wire would silently invert the counts.
3467        let parsed: PayeeClaimStatus = serde_json::from_value(claim_loop_fixture()).unwrap();
3468        assert!(
3469            matches!(
3470                parsed.claim_loop,
3471                ClaimLoopObservation::Consulted { distributors_known: 4, distributors_claimable: 2, .. }
3472            ),
3473            "distributors_known must parse from the `distributors_known` key and \
3474             distributors_claimable from `distributors_claimable`; a swap must not parse into the same value"
3475        );
3476
3477        for (state, expected_keys) in cases {
3478            let mut body = claim_loop_fixture();
3479            body["claim_loop"]["state"] = state.clone();
3480            assert_eq!(
3481                sorted_keys(&state),
3482                expected_keys,
3483                "state {state:?} does not carry its SPEC section 4.4.1 key set"
3484            );
3485            let parsed: PayeeClaimStatus = serde_json::from_value(body).unwrap_or_else(|e| {
3486                panic!("state {state:?} must round-trip, got {e}");
3487            });
3488            let back = serde_json::to_value(parsed).unwrap();
3489            assert_eq!(
3490                sorted_keys(&back["claim_loop"]["state"]),
3491                expected_keys,
3492                "state {state:?} changed shape across a round trip"
3493            );
3494        }
3495    }
3496
3497    /// **Proves:** every one of `claim_loop.consulted`'s five keys is
3498    /// REQUIRED -- removing any one is a parse error, never a default.
3499    #[test]
3500    fn claim_loop_consulted_fields_do_not_default() {
3501        for missing in [
3502            "outcome",
3503            "observed_at",
3504            "distributors_known",
3505            "distributors_claimable",
3506            "state",
3507        ] {
3508            let mut body = claim_loop_fixture();
3509            body["claim_loop"].as_object_mut().unwrap().remove(missing);
3510            assert!(
3511                serde_json::from_value::<PayeeClaimStatus>(body).is_err(),
3512                "claim_loop.consulted must require {missing}"
3513            );
3514        }
3515    }
3516
3517    /// **Proves:** a `ClaimLoopState` payload is rejected for an unknown
3518    /// `kind`, for a bare-string `state`, for `faulted` missing `cycles`, for
3519    /// `claimable_but_not_claiming` missing `submitted`, and for an unknown
3520    /// key riding beside a `faulted` payload.
3521    #[test]
3522    fn claim_loop_state_rejects_malformed_and_unknown_payloads() {
3523        let reject = |state: serde_json::Value, why: &str| {
3524            let mut body = claim_loop_fixture();
3525            body["claim_loop"]["state"] = state;
3526            assert!(
3527                serde_json::from_value::<PayeeClaimStatus>(body).is_err(),
3528                "{why}"
3529            );
3530        };
3531
3532        reject(
3533            serde_json::json!({"kind": "not_a_real_state"}),
3534            "an unknown kind must not parse, never coerce to idle",
3535        );
3536        reject(
3537            serde_json::json!("idle"),
3538            "state must always be an object, never a bare string",
3539        );
3540        reject(
3541            serde_json::json!({"kind": "faulted"}),
3542            "faulted without cycles must not parse",
3543        );
3544        reject(
3545            serde_json::json!({"kind": "claimable_but_not_claiming", "claimable": 2}),
3546            "claimable_but_not_claiming without submitted must not parse",
3547        );
3548        reject(
3549            serde_json::json!({"kind": "faulted", "cycles": 3, "extra": 1}),
3550            "an unknown key beside a faulted payload must not parse",
3551        );
3552    }
3553
3554    /// **Proves:** `claim_loop.not_consulted` carries no count and no state --
3555    /// a count or a verdict cannot ride an arm that says nothing was read.
3556    #[test]
3557    fn claim_loop_not_consulted_rejects_every_count_and_state_key() {
3558        let base_not_consulted = || {
3559            serde_json::json!({
3560                "outcome": "not_consulted",
3561                "observed_at": 1_700,
3562            })
3563        };
3564
3565        for (key, value) in [
3566            ("distributors_known", serde_json::json!(0)),
3567            ("distributors_claimable", serde_json::json!(0)),
3568            ("state", serde_json::json!({"kind": "idle"})),
3569        ] {
3570            let mut claim_loop = base_not_consulted();
3571            claim_loop
3572                .as_object_mut()
3573                .unwrap()
3574                .insert(key.to_string(), value);
3575            let mut body = claim_loop_fixture();
3576            body["claim_loop"] = claim_loop;
3577            assert!(
3578                serde_json::from_value::<PayeeClaimStatus>(body).is_err(),
3579                "not_consulted must reject a stray {key}"
3580            );
3581        }
3582    }
3583
3584    /// **Proves:** the anti-silence rule (SPEC section 4.4.4) actually holds
3585    /// on the wire -- a consumer reading ONLY `claim_loop.state.kind` from
3586    /// the serialised JSON can tell "running, not paying everybody" apart
3587    /// from "nothing to do", without touching the Rust enum. Each distributor
3588    /// count rides under its own wire key: swapping `distributors_known`
3589    /// and `distributors_claimable` field names changes the JSON values.
3590    /// **Catches:** a producer that folds `claimable_but_not_claiming` into
3591    /// `nominal` or `idle`, which is the exact silence this method exists to
3592    /// remove.
3593    #[test]
3594    fn claimable_but_not_claiming_is_distinguishable_from_idle_by_json_alone() {
3595        let running_and_shortfalling = PayeeClaimStatus {
3596            subject: PayeeSubject::Payee,
3597            claim_log: ClaimLogObservation::NotConsulted { observed_at: 1_700 },
3598            claim_loop: ClaimLoopObservation::Consulted {
3599                observed_at: 1_690,
3600                distributors_known: 4,
3601                distributors_claimable: 2,
3602                state: ClaimLoopState::ClaimableButNotClaiming {
3603                    claimable: 2,
3604                    submitted: 0,
3605                },
3606            },
3607        };
3608        let nothing_to_do = PayeeClaimStatus {
3609            subject: PayeeSubject::Payee,
3610            claim_log: ClaimLogObservation::NotConsulted { observed_at: 1_700 },
3611            claim_loop: ClaimLoopObservation::Consulted {
3612                observed_at: 1_690,
3613                distributors_known: 0,
3614                distributors_claimable: 0,
3615                state: ClaimLoopState::Idle,
3616            },
3617        };
3618
3619        let a = serde_json::to_value(running_and_shortfalling).unwrap();
3620        let b = serde_json::to_value(nothing_to_do).unwrap();
3621
3622        // The two counts an operator compares must each ride under its OWN
3623        // key: a transposition on the wire would invert "known" and
3624        // "claimable" and every other assertion here would still pass.
3625        assert_eq!(a["claim_loop"]["distributors_known"], 4);
3626        assert_eq!(a["claim_loop"]["distributors_claimable"], 2);
3627
3628        let a_kind = a["claim_loop"]["state"]["kind"].as_str().unwrap();
3629        let b_kind = b["claim_loop"]["state"]["kind"].as_str().unwrap();
3630
3631        assert_ne!(
3632            a_kind, b_kind,
3633            "a loop that is running and shortfalling must not read the same as one \
3634             with nothing to do, from the JSON alone"
3635        );
3636        assert_eq!(a_kind, "claimable_but_not_claiming");
3637    }
3638
3639    /// **Proves:** an unknown top-level key on `PayeeClaimStatus` is a parse
3640    /// error, per `deny_unknown_fields` (new in 0.13.0).
3641    #[test]
3642    fn payee_claim_status_rejects_an_unknown_top_level_key() {
3643        let mut body = claim_loop_fixture();
3644        body.as_object_mut()
3645            .unwrap()
3646            .insert("amount".to_string(), serde_json::json!(5));
3647        assert!(
3648            serde_json::from_value::<PayeeClaimStatus>(body).is_err(),
3649            "an unknown top-level key must not parse"
3650        );
3651    }
3652
3653    /// **Proves:** `GetRewardDistributorResult` round-trips, and `entry_set_stale`
3654    /// IS present on this chain-derived type (contrast `RewardProverStatus`,
3655    /// which must never carry it — SPEC §12.4 vs §2.4).
3656    #[test]
3657    fn get_reward_distributor_result_round_trips_and_carries_entry_set_stale() {
3658        let params = GetRewardDistributorParams {
3659            launcher_id: "ab".repeat(32),
3660        };
3661        let back: GetRewardDistributorParams =
3662            serde_json::from_str(&serde_json::to_string(&params).unwrap()).unwrap();
3663        assert_eq!(params, back);
3664
3665        let result = GetRewardDistributorResult {
3666            launcher_id: "ab".repeat(32),
3667            store_id: "cd".repeat(32),
3668            root: "ef".repeat(32),
3669            epoch_seconds: 86_400,
3670            first_epoch_start: 1_000,
3671            payout_threshold: 500_000,
3672            fee_bps: 250,
3673            withdrawal_share_bps: 9_000,
3674            reserve_base_units: 1_000_000,
3675            entry_count: 42,
3676            current_distributor_epoch: 7,
3677            last_entry_write_at: Some(1_650),
3678            entry_set_stale: true,
3679            observed_at: 1_700,
3680            chain_peak_height: 12_345,
3681            chain_peak_timestamp: 1_690,
3682        };
3683        let value = serde_json::to_value(&result).unwrap();
3684        assert_eq!(value["entry_set_stale"], true);
3685        let back: GetRewardDistributorResult = serde_json::from_value(value).unwrap();
3686        assert_eq!(result, back);
3687    }
3688
3689    /// **Proves:** `entry_set_stale` is placed on exactly one of the two
3690    /// reward-distributor result types — present on the chain-derived
3691    /// `GetRewardDistributorResult`, absent from the self-reported
3692    /// `RewardProverStatus` — SPEC §12.4 vs §2.4.
3693    /// **Catches:** the staleness boolean migrating (or being copy-pasted)
3694    /// onto the self-reported type, which would let a wedged prover fake
3695    /// liveness by simply never flipping it.
3696    #[test]
3697    fn entry_set_stale_is_placed_on_the_chain_derived_result_only() {
3698        let prover_status = serde_json::to_value(sample_prover_status()).unwrap();
3699        assert!(
3700            !prover_status
3701                .as_object()
3702                .unwrap()
3703                .contains_key("entry_set_stale"),
3704            "RewardProverStatus must never carry entry_set_stale (SPEC §2.4)"
3705        );
3706
3707        let distributor_result = GetRewardDistributorResult {
3708            launcher_id: "ab".repeat(32),
3709            store_id: "cd".repeat(32),
3710            root: "ef".repeat(32),
3711            epoch_seconds: 86_400,
3712            first_epoch_start: 1_000,
3713            payout_threshold: 500_000,
3714            fee_bps: 250,
3715            withdrawal_share_bps: 9_000,
3716            reserve_base_units: 1_000_000,
3717            entry_count: 42,
3718            current_distributor_epoch: 7,
3719            last_entry_write_at: None,
3720            entry_set_stale: false,
3721            observed_at: 1_700,
3722            chain_peak_height: 12_345,
3723            chain_peak_timestamp: 1_690,
3724        };
3725        let value = serde_json::to_value(&distributor_result).unwrap();
3726        assert!(
3727            value.as_object().unwrap().contains_key("entry_set_stale"),
3728            "GetRewardDistributorResult must carry entry_set_stale (SPEC §12.4)"
3729        );
3730    }
3731
3732    /// **Proves:** `GetRewardProverStatusParams` with an absent `launcher_id`
3733    /// deserializes from an empty JSON object to `None` — the field is
3734    /// genuinely optional on the wire, not merely optional in Rust.
3735    #[test]
3736    fn get_reward_prover_status_params_absent_launcher_id_is_none() {
3737        let parsed: GetRewardProverStatusParams = serde_json::from_value(json!({})).unwrap();
3738        assert_eq!(parsed.launcher_id, None);
3739
3740        // And the round trip the other way: `Some` serializes the key back out.
3741        let with_id = GetRewardProverStatusParams {
3742            launcher_id: Some("ab".repeat(32)),
3743        };
3744        let value = serde_json::to_value(&with_id).unwrap();
3745        assert_eq!(value["launcher_id"], json!("ab".repeat(32)));
3746    }
3747
3748    /// **Proves:** `ListRewardDistributorCommitmentsResult` round-trips,
3749    /// including the legitimate EMPTY `commitments` case (a distributor
3750    /// funded only via `AddIncentives` has no clawback slots at all — an
3751    /// irrevocable donation, not an error) — SPEC §7.4 clause 5.
3752    #[test]
3753    fn list_reward_distributor_commitments_round_trips_with_empty_commitments() {
3754        let params = ListRewardDistributorCommitmentsParams {
3755            launcher_id: "ab".repeat(32),
3756        };
3757        let back: ListRewardDistributorCommitmentsParams =
3758            serde_json::from_str(&serde_json::to_string(&params).unwrap()).unwrap();
3759        assert_eq!(params, back);
3760
3761        let result = ListRewardDistributorCommitmentsResult {
3762            launcher_id: "ab".repeat(32),
3763            withdrawal_share_bps: 9_000,
3764            epoch_seconds: 86_400,
3765            commitments: vec![],
3766            observed_at: 1_700,
3767            chain_peak_height: 12_345,
3768            chain_peak_timestamp: 1_690,
3769        };
3770        let back: ListRewardDistributorCommitmentsResult =
3771            serde_json::from_str(&serde_json::to_string(&result).unwrap()).unwrap();
3772        assert_eq!(result, back);
3773        assert_eq!(back.epoch_seconds, 86_400);
3774    }
3775
3776    /// A full `GetRewardDistributorResult` body, as JSON, with the chain-view
3777    /// anchor fields included. Kept as one JSON literal (not a struct literal)
3778    /// so this helper compiles whether or not `chain_peak_height` /
3779    /// `chain_peak_timestamp` exist on the struct yet — the RED phase for
3780    /// ticket #3262 depends on that.
3781    fn get_reward_distributor_result_body_with_anchor() -> serde_json::Value {
3782        json!({
3783            "launcher_id": "ab".repeat(32),
3784            "store_id": "cd".repeat(32),
3785            "root": "ef".repeat(32),
3786            "epoch_seconds": 86_400,
3787            "first_epoch_start": 1_000,
3788            "payout_threshold": 500_000,
3789            "fee_bps": 250,
3790            "withdrawal_share_bps": 9_000,
3791            "reserve_base_units": 1_000_000,
3792            "entry_count": 42,
3793            "current_distributor_epoch": 7,
3794            "last_entry_write_at": 1_650,
3795            "entry_set_stale": true,
3796            "observed_at": 1_700,
3797            "chain_peak_height": 12_345,
3798            "chain_peak_timestamp": 1_690,
3799        })
3800    }
3801
3802    /// **Proves:** a `GetRewardDistributorResult` body without
3803    /// `chain_peak_height` / `chain_peak_timestamp` is a parse ERROR (the
3804    /// pre-0.14.0, 0.12.0-shaped wire body must not parse once the anchor is
3805    /// required), and the same body WITH both keys round-trips carrying
3806    /// exactly the expected key set — SPEC §4.5, dig_ecosystem#3262.
3807    /// **Catches:** `#[serde(default)]` / `Option` on either field, which
3808    /// would let the missing-key body parse silently.
3809    #[test]
3810    fn get_reward_distributor_result_refuses_a_body_without_its_chain_anchor() {
3811        let mut body = get_reward_distributor_result_body_with_anchor();
3812        body.as_object_mut()
3813            .unwrap()
3814            .remove("chain_peak_height")
3815            .unwrap();
3816        body.as_object_mut()
3817            .unwrap()
3818            .remove("chain_peak_timestamp")
3819            .unwrap();
3820        assert!(
3821            serde_json::from_value::<GetRewardDistributorResult>(body).is_err(),
3822            "a GetRewardDistributorResult body missing the chain-view anchor \
3823             must not parse -- SPEC §4.5 requires both fields"
3824        );
3825
3826        let full_body = get_reward_distributor_result_body_with_anchor();
3827        let parsed: GetRewardDistributorResult =
3828            serde_json::from_value(full_body).expect("a body carrying both anchor keys must parse");
3829        let value = serde_json::to_value(&parsed).unwrap();
3830        assert_eq!(
3831            sorted_keys(&value),
3832            vec![
3833                "chain_peak_height",
3834                "chain_peak_timestamp",
3835                "current_distributor_epoch",
3836                "entry_count",
3837                "entry_set_stale",
3838                "epoch_seconds",
3839                "fee_bps",
3840                "first_epoch_start",
3841                "last_entry_write_at",
3842                "launcher_id",
3843                "observed_at",
3844                "payout_threshold",
3845                "reserve_base_units",
3846                "root",
3847                "store_id",
3848                "withdrawal_share_bps",
3849            ],
3850            "GetRewardDistributorResult must carry exactly these keys, including \
3851             the chain-view anchor"
3852        );
3853    }
3854
3855    /// A full `ListRewardDistributorCommitmentsResult` body, as JSON, with the
3856    /// chain-view anchor fields included. See
3857    /// [`get_reward_distributor_result_body_with_anchor`] for why this is JSON
3858    /// rather than a struct literal.
3859    fn list_reward_distributor_commitments_result_body_with_anchor() -> serde_json::Value {
3860        json!({
3861            "launcher_id": "ab".repeat(32),
3862            "withdrawal_share_bps": 9_000,
3863            "epoch_seconds": 86_400,
3864            "commitments": [],
3865            "observed_at": 1_700,
3866            "chain_peak_height": 12_345,
3867            "chain_peak_timestamp": 1_690,
3868        })
3869    }
3870
3871    /// **Proves:** a `ListRewardDistributorCommitmentsResult` body without
3872    /// `chain_peak_height` / `chain_peak_timestamp` is a parse ERROR, and the
3873    /// same body WITH both keys round-trips carrying exactly the expected key
3874    /// set — SPEC §4.5, dig_ecosystem#3262 (sibling of the
3875    /// `GetRewardDistributorResult` test above).
3876    #[test]
3877    fn list_reward_distributor_commitments_result_refuses_a_body_without_its_chain_anchor() {
3878        let mut body = list_reward_distributor_commitments_result_body_with_anchor();
3879        body.as_object_mut()
3880            .unwrap()
3881            .remove("chain_peak_height")
3882            .unwrap();
3883        body.as_object_mut()
3884            .unwrap()
3885            .remove("chain_peak_timestamp")
3886            .unwrap();
3887        assert!(
3888            serde_json::from_value::<ListRewardDistributorCommitmentsResult>(body).is_err(),
3889            "a ListRewardDistributorCommitmentsResult body missing the chain-view \
3890             anchor must not parse -- SPEC §4.5 requires both fields"
3891        );
3892
3893        let full_body = list_reward_distributor_commitments_result_body_with_anchor();
3894        let parsed: ListRewardDistributorCommitmentsResult =
3895            serde_json::from_value(full_body).expect("a body carrying both anchor keys must parse");
3896        let value = serde_json::to_value(&parsed).unwrap();
3897        assert_eq!(
3898            sorted_keys(&value),
3899            vec![
3900                "chain_peak_height",
3901                "chain_peak_timestamp",
3902                "commitments",
3903                "epoch_seconds",
3904                "launcher_id",
3905                "observed_at",
3906                "withdrawal_share_bps",
3907            ],
3908            "ListRewardDistributorCommitmentsResult must carry exactly these keys, \
3909             including the chain-view anchor"
3910        );
3911    }
3912
3913    /// **Proves:** `observed_at` (wall clock of reply assembly) and
3914    /// `chain_peak_timestamp` (chain clock `entry_set_stale` is computed
3915    /// against) are DISTINCT fields that can hold different values — the
3916    /// whole point of the anchor is that one can be fresh while the other is
3917    /// stale (dig_ecosystem#3262).
3918    /// **Catches:** collapsing the two into one field, or deriving one from
3919    /// the other at serialization time.
3920    #[test]
3921    fn chain_peak_timestamp_and_observed_at_are_distinct_fields() {
3922        let mut body = get_reward_distributor_result_body_with_anchor();
3923        body["observed_at"] = json!(2_600u64);
3924        body["chain_peak_timestamp"] = json!(1_700u64);
3925        let parsed: GetRewardDistributorResult =
3926            serde_json::from_value(body).expect("full body must parse");
3927        let value = serde_json::to_value(&parsed).unwrap();
3928        assert_eq!(value["observed_at"], json!(2_600u64));
3929        assert_eq!(value["chain_peak_timestamp"], json!(1_700u64));
3930        assert_ne!(
3931            value["observed_at"], value["chain_peak_timestamp"],
3932            "observed_at (wall clock) and chain_peak_timestamp (chain clock) \
3933             must be able to disagree -- a stalled chain source freezes the \
3934             latter while the former keeps advancing"
3935        );
3936    }
3937
3938    /// **Proves:** `recoverable_base_units` is `rewards_base_units *
3939    /// withdrawal_share_bps / 10_000`, computed with integer arithmetic
3940    /// (multiply then divide) that TRUNCATES rather than rounds up — SPEC
3941    /// §7.4 clause 4 / §7.5.
3942    /// **Catches:** a rounded-up recoverable amount, which would promise
3943    /// money the chain will not return on clawback.
3944    #[test]
3945    fn commitment_recoverable_amount_truncates_and_never_exceeds_committed() {
3946        let withdrawal_share_bps: u64 = 9_000;
3947
3948        // Evenly divisible: 1_000 * 9000 / 10000 = 900.
3949        let even = RewardDistributorCommitment {
3950            epoch_start: 10,
3951            clawback_puzzle_hash: "aa".repeat(32),
3952            rewards_base_units: 1_000,
3953            recoverable_base_units: 1_000 * withdrawal_share_bps / 10_000,
3954        };
3955        assert_eq!(even.recoverable_base_units, 900);
3956
3957        // Not evenly divisible: 1_001 * 9000 / 10000 = 900.9 -> 900, not 901.
3958        let odd = RewardDistributorCommitment {
3959            epoch_start: 11,
3960            clawback_puzzle_hash: "bb".repeat(32),
3961            rewards_base_units: 1_001,
3962            recoverable_base_units: 1_001 * withdrawal_share_bps / 10_000,
3963        };
3964        assert_eq!(
3965            odd.recoverable_base_units, 900,
3966            "a non-evenly-divisible amount must truncate down, never round up"
3967        );
3968
3969        for commitment in [even, odd] {
3970            assert!(
3971                commitment.recoverable_base_units <= commitment.rewards_base_units,
3972                "recoverable_base_units must never exceed rewards_base_units"
3973            );
3974        }
3975    }
3976}