Skip to main content

dig_node_control_interface/
params.rs

1//! Typed request params for the control methods, each bound to its method + result via
2//! [`crate::traits::ControlCall`].
3//!
4//! One params type per method (even where two methods share the same field shape, e.g. the four
5//! `{ store }` methods) so the compile-time method↔params↔result binding is exact: a caller passes
6//! `PinParams { store }` and the type system yields a [`PinResult`](crate::results::PinResult).
7//! Field names are the exact wire names dig-node reads.
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{ControlError, ControlErrorCode};
12use crate::method::ControlMethod;
13use crate::results;
14use crate::traits::ControlCall;
15
16/// Bind a params type to its wire method + typed result.
17macro_rules! control_call {
18    ($ty:ty => $method:expr, $out:ty) => {
19        impl ControlCall for $ty {
20            const METHOD: ControlMethod = $method;
21            type Output = $out;
22        }
23    };
24}
25
26/// Define a no-param call: an empty params struct (serializes to `{}`) bound to its method + result.
27macro_rules! no_params {
28    ($(#[$doc:meta])* $name:ident => $method:expr, $out:ty) => {
29        $(#[$doc])*
30        #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
31        pub struct $name {}
32        control_call!($name => $method, $out);
33    };
34}
35
36no_params!(
37    /// `control.status` params (none).
38    StatusParams => ControlMethod::Status, results::StatusResult
39);
40no_params!(
41    /// `control.config.get` params (none).
42    ConfigGetParams => ControlMethod::ConfigGet, results::ConfigResult
43);
44no_params!(
45    /// `control.cache.get` params (none).
46    CacheGetParams => ControlMethod::CacheGet, results::CacheView
47);
48no_params!(
49    /// `control.cache.clear` params (none).
50    CacheClearParams => ControlMethod::CacheClear, results::CacheClearResult
51);
52no_params!(
53    /// `control.hostedStores.list` params (none).
54    HostedStoresListParams => ControlMethod::HostedStoresList, results::HostedStoresListResult
55);
56no_params!(
57    /// `control.sync.status` params (none).
58    SyncStatusParams => ControlMethod::SyncStatus, results::SyncStatusResult
59);
60no_params!(
61    /// `control.updater.status` params (none). Result is the proxied beacon status.
62    UpdaterStatusParams => ControlMethod::UpdaterStatus, serde_json::Value
63);
64no_params!(
65    /// `control.updater.resume` params (none).
66    UpdaterResumeParams => ControlMethod::UpdaterResume, serde_json::Value
67);
68no_params!(
69    /// `control.updater.checkNow` params (none).
70    UpdaterCheckNowParams => ControlMethod::UpdaterCheckNow, serde_json::Value
71);
72no_params!(
73    /// `control.pairing.list` params (none). Result is the pending + issued-token list.
74    PairingListParams => ControlMethod::PairingList, serde_json::Value
75);
76no_params!(
77    /// `control.peerStatus` params (none). Result is the peer-pool snapshot.
78    PeerStatusParams => ControlMethod::PeerStatus, serde_json::Value
79);
80no_params!(
81    /// `control.listSubscriptions` params (none).
82    ListSubscriptionsParams => ControlMethod::ListSubscriptions, results::ListSubscriptionsResult
83);
84
85/// `control.config.setUpstream` params.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct SetUpstreamParams {
88    /// The upstream DIG RPC URL to persist (blank clears the override).
89    pub upstream: String,
90}
91control_call!(SetUpstreamParams => ControlMethod::ConfigSetUpstream, results::SetUpstreamResult);
92
93/// `control.log.setLevel` params.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct SetLevelParams {
96    /// An `EnvFilter` directive, e.g. `"debug"` or `"info,dig_node_core=debug"`.
97    pub filter: String,
98}
99control_call!(SetLevelParams => ControlMethod::LogSetLevel, results::SetLevelResult);
100
101/// `control.cache.setCap` params.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct SetCapParams {
104    /// The cache size cap in bytes (floored at 64 MiB by the node).
105    pub cap_bytes: u64,
106}
107control_call!(SetCapParams => ControlMethod::CacheSetCap, results::SetCapResult);
108
109/// `control.hostedStores.pin` params.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct PinParams {
112    /// A store reference: `storeId` or `storeId:rootHash`.
113    pub store: String,
114}
115control_call!(PinParams => ControlMethod::HostedStoresPin, results::PinResult);
116
117/// `control.hostedStores.unpin` params.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct UnpinParams {
120    /// A store reference: `storeId` or `storeId:rootHash`.
121    pub store: String,
122}
123control_call!(UnpinParams => ControlMethod::HostedStoresUnpin, results::UnpinResult);
124
125/// `control.hostedStores.status` params.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct HostedStoreStatusParams {
128    /// A store reference: `storeId` or `storeId:rootHash`.
129    pub store: String,
130}
131control_call!(HostedStoreStatusParams => ControlMethod::HostedStoresStatus, results::HostedStoreStatusResult);
132
133/// `control.capsule.fetch` params: WHICH capsule to pull, named by store id + root — the same
134/// two-field shape as [`ProfileGetBodyParams`], not the colon-joined `store` string
135/// [`PinParams`]/[`SyncTriggerParams`] use, because the caller always knows both parts already
136/// (there is no store-level-only fetch).
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138pub struct CapsuleFetchParams {
139    /// The store id to fetch a capsule of.
140    pub store: String,
141    /// The capsule root to fetch.
142    pub root: String,
143}
144control_call!(CapsuleFetchParams => ControlMethod::CapsuleFetch, results::CapsuleFetchResult);
145
146/// `control.sync.trigger` params.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct SyncTriggerParams {
149    /// A capsule reference: `storeId:rootHash` (a concrete root is required).
150    pub store: String,
151}
152control_call!(SyncTriggerParams => ControlMethod::SyncTrigger, results::SyncTriggerResult);
153
154/// `control.updater.setChannel` params.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct SetChannelParams {
157    /// The update channel (`"nightly"` | `"stable"`; the beacon CLI is the sole validator).
158    pub channel: String,
159}
160control_call!(SetChannelParams => ControlMethod::UpdaterSetChannel, serde_json::Value);
161
162/// `control.updater.pause` params.
163#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
164pub struct PauseParams {
165    /// The unix-seconds time to pause until; omit to pause indefinitely.
166    #[serde(skip_serializing_if = "Option::is_none", default)]
167    pub until: Option<u64>,
168}
169control_call!(PauseParams => ControlMethod::UpdaterPause, serde_json::Value);
170
171/// `control.pairing.approve` params.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct ApproveParams {
174    /// The pending pairing's id (from `pairing.request`).
175    pub pairing_id: String,
176}
177control_call!(ApproveParams => ControlMethod::PairingApprove, results::PairingApproveResult);
178
179/// `control.pairing.revoke` params.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct RevokeParams {
182    /// The short id of the paired token to revoke.
183    pub token_id: String,
184}
185control_call!(RevokeParams => ControlMethod::PairingRevoke, results::PairingRevokeResult);
186
187/// `control.peers.connect` params.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct PeersConnectParams {
190    /// A peer address to dial, or an already-connected peer_id to resolve.
191    pub peer: String,
192}
193control_call!(PeersConnectParams => ControlMethod::PeersConnect, results::PeersConnectResult);
194
195/// `control.peers.disconnect` params.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct PeersDisconnectParams {
198    /// The peer_id to drop.
199    pub peer: String,
200}
201control_call!(PeersDisconnectParams => ControlMethod::PeersDisconnect, results::PeersDisconnectResult);
202
203/// The CANONICAL textual form of a Chia peer address, or an `INVALID_PARAMS` error.
204///
205/// Every `ip` this crate declares — in `control.chiaPeers.add` / `.remove` params and in every
206/// result that echoes one — is a bare IP literal in this form. A conforming node MUST canonicalise
207/// through this function on the way IN and store the result, so `add`, `remove` and `list` all
208/// spell the same peer the same way.
209///
210/// **Why the contract owns this rather than each implementation.** `remove` is the only way to
211/// un-trust a peer that is believed WITHOUT corroboration, and it matches by address. If the form
212/// is left to the implementation, an operator who adds `2001:db8::1` and removes `2001:DB8:0:0::1`
213/// has named the same peer twice and un-trusted nothing — an un-trust that silently does not
214/// happen. Canonicalising is what makes the two spellings one key.
215///
216/// The rules, normatively:
217///
218/// - the value MUST parse as an IPv4 or IPv6 literal ([`std::net::IpAddr`]). A hostname, an empty
219///   string, an `ip:port`, a CIDR block or a bracketed `[..]` form is REJECTED. Rejecting
220///   non-literals is also what bounds the ban list: `remove {ban: true}` persists a row keyed by
221///   this string, so an unvalidated key is unbounded at-rest growth driven by one small call;
222/// - surrounding whitespace is trimmed before parsing, and nothing else is;
223/// - the canonical rendering is [`std::net::IpAddr`]'s own `Display` — dotted-quad for v4, and for
224///   v6 the RFC 5952 lowercase, maximally-compressed form, WITHOUT brackets and WITHOUT a zone id.
225///
226/// Bracketing belongs to the socket-address form, never to this field: see
227/// [`chia_peer_endpoint`], which is the ONLY sanctioned way to join an `ip` to a port.
228///
229/// ```
230/// use dig_node_control_interface::params::canonical_peer_ip;
231/// assert_eq!(canonical_peer_ip(" 2001:0DB8:0000::1 ").unwrap(), "2001:db8::1");
232/// assert!(canonical_peer_ip("[::1]").is_err());
233/// assert!(canonical_peer_ip("node.example.com").is_err());
234/// ```
235pub fn canonical_peer_ip(raw: &str) -> Result<String, ControlError> {
236    raw.trim()
237        .parse::<std::net::IpAddr>()
238        .map(|ip| ip.to_string())
239        .map_err(|_| {
240            ControlError::of(
241                ControlErrorCode::InvalidParams,
242                format!(
243                    "ip must be a bare IPv4 or IPv6 literal (no brackets, no port, no hostname), got: {raw:?}"
244                ),
245            )
246        })
247}
248
249/// Join a canonical peer `ip` to a port, bracketing IPv6 as RFC 3986 requires.
250///
251/// The one place a peer address and a port are ever concatenated. Formatting `"{ip}:{port}"` by
252/// hand is the bug this exists to prevent: `::1` and `8444` render as `::1:8444`, which is not a
253/// malformed string a parser rejects — it is a DIFFERENT valid IPv6 address, so the mistake
254/// survives validation and silently retargets the peer.
255///
256/// ```
257/// use dig_node_control_interface::params::chia_peer_endpoint;
258/// assert_eq!(chia_peer_endpoint("::1", 8444), "[::1]:8444");
259/// assert_eq!(chia_peer_endpoint("203.0.113.7", 8444), "203.0.113.7:8444");
260/// ```
261pub fn chia_peer_endpoint(ip: &str, port: u16) -> String {
262    match ip.trim().parse::<std::net::IpAddr>() {
263        Ok(std::net::IpAddr::V6(v6)) => format!("[{v6}]:{port}"),
264        Ok(std::net::IpAddr::V4(v4)) => format!("{v4}:{port}"),
265        Err(_) => format!("{ip}:{port}"),
266    }
267}
268
269/// The maximum number of BANNED Chia peers a conforming node persists.
270///
271/// A ban is a row written at the request of one small control call and kept across restarts, so
272/// without a ceiling the blocklist is unbounded at-rest state a caller can grow for free. On
273/// overflow a node MUST evict its OLDEST ban rather than refuse the newest — a bounded list that
274/// forgets is recoverable, and a full one that refuses turns the ceiling into a denial of the ban
275/// facility itself.
276///
277/// The value is deliberately generous against the honest use (a handful of misbehaving peers) and
278/// small against the abusive one. Banned entries are enumerable through `control.chiaPeers.list`
279/// and clearable through `control.chiaPeers.remove` with `ban: false`.
280pub const MAX_BANNED_CHIA_PEERS: usize = 256;
281
282/// `control.chiaPeers.add` params — the Chia full node to start TRUSTING.
283///
284/// Trust is the whole point of this call and it is not free: a trusted peer is exempted from the
285/// corroboration this node otherwise requires (NC-12 — dialled peers are untrusted, and agreement
286/// across several concurrently-queried peers is what makes a chain read safe). An implementation
287/// MUST tell the person that before it writes the entry.
288///
289/// The trust NC-12 authorises is the operator declaring a node THEIR OWN. That is what justifies
290/// the unbounded authority the entry carries, and it does not extend to a node somebody else runs.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292pub struct ChiaPeersAddParams {
293    /// The peer's IP address, canonical per [`canonical_peer_ip`] — a bare literal, no brackets,
294    /// no port. The standard full-node port is assumed (the Sage `add_peer` request shape carries
295    /// no port either).
296    pub ip: String,
297}
298control_call!(ChiaPeersAddParams => ControlMethod::ChiaPeersAdd, results::ChiaPeersAddResult);
299
300/// `control.chiaPeers.remove` params — the Chia full node to stop trusting.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302pub struct ChiaPeersRemoveParams {
303    /// The peer's IP address, canonical per [`canonical_peer_ip`]. Matching is by that canonical
304    /// form, so an address spelled differently from the stored entry still names the same peer.
305    pub ip: String,
306    /// Ban rather than forget: the peer is kept but excluded, so discovery cannot re-add it.
307    /// Absent means `false`, which merely forgets the entry.
308    ///
309    /// A ban is EXACT-match on this one address — never a subnet — and it is local to this node,
310    /// with no effect on any other node's peer set. It persists until removed, bounded by
311    /// [`MAX_BANNED_CHIA_PEERS`], is enumerated by `control.chiaPeers.list` (`banned: true`), and
312    /// is cleared by calling `remove` again with `ban: false`. **Clearing a ban that way grants no
313    /// trust**: `add` also un-bans, but `add` confers the corroboration bypass, so it must not be
314    /// the only route back — an over-broad ban is not a reason to trust the peer it hit.
315    ///
316    /// Every banned peer is one fewer source of agreement. NC-12 rests on several independently
317    /// chosen peers agreeing, so a caller that bans steadily shrinks the honest pool toward the
318    /// peers it chose; that is why banning is on the master-token tier
319    /// ([`ControlMethod::requires_master_token`]) and why the set is bounded and visible.
320    #[serde(default)]
321    pub ban: bool,
322}
323control_call!(ChiaPeersRemoveParams => ControlMethod::ChiaPeersRemove, results::ChiaPeersRemoveResult);
324
325/// WHAT a subscription follows: ordinary content, or a dig-profile.
326///
327/// Serializes to a lowercase, language-neutral wire token (`"capsule"` / `"profile"`).
328///
329/// # Absent means [`Capsule`](SubscriptionKind::Capsule), and that is a contract, not a convenience
330///
331/// Every subscription written before this field existed is untagged, and a node's
332/// `subscriptions.json` on a real machine is FULL of them. A required `kind` would make those rows
333/// fail to deserialize, and a node that cannot read its own subscription file starts with an empty
334/// one — an upgrade that silently unsubscribes a user from everything they had. So the field is
335/// `#[serde(default)]` everywhere it appears, and the default is the meaning those untagged rows
336/// already had: a capsule.
337#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "lowercase")]
339pub enum SubscriptionKind {
340    /// Ordinary store content — the meaning every untagged subscription already carries.
341    #[default]
342    Capsule,
343    /// A dig-profile: the node additionally follows the profile ROOT and syncs its body from peers.
344    Profile,
345}
346
347/// `control.subscribe` params.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349pub struct SubscribeParams {
350    /// The store id to subscribe to.
351    pub store_id: String,
352    /// What the subscription follows. OMITTED means [`SubscriptionKind::Capsule`], so an older
353    /// client's request and an untagged on-disk row both keep their existing meaning.
354    #[serde(default)]
355    pub kind: SubscriptionKind,
356}
357control_call!(SubscribeParams => ControlMethod::Subscribe, results::SubscribeResult);
358
359/// `control.unsubscribe` params.
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
361pub struct UnsubscribeParams {
362    /// The store id to stop watching.
363    pub store_id: String,
364}
365control_call!(UnsubscribeParams => ControlMethod::Unsubscribe, results::UnsubscribeResult);
366
367/// The length of a CAT asset id (TAIL hash) in hex characters: a 32-byte hash.
368pub const ASSET_ID_HEX_LEN: usize = 64;
369
370/// A CAT asset id — the TAIL hash that names one token on the Chia chain.
371///
372/// Stored as the 32 raw bytes rather than a `String` so two spellings of the same id (uppercase,
373/// `0x`-prefixed) cannot compare unequal. Parsing normalizes; emission is always lowercase and
374/// unprefixed.
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
376pub struct AssetId([u8; 32]);
377
378/// Why an asset id could not be parsed. Deliberately small — an id is either 32 bytes of hex or it
379/// is not an id, and guessing at a near-miss is how a wallet ends up reading the wrong token.
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub enum AssetIdParseError {
382    /// Not exactly [`ASSET_ID_HEX_LEN`] hex characters (after an optional `0x` is stripped).
383    WrongLength {
384        /// The length actually supplied.
385        got: usize,
386    },
387    /// A character outside `[0-9a-fA-F]`.
388    NotHex,
389}
390
391impl core::fmt::Display for AssetIdParseError {
392    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
393        match self {
394            Self::WrongLength { got } => write!(
395                f,
396                "asset id must be {ASSET_ID_HEX_LEN} hex characters, got {got}"
397            ),
398            Self::NotHex => f.write_str("asset id contains a non-hexadecimal character"),
399        }
400    }
401}
402
403impl std::error::Error for AssetIdParseError {}
404
405impl AssetId {
406    /// Wrap 32 already-decoded bytes. `const` so canonical ids can be declared as constants.
407    pub const fn new(bytes: [u8; 32]) -> Self {
408        Self(bytes)
409    }
410
411    /// The raw 32 bytes.
412    pub const fn as_bytes(&self) -> &[u8; 32] {
413        &self.0
414    }
415
416    /// Parse a hex asset id. A `0x` prefix and uppercase digits are TOLERATED on input — both are
417    /// what a block explorer prints — and normalized away; neither is ever emitted.
418    pub fn from_hex(hex: &str) -> Result<Self, AssetIdParseError> {
419        let body = hex.strip_prefix("0x").unwrap_or(hex);
420        if body.len() != ASSET_ID_HEX_LEN {
421            return Err(AssetIdParseError::WrongLength { got: body.len() });
422        }
423        let mut bytes = [0u8; 32];
424        for (byte, pair) in bytes.iter_mut().zip(body.as_bytes().chunks_exact(2)) {
425            let hi = decode_hex_digit(pair[0])?;
426            let lo = decode_hex_digit(pair[1])?;
427            *byte = (hi << 4) | lo;
428        }
429        Ok(Self(bytes))
430    }
431
432    /// The canonical wire spelling: lowercase, unprefixed, [`ASSET_ID_HEX_LEN`] characters.
433    pub fn to_hex(&self) -> String {
434        use core::fmt::Write as _;
435        self.0
436            .iter()
437            .fold(String::with_capacity(ASSET_ID_HEX_LEN), |mut acc, byte| {
438                let _ = write!(acc, "{byte:02x}");
439                acc
440            })
441    }
442}
443
444/// Decode one ASCII hex digit into its nibble value.
445fn decode_hex_digit(c: u8) -> Result<u8, AssetIdParseError> {
446    match c {
447        b'0'..=b'9' => Ok(c - b'0'),
448        b'a'..=b'f' => Ok(c - b'a' + 10),
449        b'A'..=b'F' => Ok(c - b'A' + 10),
450        _ => Err(AssetIdParseError::NotHex),
451    }
452}
453
454impl core::fmt::Display for AssetId {
455    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
456        f.write_str(&self.to_hex())
457    }
458}
459
460/// The asset a wallet balance/coin read is denominated in: native XCH, or any CAT by asset id.
461///
462/// # Why there is no separate `Dig` variant
463///
464/// $DIG is a CAT, so it is [`Asset::DIG`] — an associated constant, not a variant. A three-variant
465/// `{Xch, Dig, Cat(id)}` would give $DIG two INEQUAL spellings, and a balance or coin list filtered
466/// by one of them would silently omit everything carrying the other: a wallet reporting half a
467/// balance as though it were the whole. One token, one value.
468///
469/// # Wire form (additive — CLAUDE.md §5.1)
470///
471/// | Value | JSON |
472/// |---|---|
473/// | [`Asset::Xch`] | `"xch"` |
474/// | [`Asset::DIG`] | `"dig"` |
475/// | any other CAT | `{"cat":"<64-hex>"}` |
476///
477/// Both legacy tokens are still ACCEPTED and `"dig"` is still EMITTED, so a node or client built
478/// before this release keeps understanding, and being understood by, one built after it.
479/// `{"cat":"<the $DIG asset id>"}` is also accepted and normalizes to [`Asset::DIG`].
480///
481/// Byte-identical to dig-app's consumer type (`dig-app-core::wallet::state::Asset`), recorded in the
482/// `canonical` skill so the two implementations cannot drift.
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
484pub enum Asset {
485    /// Native Chia (XCH), denominated in mojos.
486    Xch,
487    /// A CAT, named by its asset id and denominated in its own base units.
488    Cat(AssetId),
489}
490
491/// The legacy wire token for native Chia.
492const XCH_TOKEN: &str = "xch";
493/// The legacy wire token for $DIG, still emitted so older peers keep understanding this crate.
494const DIG_TOKEN: &str = "dig";
495
496impl Asset {
497    /// Canonical $DIG CAT asset id (TAIL hash) on Chia mainnet, as lowercase hex.
498    ///
499    /// CONTRACT: byte-identical to `dig_constants::DIG_ASSET_ID`, `chip35_dl_coin::DIG_ASSET_ID`,
500    /// and digstore-chain's. It is duplicated here rather than imported because this crate is a
501    /// level-00 foundation crate and may not depend sideways on `dig-constants` (CLAUDE.md
502    /// Appendix B). `dig_asset_id_hex_and_bytes_are_the_same_id` pins THIS crate's two spellings
503    /// of it together; agreement with the ecosystem constant is a source-of-truth obligation on
504    /// whoever changes it, recorded in the `canonical` skill.
505    pub const DIG_ASSET_ID_HEX: &'static str =
506        "a406d3a9de984d03c9591c10d917593b434d5263cabe2b42f6b367df16832f81";
507
508    /// $DIG, the CAT every capsule payment is denominated in.
509    pub const DIG: Asset = Asset::Cat(AssetId::new([
510        0xa4, 0x06, 0xd3, 0xa9, 0xde, 0x98, 0x4d, 0x03, 0xc9, 0x59, 0x1c, 0x10, 0xd9, 0x17, 0x59,
511        0x3b, 0x43, 0x4d, 0x52, 0x63, 0xca, 0xbe, 0x2b, 0x42, 0xf6, 0xb3, 0x67, 0xdf, 0x16, 0x83,
512        0x2f, 0x81,
513    ]));
514
515    /// Whether this asset is $DIG, however it was spelled on the wire.
516    pub fn is_dig(&self) -> bool {
517        *self == Self::DIG
518    }
519
520    /// The CAT asset id, or `None` for native XCH.
521    pub fn asset_id(&self) -> Option<&AssetId> {
522        match self {
523            Self::Xch => None,
524            Self::Cat(id) => Some(id),
525        }
526    }
527}
528
529impl Serialize for Asset {
530    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
531        match self {
532            Self::Xch => serializer.serialize_str(XCH_TOKEN),
533            // $DIG keeps its legacy token: a node built before the widening understands only the
534            // two bare strings, and emitting the tagged form for it would break that direction.
535            other if other.is_dig() => serializer.serialize_str(DIG_TOKEN),
536            Self::Cat(id) => {
537                use serde::ser::SerializeMap as _;
538                let mut map = serializer.serialize_map(Some(1))?;
539                map.serialize_entry("cat", &id.to_hex())?;
540                map.end()
541            }
542        }
543    }
544}
545
546impl<'de> Deserialize<'de> for Asset {
547    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
548        /// The two accepted wire shapes, kept private so the tagged form is the ONLY map that
549        /// parses — an unknown key must be an error, never a silently ignored asset name.
550        #[derive(Deserialize)]
551        #[serde(untagged, deny_unknown_fields)]
552        enum Wire {
553            Token(String),
554            Tagged { cat: String },
555        }
556
557        match Wire::deserialize(deserializer).map_err(|_| {
558            serde::de::Error::custom(
559                "expected \"xch\", \"dig\", or {\"cat\":\"<64-hex asset id>\"}",
560            )
561        })? {
562            Wire::Token(token) if token == XCH_TOKEN => Ok(Self::Xch),
563            Wire::Token(token) if token == DIG_TOKEN => Ok(Self::DIG),
564            Wire::Token(token) => Err(serde::de::Error::custom(format!(
565                "unknown asset {token:?}: expected \"xch\", \"dig\", or {{\"cat\":\"<64-hex asset id>\"}}"
566            ))),
567            Wire::Tagged { cat } => AssetId::from_hex(&cat)
568                .map(Self::Cat)
569                .map_err(serde::de::Error::custom),
570        }
571    }
572}
573
574/// `control.wallet.balance` params: which address + asset to read the balance of.
575///
576/// A READ over the loopback control plane — never a spend. Field names + the [`Asset`] wire form are
577/// byte-identical to dig-app's frozen `BalanceRequest`, so the node reads exactly what dig-app emits.
578#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
579pub struct WalletBalanceParams {
580    /// The `xch1…` address to read the balance of.
581    pub address: String,
582    /// The asset to read the balance for.
583    pub asset: Asset,
584}
585control_call!(WalletBalanceParams => ControlMethod::WalletBalance, results::WalletBalanceResult);
586
587/// `control.wallet.coins` params: which address + asset to read spendable coins for.
588///
589/// Field-for-field identical to [`WalletBalanceParams`] — a balance is this read reduced to a sum —
590/// and byte-identical to dig-app's frozen `CoinsRequest`, so adopting the method is a body swap
591/// rather than a re-shape.
592#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
593pub struct WalletCoinsParams {
594    /// The `xch1…` address to read coins for.
595    pub address: String,
596    /// The asset to read coins for.
597    pub asset: Asset,
598}
599control_call!(WalletCoinsParams => ControlMethod::WalletCoins, results::WalletCoinsResult);
600
601/// The length of a coin id in lowercase hex characters: a 32-byte hash.
602const COIN_ID_HEX_LEN: usize = 64;
603
604/// `control.wallet.coinById` params: WHICH coin, named by its own id.
605///
606/// # Why there is no `asset` here
607///
608/// A coin id names one coin on one chain. It is not scoped to an address and not scoped to an
609/// asset, and a node reading a coin record learns neither — so an asset parameter here could only
610/// be a claim the read never checks. The answer's
611/// [`asset`](crate::results::WalletCoinRecord::asset) is `null` for the same reason.
612///
613/// # Why the method exists at all
614///
615/// [`WalletCoinsParams`] answers by ADDRESS and lists UNSPENT coins only. A mint's evidence is the
616/// opposite shape: the created DID coin (which sits at nobody's wallet address) and the funding
617/// coin the mint SPENT (which is, by then, gone from every unspent list). Without a by-id read a
618/// pushed mint can never be observed — a permanent "pending" with the money already spent.
619#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
620pub struct WalletCoinByIdParams {
621    /// The coin id: lowercase 64-hex, unprefixed. A `0x` prefix is TOLERATED on input (block
622    /// explorers print one) and normalized away by [`Self::validated`]; it is never emitted.
623    pub coin_id: String,
624}
625control_call!(WalletCoinByIdParams => ControlMethod::WalletCoinById, results::WalletCoinByIdResult);
626
627/// `control.wallet.coinSpend` params: WHICH coin's spend to read, named by that coin's own id.
628///
629/// # Why the spend and the coin record are separate methods
630///
631/// [`WalletCoinByIdParams`] answers *what is this coin, and was it spent?* — an id, an amount, a
632/// puzzle HASH and two heights. None of that reveals what the spend DID. Reconstructing a lineage
633/// (which is how a dig-profile's DID singleton is followed forward) needs the puzzle REVEAL and the
634/// solution, and those exist only in the spend. A caller holding a coin record alone can see that a
635/// coin is gone and cannot see what it became.
636///
637/// # The id names the SPENT coin, not the spend
638///
639/// A spend has no id of its own on chain; it is identified by the coin it consumed. So the parameter
640/// is the same 64-hex coin id [`WalletCoinByIdParams`] takes, validated by the same rule, and the
641/// two methods are asked with the identical value.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
643pub struct WalletCoinSpendParams {
644    /// The SPENT coin's id: lowercase 64-hex, unprefixed. A `0x` prefix is TOLERATED on input and
645    /// normalized away by [`Self::validated`]; it is never emitted.
646    pub coin_id: String,
647}
648control_call!(WalletCoinSpendParams => ControlMethod::WalletCoinSpend, results::WalletCoinSpendResult);
649
650/// `control.wallet.coinsByParent` params: WHICH coin's direct children to read.
651///
652/// # One hop, and the field name says so
653///
654/// The field is `parent_coin_id` rather than `coin_id` because the coin named here is the one being
655/// asked ABOUT as a parent — it is never the coin the caller wants back. A walk up or down a lineage
656/// is the CALLER's composition of repeated single hops; the node performs exactly one. Naming it
657/// `coin_id` would make a recursive reading of the method plausible from the request alone, and a
658/// caller expecting a whole lineage from one call would read a one-hop answer as a truncated chain.
659///
660/// # Bounded, because a parent's child count is not
661///
662/// This is the only OPEN wallet read whose answer has unbounded cardinality — every other one
663/// returns a single record (`coinById`, `peak`, `syncStatus`) or is already paged (`arrivals`). So
664/// the read is PAGED, and the page is bounded by [`COINS_BY_PARENT_MAX_LIMIT`].
665///
666/// **The bound is the ONLY thing bounding this call — there is no rate limiter anywhere behind it.**
667/// dig-node's control plane has no request rate limiting of any kind (dig_ecosystem#2577); the
668/// bandwidth limiter it does have governs content serving and is not on this path. A future reader
669/// weighing whether to relax this cap should assume no limiter exists, because none does.
670///
671/// That matters more than a local resource bound would, because the node does not necessarily answer
672/// from its own replica: on the fallback tier it forwards a caller-supplied identifier to a
673/// THIRD-PARTY coinset HTTPS oracle. An unbounded page is therefore unbounded work against somebody
674/// else's service, requested by a token-less caller on a loopback endpoint.
675///
676/// Paging rather than a bare cap, because a bare cap is a dead end: a parent with more children than
677/// the cap could never be fully enumerated, and this method exists to WALK a lineage. A walk that
678/// cannot see past the cap is a walk that silently stops.
679#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
680pub struct WalletCoinsByParentParams {
681    /// The PARENT coin's id: lowercase 64-hex, unprefixed. A `0x` prefix is TOLERATED on input and
682    /// normalized away by [`Self::validated`]; it is never emitted.
683    pub parent_coin_id: String,
684    /// Resume STRICTLY AFTER this child, in the read's
685    /// [documented order](results::WalletCoinsByParentResult). `None` starts at the first child.
686    ///
687    /// This is the value the previous page handed back as
688    /// [`cursor`](results::WalletCoinsByParentResult::cursor) — never a value the caller invented,
689    /// and never a marker for where the chain "got to". `control.wallet.arrivals` records why that
690    /// distinction loses rows; this read avoids the trap by having no such marker to reach for.
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub after_coin_id: Option<String>,
693    /// The page size. `None` asks for [`COINS_BY_PARENT_DEFAULT_LIMIT`].
694    ///
695    /// A value above [`COINS_BY_PARENT_MAX_LIMIT`], or a zero, is REFUSED as `INVALID_PARAMS` rather
696    /// than clamped — see [`Self::validated`].
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    pub limit: Option<u32>,
699}
700control_call!(WalletCoinsByParentParams => ControlMethod::WalletCoinsByParent, results::WalletCoinsByParentResult);
701
702/// `control.wallet.arrivals` — confirmed INCOMING funds recorded since a cursor position.
703///
704/// The answer to "was I just paid?", which neither a balance nor a coin list can give: a balance
705/// moves for the user's OWN change too, and an unspent-coin list cannot say which of its coins are
706/// new. Each row the node returns is a coin it determined ARRIVED — confirmed on chain, above the
707/// wallet's arrival baseline, not previously reported, and not created by spending one of the
708/// wallet's own coins. The determination is the NODE's; a client MUST NOT re-derive it, because the
709/// signals it takes (spent parents, the catch-up baseline) live only in the node's replica.
710///
711/// # A cursor, not a stream
712///
713/// The control envelope is strictly request→response, so this is polled. A client resumes from
714/// [`WalletArrivalsResult::cursor`](results::WalletArrivalsResult::cursor) — the last position it
715/// was actually handed — and NEVER from `latest`; see that field for why the distinction loses a
716/// notification when it is collapsed.
717///
718/// # `after_seq` is unsigned so a rewind is unexpressible
719///
720/// Positions are monotonic and start at 1, so there is no meaning for a negative one. `0` is the
721/// beginning of the ledger and is what a client sends when it deliberately wants everything.
722#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
723pub struct WalletArrivalsParams {
724    /// Return arrivals STRICTLY after this position. `0` starts at the beginning of the ledger,
725    /// and is also what an omitted field means — the same default the node applies.
726    #[serde(default)]
727    pub after_seq: u64,
728    /// The page size. `None` asks for the node's default rather than a number this client invented;
729    /// a node clamps whatever it is given to its own maximum.
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub limit: Option<u32>,
732}
733control_call!(WalletArrivalsParams => ControlMethod::WalletArrivals, results::WalletArrivalsResult);
734
735fn normalize_coin_id(coin_id: &str) -> Option<&str> {
736    let normalized = coin_id.strip_prefix("0x").unwrap_or(coin_id);
737    let well_formed = normalized.len() == COIN_ID_HEX_LEN
738        && normalized
739            .bytes()
740            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
741    well_formed.then_some(normalized)
742}
743
744/// Give a single-coin-id params type its validating `Deserialize` and its `validated` constructor.
745///
746/// The three by-coin reads (`coinById`, `coinSpend`, `coinsByParent`) enforce the IDENTICAL id rule
747/// under three different field names, and the rule is normative rather than incidental — see
748/// [`WalletCoinByIdParams::validated`] for why a malformed id must be refused BEFORE a chain is
749/// consulted. Written once here so a fourth by-coin read cannot arrive with a subtly looser copy of
750/// it, and so a change to the rule cannot land on two of three types.
751macro_rules! coin_id_params {
752    ($ty:ident, $field:ident, $raw:ident, $error:expr) => {
753        impl<'de> Deserialize<'de> for $ty {
754            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
755            where
756                D: serde::Deserializer<'de>,
757            {
758                #[derive(Deserialize)]
759                struct $raw {
760                    $field: String,
761                }
762
763                let raw = $raw::deserialize(deserializer)?;
764                let $field = normalize_coin_id(&raw.$field)
765                    .ok_or_else(|| serde::de::Error::custom($error))?
766                    .to_owned();
767                Ok(Self { $field })
768            }
769        }
770
771        impl $ty {
772            /// Normalize and check the coin id, or reject the request as `-32602 INVALID_PARAMS`.
773            ///
774            /// A malformed id is a malformed REQUEST, and the node refuses it here — before
775            /// consulting any chain. That ordering is normative rather than an optimisation: were a
776            /// bad id allowed through, the read would come back empty, and the caller would be told
777            /// the honest-looking answer *the chain holds nothing* about a coin it never actually
778            /// asked after. An unanswerable question and a chain that answered "no" must never wear
779            /// the same shape.
780            ///
781            /// Accepts exactly two spellings — 64 lowercase hex characters, or the same 64 preceded
782            /// by `0x`. Uppercase, whitespace and every other length are refused, because the
783            /// contract's hex wire form is lowercase and unprefixed everywhere else in this crate.
784            pub fn validated(self) -> Result<Self, crate::error::ControlError> {
785                let normalized = normalize_coin_id(&self.$field).ok_or_else(|| {
786                    crate::error::ControlError::of(
787                        crate::error::ControlErrorCode::InvalidParams,
788                        $error,
789                    )
790                })?;
791                Ok($ty {
792                    $field: normalized.to_owned(),
793                })
794            }
795        }
796    };
797}
798
799const COIN_ID_ERROR: &str = "coin_id must be lowercase 64-hex, optionally 0x-prefixed";
800const PARENT_COIN_ID_ERROR: &str =
801    "parent_coin_id must be lowercase 64-hex, optionally 0x-prefixed";
802const AFTER_COIN_ID_ERROR: &str = "after_coin_id must be lowercase 64-hex, optionally 0x-prefixed";
803
804coin_id_params!(
805    WalletCoinByIdParams,
806    coin_id,
807    RawWalletCoinByIdParams,
808    COIN_ID_ERROR
809);
810coin_id_params!(
811    WalletCoinSpendParams,
812    coin_id,
813    RawWalletCoinSpendParams,
814    COIN_ID_ERROR
815);
816/// The page size `control.wallet.coinsByParent` uses when the caller names none.
817///
818/// A spend in the lineages this read exists to follow — a singleton, a DID, an ordinary transfer —
819/// creates a small handful of children, so one default page covers a realistic hop in a single round
820/// trip and a caller never pages at all.
821pub const COINS_BY_PARENT_DEFAULT_LIMIT: u32 = 100;
822
823/// The largest page `control.wallet.coinsByParent` will accept, derived from the transport's own
824/// frame limit rather than chosen for feel.
825///
826/// dig-ipc-protocol caps a control frame at `MAX_FRAME_BYTES` = 1 MiB (its `SPEC.md` §
827/// bounds), and that is the hard ceiling every answer on this plane has to fit inside. A
828/// [`WalletCoinRecord`](results::WalletCoinRecord) is at most ~350 bytes of JSON — three 64-hex
829/// hashes at 66 bytes quoted, a 20-digit `u64`, two 10-digit heights, and their keys — so the
830/// arithmetic that fixes this number is:
831///
832/// ```text
833/// 1 MiB / 350 B  ~=  2,996 records is where a page STOPS FITTING
834/// 1,000 records  ~=  350 KB, roughly a third of the frame
835/// ```
836///
837/// The cap is set at a third of what fits, not at what fits, so the envelope, the freshness fields
838/// and any future additive member cannot push a legal page over the transport's limit. A larger
839/// value would put the contract's own maximum inside the region where a conforming node's honest
840/// answer is undeliverable — the failure would surface as a truncated frame, not as a refusal.
841pub const COINS_BY_PARENT_MAX_LIMIT: u32 = 1_000;
842
843const COINS_BY_PARENT_LIMIT_ERROR: &str = "limit must be between 1 and 1000";
844
845impl<'de> Deserialize<'de> for WalletCoinsByParentParams {
846    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
847    where
848        D: serde::Deserializer<'de>,
849    {
850        #[derive(Deserialize)]
851        struct RawWalletCoinsByParentParams {
852            parent_coin_id: String,
853            #[serde(default)]
854            after_coin_id: Option<String>,
855            #[serde(default)]
856            limit: Option<u32>,
857        }
858
859        let raw = RawWalletCoinsByParentParams::deserialize(deserializer)?;
860        let parent_coin_id = normalize_coin_id(&raw.parent_coin_id)
861            .ok_or_else(|| serde::de::Error::custom(PARENT_COIN_ID_ERROR))?
862            .to_owned();
863        let after_coin_id = raw
864            .after_coin_id
865            .map(|id| {
866                normalize_coin_id(&id)
867                    .map(str::to_owned)
868                    .ok_or_else(|| serde::de::Error::custom(AFTER_COIN_ID_ERROR))
869            })
870            .transpose()?;
871        if !raw.limit.map_or(true, is_legal_page) {
872            return Err(serde::de::Error::custom(COINS_BY_PARENT_LIMIT_ERROR));
873        }
874        Ok(Self {
875            parent_coin_id,
876            after_coin_id,
877            limit: raw.limit,
878        })
879    }
880}
881
882/// Is this a page size the contract accepts — at least one row, at most the frame-derived maximum?
883fn is_legal_page(limit: u32) -> bool {
884    (1..=COINS_BY_PARENT_MAX_LIMIT).contains(&limit)
885}
886
887impl WalletCoinsByParentParams {
888    /// A first page of children for one parent: the node's default size, starting at the beginning.
889    ///
890    /// The common case, and the one a caller should not have to spell out — naming a page size means
891    /// asserting a number this caller invented over the one the contract chose.
892    pub fn first_page(parent_coin_id: impl Into<String>) -> Self {
893        Self {
894            parent_coin_id: parent_coin_id.into(),
895            after_coin_id: None,
896            limit: None,
897        }
898    }
899
900    /// The page size this request asks for, resolving `None` to [`COINS_BY_PARENT_DEFAULT_LIMIT`].
901    ///
902    /// Stated once here so a node and a client cannot resolve the same omitted field to two
903    /// different numbers — a disagreement that would show up as a page boundary in the wrong place,
904    /// which is exactly where a paged walk loses rows.
905    pub fn effective_limit(&self) -> u32 {
906        self.limit.unwrap_or(COINS_BY_PARENT_DEFAULT_LIMIT)
907    }
908
909    /// Normalize and check both ids and the page bound, or reject as `-32602 INVALID_PARAMS`.
910    ///
911    /// The ids follow the rule every by-coin read in this crate follows (lowercase 64-hex, `0x`
912    /// tolerated on input and never emitted).
913    ///
914    /// An out-of-range `limit` is REFUSED, never clamped. That is a deliberate departure from
915    /// `control.wallet.arrivals`, which lets a node clamp: this read's page boundary is what a
916    /// caller RESUMES from, so a silently shrunk page hands back a cursor for a position the caller
917    /// did not ask about, and a caller that believed its own number would mis-size every subsequent
918    /// request. Refusing keeps the caller's model of the page and the node's identical, which is the
919    /// same reason a 65-hex coin id is refused rather than truncated.
920    ///
921    /// `limit: 0` is refused for a separate reason: a page that can hold nothing makes no progress,
922    /// so a caller looping until a page comes back short would loop forever.
923    pub fn validated(self) -> Result<Self, crate::error::ControlError> {
924        fn invalid(message: &'static str) -> crate::error::ControlError {
925            crate::error::ControlError::of(crate::error::ControlErrorCode::InvalidParams, message)
926        }
927
928        let parent_coin_id = normalize_coin_id(&self.parent_coin_id)
929            .ok_or_else(|| invalid(PARENT_COIN_ID_ERROR))?
930            .to_owned();
931        let after_coin_id = self
932            .after_coin_id
933            .as_deref()
934            .map(|id| {
935                normalize_coin_id(id)
936                    .map(str::to_owned)
937                    .ok_or_else(|| invalid(AFTER_COIN_ID_ERROR))
938            })
939            .transpose()?;
940        if !self.limit.map_or(true, is_legal_page) {
941            return Err(invalid(COINS_BY_PARENT_LIMIT_ERROR));
942        }
943        Ok(WalletCoinsByParentParams {
944            parent_coin_id,
945            after_coin_id,
946            limit: self.limit,
947        })
948    }
949}
950
951/// `control.wallet.peak` params — none.
952///
953/// The peak is a property of the node's chain view, not of any address, which is exactly why it is
954/// its own method: [`results::WalletBalanceResult::peak_height`] is `null` on every fallback-tier
955/// answer, so a caller bounding a claimed confirmation cannot rely on getting one from a balance.
956#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
957pub struct WalletPeakParams {}
958control_call!(WalletPeakParams => ControlMethod::WalletPeak, results::WalletPeakResult);
959
960/// `control.peerCounts` params — none.
961///
962/// The counts describe this node's own connectivity on each network, so there is nothing to scope
963/// the question by. One call answers for BOTH networks deliberately: a consumer that had to collect
964/// the DIG count from a peer method and the Chia count from a wallet method is a consumer that can
965/// reach for the wrong one.
966#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
967pub struct PeerCountsParams {}
968control_call!(PeerCountsParams => ControlMethod::PeerCounts, results::PeerCountsResult);
969
970/// `control.wallet.syncStatus` params — none.
971///
972/// The wallet's sync progress is a property of the node's own chain replica, not of any address, so
973/// there is nothing to scope the question by. Deliberately NOT confused with `control.sync.status`,
974/// which reports §21 DIG STORE sync and has nothing to do with the chain.
975#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
976pub struct WalletSyncStatusParams {}
977control_call!(WalletSyncStatusParams => ControlMethod::WalletSyncStatus, results::WalletSyncStatusResult);
978
979/// `control.wallet.broadcast` params: an ALREADY-SIGNED spend bundle to push.
980///
981/// # The custody boundary (§908)
982///
983/// This carries signed bytes and nothing else. There is deliberately no key, no seed, no phrase and
984/// no unsigned-spend-plus-key field here, and there never may be: the node's role on the money path
985/// is to read chain state and to push what somebody else signed. A parameter that let the node
986/// produce a signature would move custody into an identity-agnostic daemon, which is the one thing
987/// the boundary exists to prevent.
988#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
989pub struct WalletBroadcastParams {
990    /// The signed spend bundle: lowercase hex of its chia `Streamable` serialization.
991    pub signed_bundle_hex: String,
992}
993control_call!(WalletBroadcastParams => ControlMethod::WalletBroadcast, results::WalletBroadcastResult);
994
995/// The length of a BLS G1 public key in lowercase hex characters: 48 bytes.
996const PUBLIC_KEY_HEX_LEN: usize = 96;
997
998/// `control.wallet.watch` params: which PUBLIC keys the node should follow.
999///
1000/// # Keys, never puzzle hashes
1001///
1002/// The node already derives addresses from the public keys it holds in its own custody, through one
1003/// standard derivation. Enrolling KEYS reuses that exact derivation for a client's keys too, so the
1004/// ecosystem has ONE mapping from key to address and a client and a node can never disagree about
1005/// which addresses a key covers. Enrolling puzzle hashes instead would make every client re-derive
1006/// independently, and a client whose derivation window is narrower than the node's would silently
1007/// under-report the money it owns.
1008///
1009/// # No key material crosses (§908)
1010///
1011/// A G1 public key is public. There is deliberately no seed, phrase, private key or signature field
1012/// here, and there never may be: enrolment tells the node what to WATCH, and watching needs nothing
1013/// a signature could be produced from.
1014///
1015/// # Idempotent, so a client can reconcile without asking first
1016///
1017/// Submitting keys the node already follows is a SUCCESS that changes nothing — see
1018/// [`WalletWatchResult`](results::WalletWatchResult). Duplicates WITHIN one request count once. An
1019/// empty list is accepted and does nothing, because "enrol everything in this (currently empty) set"
1020/// is a reconciliation a client legitimately performs.
1021#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1022pub struct WalletWatchParams {
1023    /// The public keys to enrol: lowercase 96-hex, unprefixed. A `0x` prefix is TOLERATED on input
1024    /// and normalized away by [`Self::validated`]; it is never emitted.
1025    pub public_keys: Vec<String>,
1026}
1027control_call!(WalletWatchParams => ControlMethod::WalletWatch, results::WalletWatchResult);
1028
1029/// `control.wallet.unwatch` params: which PUBLIC keys the node should stop following.
1030///
1031/// Takes the same wire form as [`WalletWatchParams`] under the same field name, so a client
1032/// reverses an enrolment by re-sending exactly what it sent. Deregistering a key that was never
1033/// enrolled is a success, not an error — the mirror of enrolment's idempotence, and what lets a
1034/// client assert an end state rather than compute a diff.
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1036pub struct WalletUnwatchParams {
1037    /// The public keys to deregister: lowercase 96-hex, unprefixed. A `0x` prefix is TOLERATED on
1038    /// input and normalized away by [`Self::validated`]; it is never emitted.
1039    pub public_keys: Vec<String>,
1040}
1041control_call!(WalletUnwatchParams => ControlMethod::WalletUnwatch, results::WalletUnwatchResult);
1042
1043/// `control.wallet.watched` params — none.
1044///
1045/// The enrolled set is a property of the node, so there is nothing to scope the question by. This
1046/// is why the method is TOKEN-GATED although it only reads: the caller supplies nothing, so the
1047/// answer is the node's OWN key set — see [`ControlMethod::is_open_read`].
1048#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1049pub struct WalletWatchedParams {}
1050control_call!(WalletWatchedParams => ControlMethod::WalletWatched, results::WalletWatchedResult);
1051
1052fn normalize_public_key(public_key: &str) -> Option<&str> {
1053    let normalized = public_key.strip_prefix("0x").unwrap_or(public_key);
1054    let well_formed = normalized.len() == PUBLIC_KEY_HEX_LEN
1055        && normalized
1056            .bytes()
1057            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
1058    well_formed.then_some(normalized)
1059}
1060
1061/// Give an enrolment params type its validating `Deserialize` and its `validated` constructor.
1062///
1063/// `watch` and `unwatch` carry the IDENTICAL key list under the identical field name, and must
1064/// enforce the identical rule: a client reverses an enrolment by re-sending what it sent, so a
1065/// spelling one method accepts and the other refuses would leave a key enrolled forever. Written
1066/// once so the two cannot drift apart.
1067macro_rules! public_keys_params {
1068    ($ty:ident, $raw:ident, $error:expr) => {
1069        impl<'de> Deserialize<'de> for $ty {
1070            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1071            where
1072                D: serde::Deserializer<'de>,
1073            {
1074                #[derive(Deserialize)]
1075                struct $raw {
1076                    public_keys: Vec<String>,
1077                }
1078
1079                let raw = $raw::deserialize(deserializer)?;
1080                let public_keys = raw
1081                    .public_keys
1082                    .iter()
1083                    .map(|key| {
1084                        normalize_public_key(key)
1085                            .map(str::to_owned)
1086                            .ok_or_else(|| serde::de::Error::custom($error))
1087                    })
1088                    .collect::<Result<Vec<_>, _>>()?;
1089                Ok(Self { public_keys })
1090            }
1091        }
1092
1093        impl $ty {
1094            /// Normalize and check every key, or reject the request as `-32602 INVALID_PARAMS`.
1095            ///
1096            /// The whole request is refused when ANY key is malformed — never the well-formed
1097            /// subset. A partial enrolment would leave the node following fewer addresses than the
1098            /// client believes it asked for, and the client's next balance read would report a
1099            /// shortfall as though the money were not there. One bad key is a malformed REQUEST.
1100            ///
1101            /// Accepts exactly two spellings per key — 96 lowercase hex characters, or the same 96
1102            /// preceded by `0x`. Uppercase, whitespace and every other length are refused, because
1103            /// the contract's hex wire form is lowercase and unprefixed everywhere else.
1104            pub fn validated(self) -> Result<Self, crate::error::ControlError> {
1105                let public_keys = self
1106                    .public_keys
1107                    .iter()
1108                    .map(|key| {
1109                        normalize_public_key(key).map(str::to_owned).ok_or_else(|| {
1110                            crate::error::ControlError::of(
1111                                crate::error::ControlErrorCode::InvalidParams,
1112                                $error,
1113                            )
1114                        })
1115                    })
1116                    .collect::<Result<Vec<_>, _>>()?;
1117                Ok(Self { public_keys })
1118            }
1119        }
1120    };
1121}
1122
1123const PUBLIC_KEYS_ERROR: &str =
1124    "public_keys must each be lowercase 96-hex (a 48-byte G1 key), optionally 0x-prefixed";
1125
1126public_keys_params!(WalletWatchParams, RawWalletWatch, PUBLIC_KEYS_ERROR);
1127public_keys_params!(WalletUnwatchParams, RawWalletUnwatch, PUBLIC_KEYS_ERROR);
1128
1129/// Every id in a reservation's `coin_ids` takes the same wire form the single-coin reads accept,
1130/// so a client can feed a coin straight from `control.wallet.coins` into a reservation.
1131const COIN_IDS_ERROR: &str =
1132    "coin_ids must each be lowercase 64-hex (a 32-byte coin id), optionally 0x-prefixed";
1133
1134/// `control.wallet.reservations.held` params — none.
1135///
1136/// # Why the caller does not supply the time
1137///
1138/// dig-account's `CoinReservationStore::held(now_unix)` takes the current time from its caller,
1139/// because in-process both sides share one clock and one trust domain. Across the control boundary
1140/// they share neither, and a caller-supplied `now` would be a lapse oracle: a far-future value makes
1141/// every live reservation read as expired, and the caller then selects coins another process is
1142/// about to spend. The node reads its OWN clock and reports it back as
1143/// [`as_of_unix`](results::WalletReservationsHeldResult::as_of_unix), so a client can SEE skew
1144/// rather than impose it.
1145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1146pub struct WalletReservationsHeldParams {}
1147control_call!(WalletReservationsHeldParams => ControlMethod::WalletReservationsHeld, results::WalletReservationsHeldResult);
1148
1149/// `control.wallet.reservations.reserve` params: take EVERY named coin, or take none.
1150///
1151/// The wire form of `dig_account::wallet::reservation::CoinReservationStore::reserve_all`, so a
1152/// client backing that seam with the node forwards its arguments rather than translating them.
1153///
1154/// # All-or-none is the whole contract
1155///
1156/// Reading the held set, selecting, then reserving is check-then-act: two processes both read an
1157/// empty set and both take the same coin. Atomic acquisition is what closes that window, so a
1158/// conflict on ANY coin refuses the WHOLE call and reserves nothing — see
1159/// [`ControlErrorCode::WalletCoinsReserved`]. A caller that loses re-reads
1160/// [`WalletReservationsHeldParams`] and re-selects from what remains.
1161///
1162/// # An empty list is a success, not an error
1163///
1164/// It yields a handle that releases nothing, which is what the caller asked for. This matches
1165/// dig-account exactly: an empty reservation can never conflict, so refusing it would make a
1166/// legitimate no-op selection look like a malformed request.
1167///
1168/// # No key material (§908)
1169///
1170/// A coin id is a public chain fact. There is no seed, key, signature or bundle field here and
1171/// there never may be: a reservation is BOOKKEEPING — it narrows what a selector will choose and
1172/// authorizes nothing.
1173#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1174pub struct WalletReservationsReserveParams {
1175    /// The coin ids to hold: lowercase 64-hex, unprefixed. A `0x` prefix is TOLERATED on input and
1176    /// normalized away by [`Self::validated`]; it is never emitted.
1177    pub coin_ids: Vec<String>,
1178    /// How long the hold should live, in seconds; `None` asks for the node's default.
1179    ///
1180    /// A REQUEST, never a command. The node clamps this to its own maximum and returns the value it
1181    /// actually applied as
1182    /// [`ttl_secs`](results::WalletReservationsReserveResult::ttl_secs) — an unclamped caller-chosen
1183    /// lifetime is a lockout weapon, since one call could hold a wallet's coins away from its owner
1184    /// for as long as it liked.
1185    #[serde(skip_serializing_if = "Option::is_none")]
1186    pub ttl_secs: Option<u64>,
1187}
1188control_call!(WalletReservationsReserveParams => ControlMethod::WalletReservationsReserve, results::WalletReservationsReserveResult);
1189
1190/// `control.wallet.reservations.release` params: free one reservation now, ahead of its TTL.
1191///
1192/// # The release path is why a reservation is safe at all
1193///
1194/// A hold with no way out is a wallet that locks itself out of its own funds, which is worse than
1195/// the double-select it prevents. Two mechanisms keep that impossible and BOTH are required: the
1196/// TTL bounds every hold whether or not anyone releases it, and this method lets a caller that
1197/// KNOWS the answer — the spend settled, or was definitively rejected — stop holding the user's
1198/// coins over a question the chain has already resolved.
1199///
1200/// # Releasing an unknown or lapsed id is a SUCCESS
1201///
1202/// A caller releasing on confirmation cannot know whether the TTL got there first, and making that
1203/// race an error would teach callers to ignore the result — which is how a release stops being
1204/// called at all. See [`WalletReservationsReleaseResult`](results::WalletReservationsReleaseResult).
1205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1206pub struct WalletReservationsReleaseParams {
1207    /// The handle returned by
1208    /// [`reserve`](results::WalletReservationsReserveResult::reservation_id).
1209    ///
1210    /// OPAQUE: a client stores it and sends it back, and MUST NOT parse, derive or construct one.
1211    /// The node mints it, and how it is spelled is free to differ between a hold taken before a
1212    /// broadcast and one recorded for a bundle already in flight.
1213    pub reservation_id: String,
1214}
1215control_call!(WalletReservationsReleaseParams => ControlMethod::WalletReservationsRelease, results::WalletReservationsReleaseResult);
1216
1217impl<'de> Deserialize<'de> for WalletReservationsReserveParams {
1218    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1219    where
1220        D: serde::Deserializer<'de>,
1221    {
1222        #[derive(Deserialize)]
1223        struct RawReserve {
1224            coin_ids: Vec<String>,
1225            #[serde(default)]
1226            ttl_secs: Option<u64>,
1227        }
1228
1229        let raw = RawReserve::deserialize(deserializer)?;
1230        let coin_ids = raw
1231            .coin_ids
1232            .iter()
1233            .map(|id| {
1234                normalize_coin_id(id)
1235                    .map(str::to_owned)
1236                    .ok_or_else(|| serde::de::Error::custom(COIN_IDS_ERROR))
1237            })
1238            .collect::<Result<Vec<_>, _>>()?;
1239        Ok(Self {
1240            coin_ids,
1241            ttl_secs: raw.ttl_secs,
1242        })
1243    }
1244}
1245
1246impl WalletReservationsReserveParams {
1247    /// Normalize and check every coin id, or reject the request as `-32602 INVALID_PARAMS`.
1248    ///
1249    /// The WHOLE request is refused when any id is malformed, never the well-formed subset. A
1250    /// partial reservation would leave the caller believing it holds inputs it does not — the exact
1251    /// state all-or-none acquisition exists to make unreachable.
1252    pub fn validated(self) -> Result<Self, ControlError> {
1253        let coin_ids = self
1254            .coin_ids
1255            .iter()
1256            .map(|id| {
1257                normalize_coin_id(id).map(str::to_owned).ok_or_else(|| {
1258                    ControlError::of(ControlErrorCode::InvalidParams, COIN_IDS_ERROR)
1259                })
1260            })
1261            .collect::<Result<Vec<_>, _>>()?;
1262        Ok(Self {
1263            coin_ids,
1264            ttl_secs: self.ttl_secs,
1265        })
1266    }
1267}
1268
1269/// `pairing.request` params (OPEN — no token).
1270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1271pub struct RequestParams {
1272    /// A human-readable name for the requesting client (shown to the operator).
1273    pub client_name: String,
1274}
1275control_call!(RequestParams => ControlMethod::PairingRequest, results::PairingRequestResult);
1276
1277/// `pairing.poll` params (OPEN — no token).
1278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1279pub struct PollParams {
1280    /// The pairing id to poll.
1281    pub pairing_id: String,
1282}
1283control_call!(PollParams => ControlMethod::PairingPoll, results::PairingPollResult);
1284
1285/// The largest dig-profile body the control plane accepts or returns, in bytes: **4 MiB**.
1286///
1287/// # Why the contract carries the cap instead of the implementation
1288///
1289/// A client that learns the bound by exceeding it learns it as a failed round trip, after paying to
1290/// serialize and send megabytes. Stated here, an app checks before it sends and can tell a person
1291/// *this profile is too large* rather than *something went wrong*.
1292///
1293/// # Why this number
1294///
1295/// It is HALF of dig-gossip's `WS_MAX_MESSAGE_BYTES` (8 MiB), the frame ceiling a body must fit
1296/// inside when a node serves it to a peer over `PROFILE_BODY` (opcode 225). A body accepted here
1297/// but unservable there would be stored and then permanently unsyncable — accepted by the node the
1298/// app talks to and invisible to every other node. The halving leaves room for the framing,
1299/// envelope and base64 expansion that sit around the bytes on that hop.
1300///
1301/// The cap is on the DECODED body, not on the base64 text that carries it.
1302pub const MAX_BODY_BYTES: usize = 4 * 1024 * 1024;
1303
1304/// `control.profile.putBody` params: the profile body a confirmed chain root commits to.
1305///
1306/// # The node CHECKS the root; it does not take the caller's word for it
1307///
1308/// `root` is a CLAIM, and the node's obligation is to refuse it when it is false. An implementation
1309/// MUST independently resolve the profile's root on chain, recompute the root of the supplied body,
1310/// and reject the call unless the two agree and that root is CONFIRMED. dig-app is a caller like
1311/// any other here: it holds the key and signs the root (§908), but the bytes it then hands over
1312/// arrive at the node exactly as a peer's bytes do, and the standing rule for this epic is that a
1313/// body is checked against the on-chain root and anything that does not match is rejected.
1314///
1315/// A method documented as *the caller supplies a matching root* invites an implementation that
1316/// stores what it is given. That implementation turns the control plane into a way to make a node
1317/// serve arbitrary bytes to the network under someone else's profile id.
1318///
1319/// # No key material crosses (§908)
1320///
1321/// There is deliberately no seed, private key, signature or unsigned spend field here, and there
1322/// never may be. The node persists, serves and fetches bodies; it never signs.
1323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1324pub struct ProfilePutBodyParams {
1325    /// The profile's store id: lowercase 64-hex, unprefixed.
1326    pub store_id: String,
1327    /// The root the body is claimed to hash to: lowercase 64-hex, unprefixed. Checked against the
1328    /// chain, never trusted.
1329    pub root: String,
1330    /// The body itself, standard base64 (padded) of its `DPB` serialization. The DECODED length
1331    /// MUST NOT exceed [`MAX_BODY_BYTES`]; a larger body is refused as `INVALID_PARAMS`.
1332    pub body_b64: String,
1333}
1334control_call!(ProfilePutBodyParams => ControlMethod::ProfilePutBody, results::ProfilePutBodyResult);
1335
1336/// `control.profile.getBody` params: WHICH profile body to read, named by store id + root.
1337///
1338/// The root is part of the question rather than part of the answer: a caller asks for the body at a
1339/// root it already knows, so it can never be handed a body for a DIFFERENT root and mistake it for
1340/// the one it asked about. A node holding no body at that root answers `body_b64: null`.
1341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1342pub struct ProfileGetBodyParams {
1343    /// The profile's store id: lowercase 64-hex, unprefixed.
1344    pub store_id: String,
1345    /// The root to read the body at: lowercase 64-hex, unprefixed.
1346    pub root: String,
1347}
1348control_call!(ProfileGetBodyParams => ControlMethod::ProfileGetBody, results::ProfileGetBodyResult);
1349
1350/// The page size `control.spends.list` uses when the caller names none.
1351///
1352/// Stated on the contract rather than chosen by each side, so a node and a client cannot resolve the
1353/// same omitted field to two different numbers — a disagreement that shows up as a page boundary in
1354/// the wrong place, which is where a paged walk loses rows.
1355pub const SPENDS_LIST_DEFAULT_LIMIT: u32 = 50;
1356
1357/// The largest page `control.spends.list` will serve.
1358///
1359/// The audit record grows without limit — it is append-only and every automated cycle adds to it —
1360/// so an unbounded read is unbounded work and an unbounded response. The bound is declared here from
1361/// the start rather than added later, because a method that ships unbounded teaches every client to
1362/// expect the whole record in one call, and bounding it afterwards is then a breaking change.
1363///
1364/// **This bound is the only thing bounding the call.** dig-node's control plane has no request rate
1365/// limiting of any kind (dig_ecosystem#2577), so a future reader weighing a larger cap should assume
1366/// no limiter exists behind it, because none does.
1367pub const SPENDS_LIST_MAX_LIMIT: u32 = 500;
1368
1369/// The one refusal message for an out-of-range `control.spends.list` page size.
1370const SPENDS_LIST_LIMIT_ERROR: &str = "limit must be between 1 and 500 spends per page";
1371
1372/// `control.spends.list` params: WHICH automated spends to read, and how much of the record at once.
1373///
1374/// # A read, and only a read
1375///
1376/// Nothing here initiates, signs, cancels or amends a spend, and the catalog offers no method that
1377/// does. The record exists to make automatic signing accountable, and a surface able to edit it
1378/// would be a surface able to edit the evidence.
1379///
1380/// # Every filter is an AND; an unset filter constrains nothing
1381///
1382/// Omitting a field means "do not narrow on this", never "match nothing". A client that sends no
1383/// field at all asks for the newest page of the whole record.
1384///
1385/// # Paged, and the page boundary is the caller's
1386///
1387/// Rows come newest-initiated first (the full ordering rule is on
1388/// [`SpendsListResult`](results::SpendsListResult)) and a caller resumes from
1389/// [`after_id`](Self::after_id) — the id of the last row it was actually HANDED. An out-of-range
1390/// [`limit`](Self::limit) is REFUSED rather than clamped, matching
1391/// [`WalletCoinsByParentParams`] and for the same reason: a silently shrunk page hands back a cursor
1392/// for a position the caller did not ask about.
1393#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
1394pub struct SpendsListParams {
1395    /// Only spends INITIATED at or after this unix-ms instant. Inclusive.
1396    #[serde(default, skip_serializing_if = "Option::is_none")]
1397    pub since_ms: Option<u64>,
1398    /// Only spends INITIATED strictly before this unix-ms instant. Exclusive.
1399    ///
1400    /// Half-open with [`since_ms`](Self::since_ms) so consecutive windows tile the record exactly:
1401    /// one window's `until_ms` is the next window's `since_ms`, and no spend is counted twice or
1402    /// dropped between them.
1403    #[serde(default, skip_serializing_if = "Option::is_none")]
1404    pub until_ms: Option<u64>,
1405    /// Only spends serving this store id.
1406    #[serde(default, skip_serializing_if = "Option::is_none")]
1407    pub store_id: Option<String>,
1408    /// Only this kind of spend — the stable token the producer stamped (`"mirror-coin"`, …).
1409    ///
1410    /// An open string rather than an enum, because a new producer must be able to appear in the
1411    /// record without a release of this crate. An unrecognised kind matches nothing rather than
1412    /// erroring, which is the same answer a caller gets for a real kind that has no rows yet.
1413    #[serde(default, skip_serializing_if = "Option::is_none")]
1414    pub kind: Option<String>,
1415    /// Only this outcome, by its [`SpendOutcome::token`](results::SpendOutcome::token) —
1416    /// `pending` / `submitted` / `confirmed` / `failed` / `unresolved`.
1417    ///
1418    /// **`failed` does NOT mean "the money stayed put"**, so a client filtering on it must still
1419    /// read each row's stage — see [`SpendOutcome::Failed`](results::SpendOutcome::Failed). A UI
1420    /// that offers a "failed" filter and renders its rows as untouched money asserts something the
1421    /// node does not know.
1422    #[serde(default, skip_serializing_if = "Option::is_none")]
1423    pub status: Option<String>,
1424    /// Resume STRICTLY AFTER this audit id, in the read's documented order. `None` starts at the
1425    /// newest matching row.
1426    ///
1427    /// This is the value the previous page handed back as
1428    /// [`cursor`](results::SpendsListResult::cursor) — never an id the caller kept for another
1429    /// reason, and never a timestamp. Resuming by time would drop every spend sharing the boundary
1430    /// millisecond.
1431    #[serde(default, skip_serializing_if = "Option::is_none")]
1432    pub after_id: Option<String>,
1433    /// The page size. `None` asks for [`SPENDS_LIST_DEFAULT_LIMIT`].
1434    ///
1435    /// A zero, or a value above [`SPENDS_LIST_MAX_LIMIT`], is REFUSED as `INVALID_PARAMS` rather
1436    /// than clamped — see [`Self::validated`].
1437    #[serde(default, skip_serializing_if = "Option::is_none")]
1438    pub limit: Option<u32>,
1439}
1440
1441impl SpendsListParams {
1442    /// The page size this request asks for, resolving `None` to [`SPENDS_LIST_DEFAULT_LIMIT`].
1443    ///
1444    /// Stated once here so the node and the client cannot resolve the same omitted field to two
1445    /// different numbers.
1446    pub fn effective_limit(&self) -> u32 {
1447        self.limit.unwrap_or(SPENDS_LIST_DEFAULT_LIMIT)
1448    }
1449
1450    /// Check the page bound, or reject as `-32602 INVALID_PARAMS`.
1451    ///
1452    /// `limit: 0` is refused because a page that can hold nothing makes no progress: a caller
1453    /// looping until [`complete`](results::SpendsListResult::complete) would loop forever. A limit
1454    /// above the cap is refused rather than clamped so the caller's model of the page and the node's
1455    /// stay identical.
1456    ///
1457    /// The time window is deliberately NOT validated. `since_ms > until_ms` is a well-formed request
1458    /// for an empty window, and an empty window has an honest answer — no rows — which is a
1459    /// different thing from a malformed request.
1460    pub fn validated(self) -> Result<Self, ControlError> {
1461        if let Some(limit) = self.limit {
1462            if limit == 0 || limit > SPENDS_LIST_MAX_LIMIT {
1463                return Err(ControlError::of(
1464                    ControlErrorCode::InvalidParams,
1465                    SPENDS_LIST_LIMIT_ERROR,
1466                ));
1467            }
1468        }
1469        Ok(self)
1470    }
1471}
1472
1473impl<'de> Deserialize<'de> for SpendsListParams {
1474    /// Validates on the way in, so a node cannot forget to call [`Self::validated`].
1475    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1476    where
1477        D: serde::Deserializer<'de>,
1478    {
1479        #[derive(Deserialize)]
1480        struct Raw {
1481            #[serde(default)]
1482            since_ms: Option<u64>,
1483            #[serde(default)]
1484            until_ms: Option<u64>,
1485            #[serde(default)]
1486            store_id: Option<String>,
1487            #[serde(default)]
1488            kind: Option<String>,
1489            #[serde(default)]
1490            status: Option<String>,
1491            #[serde(default)]
1492            after_id: Option<String>,
1493            #[serde(default)]
1494            limit: Option<u32>,
1495        }
1496        let raw = Raw::deserialize(deserializer)?;
1497        SpendsListParams {
1498            since_ms: raw.since_ms,
1499            until_ms: raw.until_ms,
1500            store_id: raw.store_id,
1501            kind: raw.kind,
1502            status: raw.status,
1503            after_id: raw.after_id,
1504            limit: raw.limit,
1505        }
1506        .validated()
1507        .map_err(serde::de::Error::custom)
1508    }
1509}
1510control_call!(SpendsListParams => ControlMethod::SpendsList, results::SpendsListResult);
1511
1512#[cfg(test)]
1513mod tests {
1514    use super::*;
1515    use crate::traits::build_request;
1516    use serde_json::json;
1517
1518    /// An asset id that is emphatically NOT $DIG, so a round-trip through it cannot be satisfied
1519    /// by an implementation that only ever answers about $DIG.
1520    const OTHER_CAT_HEX: &str = "1c2b3a4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809";
1521
1522    /// The legacy spellings are what an ALREADY-DEPLOYED dig-node and dig-app emit today. This is
1523    /// the load-bearing additive-discipline test (§5.1): if widening the enum ever stops accepting
1524    /// them, every peer built before this release becomes unreadable.
1525    #[test]
1526    fn legacy_xch_and_dig_spellings_still_deserialize() {
1527        assert_eq!(
1528            serde_json::from_value::<Asset>(json!("xch")).unwrap(),
1529            Asset::Xch
1530        );
1531        assert_eq!(
1532            serde_json::from_value::<Asset>(json!("dig")).unwrap(),
1533            Asset::DIG
1534        );
1535    }
1536
1537    /// $DIG keeps EMITTING its legacy token. A newer client talking to an OLDER node must still be
1538    /// understood, and an older node knows only `"xch"`/`"dig"` — so emitting `{"cat":…}` for $DIG
1539    /// would break the compatibility direction the legacy test above cannot see.
1540    #[test]
1541    fn dig_still_serializes_to_its_legacy_token() {
1542        assert_eq!(serde_json::to_value(Asset::DIG).unwrap(), json!("dig"));
1543        assert_eq!(serde_json::to_value(Asset::Xch).unwrap(), json!("xch"));
1544    }
1545
1546    /// The new capability: an arbitrary CAT, named by asset id, survives a full round-trip.
1547    #[test]
1548    fn an_arbitrary_cat_round_trips_by_asset_id() {
1549        let asset = Asset::Cat(AssetId::from_hex(OTHER_CAT_HEX).unwrap());
1550        let wire = serde_json::to_value(asset).unwrap();
1551        assert_eq!(wire, json!({ "cat": OTHER_CAT_HEX }));
1552        assert_eq!(serde_json::from_value::<Asset>(wire).unwrap(), asset);
1553    }
1554
1555    /// $DIG has exactly ONE value, however it was spelled on the wire.
1556    ///
1557    /// This is the test that rules out a three-variant `{Xch, Dig, Cat(id)}`, where
1558    /// `Dig != Cat(DIG_ASSET_ID)` and a balance filtered by one spelling silently omits the coins
1559    /// carrying the other — a wallet reporting half a balance as if it were the whole.
1560    #[test]
1561    fn dig_spelled_either_way_is_one_and_the_same_value() {
1562        let via_token: Asset = serde_json::from_value(json!("dig")).unwrap();
1563        let via_asset_id: Asset =
1564            serde_json::from_value(json!({ "cat": Asset::DIG_ASSET_ID_HEX })).unwrap();
1565        assert_eq!(via_token, via_asset_id);
1566        assert_eq!(via_token, Asset::DIG);
1567        assert!(via_asset_id.is_dig());
1568    }
1569
1570    /// The 64-hex length is a published bound, so it is pinned from BOTH sides: one nibble short
1571    /// and one nibble long must both fail, and exactly 64 must pass.
1572    #[test]
1573    fn asset_id_hex_length_is_bounded_on_both_sides() {
1574        assert!(AssetId::from_hex(&"a".repeat(63)).is_err());
1575        assert!(AssetId::from_hex(&"a".repeat(64)).is_ok());
1576        assert!(AssetId::from_hex(&"a".repeat(65)).is_err());
1577    }
1578
1579    /// Input is tolerant of the two forms a human copies out of a block explorer; output is not.
1580    #[test]
1581    fn asset_id_normalizes_prefix_and_case_but_emits_lowercase_unprefixed() {
1582        let upper = OTHER_CAT_HEX.to_uppercase();
1583        let canonical = AssetId::from_hex(OTHER_CAT_HEX).unwrap();
1584        assert_eq!(AssetId::from_hex(&upper).unwrap(), canonical);
1585        assert_eq!(AssetId::from_hex(&format!("0x{upper}")).unwrap(), canonical);
1586        assert_eq!(canonical.to_hex(), OTHER_CAT_HEX);
1587    }
1588
1589    /// The $DIG asset id is written twice in this file — once as hex for callers, once as bytes so
1590    /// [`Asset::DIG`] can be `const`. A typo in either would make `"dig"` and the tagged form name
1591    /// different tokens, which is precisely the split this design exists to prevent.
1592    #[test]
1593    fn dig_asset_id_hex_and_bytes_are_the_same_id() {
1594        let from_hex = AssetId::from_hex(Asset::DIG_ASSET_ID_HEX).unwrap();
1595        assert_eq!(Asset::DIG.asset_id(), Some(&from_hex));
1596        assert_eq!(from_hex.to_hex(), Asset::DIG_ASSET_ID_HEX);
1597        assert_eq!(Asset::Xch.asset_id(), None);
1598    }
1599
1600    /// A rejection has to say WHICH way the input was wrong, or the caller is left guessing at a
1601    /// value it can see but cannot fix.
1602    #[test]
1603    fn parse_errors_name_the_defect_and_reach_the_wire() {
1604        assert_eq!(
1605            AssetId::from_hex("ab").unwrap_err(),
1606            AssetIdParseError::WrongLength { got: 2 }
1607        );
1608        assert!(AssetIdParseError::WrongLength { got: 2 }
1609            .to_string()
1610            .contains("64 hex characters"));
1611        assert!(AssetIdParseError::NotHex
1612            .to_string()
1613            .contains("non-hexadecimal"));
1614        assert!(AssetId::from_hex(&"3c".repeat(32))
1615            .unwrap()
1616            .to_string()
1617            .starts_with("3c3c"));
1618        // The deserializer surfaces the reason rather than a bare "invalid value".
1619        let err = serde_json::from_value::<Asset>(json!({ "cat": "zz" })).unwrap_err();
1620        assert!(err.to_string().contains("64 hex characters"), "{err}");
1621    }
1622
1623    #[test]
1624    fn malformed_assets_are_rejected_rather_than_guessed_at() {
1625        assert!(AssetId::from_hex(&"z".repeat(64)).is_err());
1626        // An unknown bare token is not silently treated as a CAT name.
1627        assert!(serde_json::from_value::<Asset>(json!("usdc")).is_err());
1628        // The tagged form carries exactly one recognized key.
1629        assert!(serde_json::from_value::<Asset>(json!({})).is_err());
1630        assert!(serde_json::from_value::<Asset>(json!({ "tail": OTHER_CAT_HEX })).is_err());
1631        assert!(serde_json::from_value::<Asset>(json!({ "cat": "ab" })).is_err());
1632    }
1633
1634    /// The params types that CARRY an asset must carry the widened one — the whole point of the
1635    /// change is that these two questions become askable about an arbitrary CAT.
1636    #[test]
1637    fn balance_and_coins_reads_can_name_an_arbitrary_cat() {
1638        let cat = Asset::Cat(AssetId::from_hex(OTHER_CAT_HEX).unwrap());
1639        assert_eq!(
1640            serde_json::to_value(WalletBalanceParams {
1641                address: "xch1exampleaddr".into(),
1642                asset: cat,
1643            })
1644            .unwrap(),
1645            json!({ "address": "xch1exampleaddr", "asset": { "cat": OTHER_CAT_HEX } })
1646        );
1647        assert_eq!(
1648            serde_json::to_value(WalletCoinsParams {
1649                address: "xch1exampleaddr".into(),
1650                asset: cat,
1651            })
1652            .unwrap(),
1653            json!({ "address": "xch1exampleaddr", "asset": { "cat": OTHER_CAT_HEX } })
1654        );
1655    }
1656
1657    #[test]
1658    fn no_param_call_serializes_params_to_empty_object() {
1659        let req = build_request(1.into(), &StatusParams {});
1660        assert_eq!(req.method, "control.status");
1661        assert_eq!(req.params, json!({}));
1662    }
1663
1664    #[test]
1665    fn data_param_call_carries_its_fields() {
1666        let req = build_request(2.into(), &SetCapParams { cap_bytes: 128 });
1667        assert_eq!(req.method, "control.cache.setCap");
1668        assert_eq!(req.params, json!({ "cap_bytes": 128 }));
1669    }
1670
1671    #[test]
1672    fn pause_omits_until_when_indefinite() {
1673        assert_eq!(
1674            serde_json::to_value(PauseParams { until: None }).unwrap(),
1675            json!({})
1676        );
1677        assert_eq!(
1678            serde_json::to_value(PauseParams { until: Some(99) }).unwrap(),
1679            json!({ "until": 99 })
1680        );
1681    }
1682
1683    #[test]
1684    fn method_binding_matches_the_catalog_name() {
1685        assert_eq!(
1686            SetUpstreamParams::METHOD.name(),
1687            "control.config.setUpstream"
1688        );
1689        assert_eq!(RequestParams::METHOD.name(), "pairing.request");
1690        assert_eq!(PollParams::METHOD.name(), "pairing.poll");
1691    }
1692
1693    /// **Two spellings of one address canonicalise to one key — which is what makes `remove` able
1694    /// to find what `add` stored.**
1695    ///
1696    /// The fixture is deliberately not a pair of identical strings: each pair differs in the ways
1697    /// a person actually types an address (case, leading zeroes, an uncompressed run, whitespace),
1698    /// so a canonicaliser that only trimmed would pass the last pair and fail the rest.
1699    #[test]
1700    fn spellings_of_the_same_peer_canonicalise_to_one_key() {
1701        for (typed, also_typed) in [
1702            ("2001:0db8:0000:0000:0000:0000:0000:0001", "2001:DB8::1"),
1703            ("::1", "0:0:0:0:0:0:0:1"),
1704            (" 203.0.113.7 ", "203.0.113.7"),
1705        ] {
1706            let a = canonical_peer_ip(typed).expect("typed form is a literal");
1707            let b = canonical_peer_ip(also_typed).expect("second form is a literal");
1708            assert_eq!(a, b, "{typed} and {also_typed} name one peer");
1709        }
1710        // And the canonical form is the compressed lowercase one, not merely SOME agreed form.
1711        assert_eq!(canonical_peer_ip("2001:DB8:0:0::1").unwrap(), "2001:db8::1");
1712    }
1713
1714    /// **Anything that is not a bare IP literal is REFUSED.**
1715    ///
1716    /// This is the bound on the ban list: `remove {ban: true}` persists a row keyed by this
1717    /// string, so accepting arbitrary text is unbounded at-rest growth for the cost of one call.
1718    /// Each rejected case is one a naive implementation accepts: a hostname resolves, a bracketed
1719    /// form round-trips through some parsers, and `ip:port` is what a person copies out of a log.
1720    #[test]
1721    fn a_peer_ip_that_is_not_a_bare_literal_is_refused() {
1722        for bad in [
1723            "",
1724            "   ",
1725            "node.example.com",
1726            "[2001:db8::1]",
1727            "[2001:db8::1]:8444",
1728            "203.0.113.7:8444",
1729            "203.0.113.0/24",
1730            "not an address",
1731        ] {
1732            let Err(err) = canonical_peer_ip(bad) else {
1733                panic!("{bad:?} must be refused, it was accepted");
1734            };
1735            assert_eq!(
1736                err.code_enum(),
1737                Some(ControlErrorCode::InvalidParams),
1738                "{bad:?} must be an INVALID_PARAMS refusal, not some other failure"
1739            );
1740        }
1741    }
1742
1743    /// **Joining an address to a port brackets IPv6 — the un-bracketed form is a DIFFERENT valid
1744    /// address, so the mistake survives validation.**
1745    ///
1746    /// `::1` + `8444` formatted by hand is `::1:8444`, which parses fine and points somewhere
1747    /// else. The assertion is therefore not merely "it contains brackets": the naive rendering is
1748    /// checked to be a parseable address that is NOT the peer, which is what makes the bug silent.
1749    #[test]
1750    fn joining_a_v6_peer_to_a_port_cannot_produce_a_different_address() {
1751        assert_eq!(chia_peer_endpoint("::1", 8444), "[::1]:8444");
1752        assert_eq!(
1753            chia_peer_endpoint("2001:db8::1", 8444),
1754            "[2001:db8::1]:8444"
1755        );
1756        assert_eq!(chia_peer_endpoint("203.0.113.7", 8444), "203.0.113.7:8444");
1757
1758        let naive = format!("{}:{}", "::1", 8444);
1759        let hijacked: std::net::IpAddr =
1760            naive.parse().expect("the naive join is itself an address");
1761        assert_ne!(
1762            hijacked,
1763            "::1".parse::<std::net::IpAddr>().unwrap(),
1764            "the naive join must be a DIFFERENT address — that is why the helper exists"
1765        );
1766        assert_ne!(chia_peer_endpoint("::1", 8444), naive);
1767    }
1768}
1769
1770/// The default local safety margin, in basis points — `+1%`.
1771///
1772/// The same value as `dig_mirror_collateral::SAFETY_MARGIN_BP_DEFAULT`, restated here rather than
1773/// imported: `dig-mirror-collateral` sits at the SAME crate level as this contract, and a
1774/// same-level dependency is forbidden (CLAUDE.md Appendix B). It is published on the contract so a
1775/// config written before the field existed loads as the default rather than as a zero margin.
1776///
1777/// The default errs HIGH because the failure is asymmetric: under-posting likely costs an epoch's
1778/// rewards, while over-posting costs only the opportunity cost of the locked $DIG.
1779pub const DEFAULT_SAFETY_MARGIN_BP: u64 = 100;
1780
1781/// The largest safety margin a node accepts, in basis points — `10_000`, i.e. +100%.
1782///
1783/// A margin is a cushion against the requirement rising, so doubling the requirement is already far
1784/// past any honest cushion. The bound exists because `.set` is a MONEY-PATH mutation reachable with
1785/// an ordinary paired token: an unbounded `u64` lets a caller commit the operator to locking an
1786/// arbitrary multiple of every store's requirement, and the margin arithmetic saturates rather than
1787/// failing, so an absurd value produces a silently enormous posting instead of an error.
1788pub const MAX_SAFETY_MARGIN_BP: u64 = 10_000;
1789
1790no_params!(
1791    /// `control.collateral.requirement` params (none).
1792    ///
1793    /// The caller supplies no epoch: the answer is the epoch the NODE currently derives, so a
1794    /// caller-named epoch would invite a client to render a requirement for an epoch that is not
1795    /// the one being posted against.
1796    CollateralRequirementParams => ControlMethod::CollateralRequirement,
1797    results::CollateralRequirementResult
1798);
1799no_params!(
1800    /// `control.collateral.margin.get` params (none).
1801    CollateralMarginGetParams => ControlMethod::CollateralMarginGet,
1802    results::CollateralMarginResult
1803);
1804
1805/// `control.collateral.margin.set` params.
1806#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1807pub struct CollateralMarginSetParams {
1808    /// The margin in BASIS POINTS over the requirement (`100` is +1%), at most
1809    /// [`MAX_SAFETY_MARGIN_BP`].
1810    ///
1811    /// Basis points, never a percentage and never a float: it is the unit
1812    /// `dig_mirror_collateral::apply_safety_margin` takes and the unit dig-app `SPEC.md` §3.7b
1813    /// fixes for `collateral.margin_bp`. A 1 bp margin (0.01%) is a legal choice and any conversion
1814    /// to whole percent would erase it.
1815    pub margin_bp: u64,
1816}
1817
1818impl CollateralMarginSetParams {
1819    /// Refuse a margin above [`MAX_SAFETY_MARGIN_BP`] as `-32602 INVALID_PARAMS`.
1820    ///
1821    /// Refused rather than clamped, and the asymmetry with dig-app is deliberate. dig-app CLAMPS a
1822    /// stored margin that exceeds its own ceiling, because refusing a value already on disk would
1823    /// leave the node posting the lower amount it was trying to move away from. This is the
1824    /// opposite situation: a caller is stating an intent right now, and silently applying a
1825    /// different number than the one requested would make a subsequent
1826    /// [`CollateralMarginResult`](crate::results::CollateralMarginResult) disagree with what the
1827    /// caller believes it set — on the money path.
1828    pub fn validated(self) -> Result<Self, ControlError> {
1829        if self.margin_bp > MAX_SAFETY_MARGIN_BP {
1830            return Err(ControlError::of(
1831                ControlErrorCode::InvalidParams,
1832                format!(
1833                    "margin_bp must be at most {MAX_SAFETY_MARGIN_BP} basis points (+100%); got {}",
1834                    self.margin_bp
1835                ),
1836            ));
1837        }
1838        Ok(self)
1839    }
1840}
1841control_call!(CollateralMarginSetParams => ControlMethod::CollateralMarginSet, results::CollateralMarginResult);